tailwindcss-injector 1.0.11-alpha.1 → 1.0.12-next.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1 +0,0 @@
1
- "use strict";
package/dist/index.d.ts CHANGED
@@ -1,2 +1 @@
1
-
2
- export { }
1
+ export { };
package/dist/index.js CHANGED
@@ -0,0 +1 @@
1
+ export {};
package/dist/postcss.cjs CHANGED
@@ -1,252 +1,213 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } async function _asyncNullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return await rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }// src/postcss.ts
2
- var _postcss = require('postcss'); var _postcss2 = _interopRequireDefault(_postcss);
3
- var _tailwindcss = require('tailwindcss'); var _tailwindcss2 = _interopRequireDefault(_tailwindcss);
4
- var _tailwindcssconfig = require('tailwindcss-config');
5
-
6
- // src/config.ts
7
- var _process = require('process'); var _process2 = _interopRequireDefault(_process);
8
-
9
- // src/utils.ts
10
-
11
-
12
-
13
-
14
-
15
- var _shared = require('@weapp-tailwindcss/shared');
16
-
17
-
18
-
19
- var _node = require('@weapp-tailwindcss/shared/node');
20
-
21
- // src/config.ts
1
+ //#region \0rolldown/runtime.js
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __copyProps = (to, from, except, desc) => {
9
+ if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
10
+ key = keys[i];
11
+ if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
12
+ get: ((k) => from[k]).bind(null, key),
13
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
14
+ });
15
+ }
16
+ return to;
17
+ };
18
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
19
+ value: mod,
20
+ enumerable: true
21
+ }) : target, mod));
22
+ //#endregion
23
+ let postcss = require("postcss");
24
+ postcss = __toESM(postcss, 1);
25
+ let tailwindcss = require("tailwindcss");
26
+ tailwindcss = __toESM(tailwindcss, 1);
27
+ let tailwindcss_config = require("tailwindcss-config");
28
+ let node_process = require("node:process");
29
+ node_process = __toESM(node_process, 1);
30
+ let node_path = require("node:path");
31
+ node_path = __toESM(node_path, 1);
32
+ let fs_extra = require("fs-extra");
33
+ fs_extra = __toESM(fs_extra, 1);
34
+ let htmlparser2 = require("htmlparser2");
35
+ let magic_string = require("magic-string");
36
+ magic_string = __toESM(magic_string, 1);
37
+ let _weapp_tailwindcss_shared = require("@weapp-tailwindcss/shared");
38
+ let _weapp_tailwindcss_shared_node = require("@weapp-tailwindcss/shared/node");
39
+ //#region src/config.ts
22
40
  function getDefaultConfig() {
23
- return {
24
- filter: () => true,
25
- config: void 0,
26
- // 倒叙插入
27
- directiveParams: ["utilities", "components"],
28
- cwd: _process2.default.cwd(),
29
- extensions: ["wxml", "js", "ts"],
30
- // 处理 @import 与 @use(SCSS)
31
- insertAfterAtRulesNames: ["import", "use"],
32
- insertAfterComments: ["@import"]
33
- };
41
+ return {
42
+ filter: () => true,
43
+ config: void 0,
44
+ directiveParams: ["utilities", "components"],
45
+ cwd: node_process.default.cwd(),
46
+ extensions: [
47
+ "wxml",
48
+ "js",
49
+ "ts"
50
+ ],
51
+ insertAfterAtRulesNames: ["import", "use"],
52
+ insertAfterComments: ["@import"]
53
+ };
34
54
  }
35
55
  function getConfig(options) {
36
- return _shared.defuOverrideArray.call(void 0, options, getDefaultConfig());
56
+ return (0, _weapp_tailwindcss_shared.defuOverrideArray)(options, getDefaultConfig());
37
57
  }
38
-
39
- // src/constants.ts
40
- var postcssPlugin = "postcss-tailwindcss-injector";
41
-
42
- // src/wxml.ts
43
- var _path = require('path'); var _path2 = _interopRequireDefault(_path);
44
- var _fsextra = require('fs-extra'); var _fsextra2 = _interopRequireDefault(_fsextra);
45
- var _htmlparser2 = require('htmlparser2');
46
- var _magicstring = require('magic-string'); var _magicstring2 = _interopRequireDefault(_magicstring);
47
- var hashMap = /* @__PURE__ */ new Map();
48
- var depsMap = /* @__PURE__ */ new Map();
49
- var srcImportTagsMap = {
50
- // audio: ['src', 'poster'],
51
- // video: ['src', 'poster'],
52
- // image: ['src'],
53
- // 参考:https://developers.weixin.qq.com/miniprogram/dev/reference/wxs/01wxs-module.html
54
- // wxs: ['src'],
55
- // 参考:https://developers.weixin.qq.com/miniprogram/dev/reference/wxml/import.html
56
- import: ["src"],
57
- include: ["src"]
58
+ //#endregion
59
+ //#region src/constants.ts
60
+ const postcssPlugin = "postcss-tailwindcss-injector";
61
+ //#endregion
62
+ //#region src/wxml.ts
63
+ const hashMap = /* @__PURE__ */ new Map();
64
+ const depsMap = /* @__PURE__ */ new Map();
65
+ const srcImportTagsMap = {
66
+ import: ["src"],
67
+ include: ["src"]
58
68
  };
59
69
  function processWxml(wxml) {
60
- const ms = new (0, _magicstring2.default)(wxml.toString());
61
- const deps = [];
62
- let currentTagName = "";
63
- let importAttrs;
64
- let attrs = {};
65
- const parser = new (0, _htmlparser2.Parser)(
66
- {
67
- onopentagname(name) {
68
- currentTagName = name;
69
- importAttrs = srcImportTagsMap[currentTagName];
70
- },
71
- onattribute(name, value, quote) {
72
- attrs[name] = value;
73
- if (importAttrs) {
74
- for (const attrName of importAttrs) {
75
- if (attrName === name) {
76
- deps.push({
77
- name,
78
- value,
79
- quote,
80
- tagName: currentTagName,
81
- start: parser.startIndex,
82
- end: parser.endIndex,
83
- attrs
84
- });
85
- }
86
- }
87
- }
88
- },
89
- onclosetag() {
90
- currentTagName = "";
91
- attrs = {};
92
- importAttrs = void 0;
93
- }
94
- },
95
- {
96
- lowerCaseTags: false,
97
- xmlMode: true
98
- }
99
- );
100
- parser.write(
101
- ms.original
102
- );
103
- parser.end();
104
- return deps;
70
+ const ms = new magic_string.default(wxml.toString());
71
+ const deps = [];
72
+ let currentTagName = "";
73
+ let importAttrs;
74
+ let attrs = {};
75
+ const parser = new htmlparser2.Parser({
76
+ onopentagname(name) {
77
+ currentTagName = name;
78
+ importAttrs = srcImportTagsMap[currentTagName];
79
+ },
80
+ onattribute(name, value, quote) {
81
+ attrs[name] = value;
82
+ if (importAttrs) {
83
+ for (const attrName of importAttrs) if (attrName === name) deps.push({
84
+ name,
85
+ value,
86
+ quote,
87
+ tagName: currentTagName,
88
+ start: parser.startIndex,
89
+ end: parser.endIndex,
90
+ attrs
91
+ });
92
+ }
93
+ },
94
+ onclosetag() {
95
+ currentTagName = "";
96
+ attrs = {};
97
+ importAttrs = void 0;
98
+ }
99
+ }, {
100
+ lowerCaseTags: false,
101
+ xmlMode: true
102
+ });
103
+ parser.write(ms.original);
104
+ parser.end();
105
+ return deps;
105
106
  }
106
107
  async function getDep(filepath, set) {
107
- if (await _fsextra2.default.exists(filepath)) {
108
- const dirname = _path2.default.dirname(filepath);
109
- set.add(filepath);
110
- const wxml = await _fsextra2.default.readFile(filepath, "utf8");
111
- const hash = _node.md5.call(void 0, wxml);
112
- const oldHash = hashMap.get(filepath);
113
- const isChanged = hash !== oldHash;
114
- let deps = [];
115
- const cacheDeps = depsMap.get(filepath);
116
- if (isChanged || !cacheDeps) {
117
- hashMap.set(filepath, hash);
118
- deps = await processWxml(wxml);
119
- depsMap.set(filepath, deps);
120
- } else {
121
- deps = cacheDeps;
122
- }
123
- for (const { value } of deps) {
124
- const p = _path2.default.resolve(dirname, value);
125
- if (!set.has(p)) {
126
- await getDep(p, set);
127
- }
128
- }
129
- }
108
+ if (await fs_extra.default.exists(filepath)) {
109
+ const dirname = node_path.default.dirname(filepath);
110
+ set.add(filepath);
111
+ const wxml = await fs_extra.default.readFile(filepath, "utf8");
112
+ const hash = (0, _weapp_tailwindcss_shared_node.md5)(wxml);
113
+ const isChanged = hash !== hashMap.get(filepath);
114
+ let deps = [];
115
+ const cacheDeps = depsMap.get(filepath);
116
+ if (isChanged || !cacheDeps) {
117
+ hashMap.set(filepath, hash);
118
+ deps = await processWxml(wxml);
119
+ depsMap.set(filepath, deps);
120
+ } else deps = cacheDeps;
121
+ for (const { value } of deps) {
122
+ const p = node_path.default.resolve(dirname, value);
123
+ if (!set.has(p)) await getDep(p, set);
124
+ }
125
+ }
130
126
  }
131
127
  async function getDepFiles(file) {
132
- const set = /* @__PURE__ */ new Set();
133
- await getDep(file, set);
134
- return set;
128
+ const set = /* @__PURE__ */ new Set();
129
+ await getDep(file, set);
130
+ return set;
135
131
  }
136
-
137
- // src/postcss.ts
138
- var configCache = /* @__PURE__ */ new Map();
132
+ //#endregion
133
+ //#region src/postcss.ts
134
+ const configCache = /* @__PURE__ */ new Map();
139
135
  async function loadTailwindConfigOnce(cwd, configPath) {
140
- const cacheKey = `${cwd}::${configPath}`;
141
- let cached = configCache.get(cacheKey);
142
- if (!cached) {
143
- cached = _tailwindcssconfig.loadConfig.call(void 0, {
144
- cwd,
145
- config: configPath
146
- }).then((result) => _optionalChain([result, 'optionalAccess', _ => _.config]));
147
- configCache.set(cacheKey, cached);
148
- }
149
- return cached;
136
+ const cacheKey = `${cwd}::${configPath}`;
137
+ let cached = configCache.get(cacheKey);
138
+ if (!cached) {
139
+ cached = (0, tailwindcss_config.loadConfig)({
140
+ cwd,
141
+ config: configPath
142
+ }).then((result) => result?.config);
143
+ configCache.set(cacheKey, cached);
144
+ }
145
+ return cached;
150
146
  }
151
147
  function cloneConfig(config) {
152
- if (!config) {
153
- return config;
154
- }
155
- return {
156
- ...config
157
- };
148
+ if (!config) return config;
149
+ return { ...config };
158
150
  }
159
151
  async function resolveTailwindConfig(config, cwd, sourceInput) {
160
- if (!config) {
161
- return void 0;
162
- }
163
- const resolved = typeof config === "function" ? config(sourceInput) : config;
164
- if (typeof resolved === "string") {
165
- const loaded = await loadTailwindConfigOnce(cwd, resolved);
166
- return cloneConfig(loaded);
167
- }
168
- return cloneConfig(resolved);
152
+ if (!config) return;
153
+ const resolved = typeof config === "function" ? config(sourceInput) : config;
154
+ if (typeof resolved === "string") return cloneConfig(await loadTailwindConfigOnce(cwd, resolved));
155
+ return cloneConfig(resolved);
169
156
  }
170
- var creator = (options) => {
171
- const { config, filter, directiveParams, cwd, extensions, insertAfterAtRulesNames, insertAfterComments } = getConfig(options);
172
- const extensionsGlob = `{${extensions.join(",")}}`;
173
- return {
174
- postcssPlugin,
175
- plugins: [
176
- {
177
- postcssPlugin: `${postcssPlugin}:post`,
178
- async Once(root, helpers) {
179
- const sourceInput = _optionalChain([root, 'access', _2 => _2.source, 'optionalAccess', _3 => _3.input]);
180
- if (filter(sourceInput)) {
181
- const nodes = _nullishCoalesce(root.nodes, () => ( []));
182
- let atruleAnchorIndex = -1;
183
- let commentAnchorIndex = -1;
184
- const directivePresence = /* @__PURE__ */ new Set();
185
- nodes.forEach((node, index) => {
186
- if (node.type === "atrule") {
187
- const nameMatches = insertAfterAtRulesNames.includes(node.name);
188
- if (nameMatches) {
189
- atruleAnchorIndex = Math.max(atruleAnchorIndex, index);
190
- }
191
- if (typeof node.params === "string") {
192
- directivePresence.add(node.params);
193
- }
194
- } else if (node.type === "comment" && _shared.regExpTest.call(void 0, insertAfterComments, node.text)) {
195
- commentAnchorIndex = Math.max(commentAnchorIndex, index);
196
- }
197
- });
198
- const anchorIndex = Math.max(atruleAnchorIndex, commentAnchorIndex);
199
- const anchorNode = anchorIndex >= 0 ? nodes[anchorIndex] : void 0;
200
- let lastInserted = anchorNode;
201
- for (const params of directiveParams) {
202
- if (!directivePresence.has(params)) {
203
- const atRule = helpers.atRule({ name: "tailwind", params });
204
- if (lastInserted) {
205
- root.insertAfter(lastInserted, atRule);
206
- } else {
207
- root.prepend(atRule);
208
- }
209
- lastInserted = atRule;
210
- directivePresence.add(params);
211
- }
212
- }
213
- if (_optionalChain([sourceInput, 'optionalAccess', _4 => _4.file])) {
214
- const tailwindcssConfig = await _asyncNullishCoalesce(await resolveTailwindConfig(config, cwd, sourceInput), async () => ( { content: [] }));
215
- const basename = _node.removeAllExtensions.call(void 0, sourceInput.file);
216
- const contentEntries = [`${basename}.${extensionsGlob}`];
217
- const deps = await getDepFiles(`${basename}.wxml`);
218
- for (const dep of deps) {
219
- contentEntries.push(`${_node.removeAllExtensions.call(void 0, dep)}.${extensionsGlob}`);
220
- }
221
- const uniqueEntries = [...new Set(contentEntries)];
222
- const { content: existingContent } = tailwindcssConfig;
223
- if (!existingContent || Array.isArray(existingContent)) {
224
- tailwindcssConfig.content = uniqueEntries;
225
- } else if (typeof existingContent === "object" && existingContent !== null) {
226
- const normalizedContent = { ...existingContent };
227
- const currentFiles = normalizedContent.files;
228
- const normalizedFiles = Array.isArray(currentFiles) ? currentFiles : typeof currentFiles === "string" ? [currentFiles] : [];
229
- normalizedContent.files = [.../* @__PURE__ */ new Set([...normalizedFiles, ...uniqueEntries])];
230
- tailwindcssConfig.content = normalizedContent;
231
- } else {
232
- tailwindcssConfig.content = uniqueEntries;
233
- }
234
- await _postcss2.default.call(void 0, [
235
- _tailwindcss2.default.call(void 0, tailwindcssConfig)
236
- ]).process(root, {
237
- from: sourceInput.file
238
- }).async();
239
- }
240
- }
241
- }
242
- }
243
- ]
244
- };
157
+ const creator = (options) => {
158
+ const { config, filter, directiveParams, cwd, extensions, insertAfterAtRulesNames, insertAfterComments } = getConfig(options);
159
+ const extensionsGlob = `{${extensions.join(",")}}`;
160
+ return {
161
+ postcssPlugin,
162
+ plugins: [{
163
+ postcssPlugin: `${postcssPlugin}:post`,
164
+ async Once(root, helpers) {
165
+ const sourceInput = root.source?.input;
166
+ if (filter(sourceInput)) {
167
+ const nodes = root.nodes ?? [];
168
+ let atruleAnchorIndex = -1;
169
+ let commentAnchorIndex = -1;
170
+ const directivePresence = /* @__PURE__ */ new Set();
171
+ nodes.forEach((node, index) => {
172
+ if (node.type === "atrule") {
173
+ if (insertAfterAtRulesNames.includes(node.name)) atruleAnchorIndex = Math.max(atruleAnchorIndex, index);
174
+ if (typeof node.params === "string") directivePresence.add(node.params);
175
+ } else if (node.type === "comment" && (0, _weapp_tailwindcss_shared.regExpTest)(insertAfterComments, node.text)) commentAnchorIndex = Math.max(commentAnchorIndex, index);
176
+ });
177
+ const anchorIndex = Math.max(atruleAnchorIndex, commentAnchorIndex);
178
+ let lastInserted = anchorIndex >= 0 ? nodes[anchorIndex] : void 0;
179
+ for (const params of directiveParams) if (!directivePresence.has(params)) {
180
+ const atRule = helpers.atRule({
181
+ name: "tailwind",
182
+ params
183
+ });
184
+ if (lastInserted) root.insertAfter(lastInserted, atRule);
185
+ else root.prepend(atRule);
186
+ lastInserted = atRule;
187
+ directivePresence.add(params);
188
+ }
189
+ if (sourceInput?.file) {
190
+ const tailwindcssConfig = await resolveTailwindConfig(config, cwd, sourceInput) ?? { content: [] };
191
+ const basename = (0, _weapp_tailwindcss_shared_node.removeAllExtensions)(sourceInput.file);
192
+ const contentEntries = [`${basename}.${extensionsGlob}`];
193
+ const deps = await getDepFiles(`${basename}.wxml`);
194
+ for (const dep of deps) contentEntries.push(`${(0, _weapp_tailwindcss_shared_node.removeAllExtensions)(dep)}.${extensionsGlob}`);
195
+ const uniqueEntries = [...new Set(contentEntries)];
196
+ const { content: existingContent } = tailwindcssConfig;
197
+ if (!existingContent || Array.isArray(existingContent)) tailwindcssConfig.content = uniqueEntries;
198
+ else if (typeof existingContent === "object" && existingContent !== null) {
199
+ const normalizedContent = { ...existingContent };
200
+ const currentFiles = normalizedContent.files;
201
+ normalizedContent.files = [...new Set([...Array.isArray(currentFiles) ? currentFiles : typeof currentFiles === "string" ? [currentFiles] : [], ...uniqueEntries])];
202
+ tailwindcssConfig.content = normalizedContent;
203
+ } else tailwindcssConfig.content = uniqueEntries;
204
+ await (0, postcss.default)([(0, tailwindcss.default)(tailwindcssConfig)]).process(root, { from: sourceInput.file }).async();
205
+ }
206
+ }
207
+ }
208
+ }]
209
+ };
245
210
  };
246
211
  creator.postcss = true;
247
- var postcss_default = creator;
248
-
249
-
250
- exports.default = postcss_default;
251
-
252
- module.exports = exports.default;
212
+ //#endregion
213
+ module.exports = creator;
package/dist/postcss.d.ts CHANGED
@@ -1,17 +1,19 @@
1
- import postcss, { PluginCreator } from 'postcss';
2
- import { Config } from 'tailwindcss';
1
+ import postcss, { PluginCreator } from "postcss";
2
+ import { Config } from "tailwindcss";
3
3
 
4
+ //#region src/types.d.ts
4
5
  type InlineTailwindcssOptions = string | Partial<Config> | undefined;
5
6
  interface Options {
6
- cwd: string;
7
- filter: (input?: postcss.Input) => boolean;
8
- config: InlineTailwindcssOptions | ((input?: postcss.Input) => InlineTailwindcssOptions);
9
- directiveParams: ('base' | 'components' | 'utilities' | 'variants')[];
10
- extensions: string[];
11
- insertAfterAtRulesNames: string[];
12
- insertAfterComments: (string | RegExp)[];
7
+ cwd: string;
8
+ filter: (input?: postcss.Input) => boolean;
9
+ config: InlineTailwindcssOptions | ((input?: postcss.Input) => InlineTailwindcssOptions);
10
+ directiveParams: ('base' | 'components' | 'utilities' | 'variants')[];
11
+ extensions: string[];
12
+ insertAfterAtRulesNames: string[];
13
+ insertAfterComments: (string | RegExp)[];
13
14
  }
14
-
15
+ //#endregion
16
+ //#region src/postcss.d.ts
15
17
  declare const creator: PluginCreator<Partial<Options>>;
16
-
17
- export { type Options, creator as default };
18
+ //#endregion
19
+ export { type Options, creator as default };
package/dist/postcss.js CHANGED
@@ -1,250 +1,185 @@
1
- // src/postcss.ts
2
1
  import postcss from "postcss";
3
2
  import tailwindcss from "tailwindcss";
4
3
  import { loadConfig } from "tailwindcss-config";
5
-
6
- // src/config.ts
7
- import process from "process";
8
-
9
- // src/utils.ts
10
- import {
11
- defu,
12
- defuOverrideArray,
13
- isRegexp,
14
- regExpTest
15
- } from "@weapp-tailwindcss/shared";
16
- import {
17
- md5,
18
- removeAllExtensions
19
- } from "@weapp-tailwindcss/shared/node";
20
-
21
- // src/config.ts
4
+ import process from "node:process";
5
+ import { defuOverrideArray, regExpTest } from "@weapp-tailwindcss/shared";
6
+ import { md5, removeAllExtensions as removeFileExtension } from "@weapp-tailwindcss/shared/node";
7
+ import path from "node:path";
8
+ import fs from "fs-extra";
9
+ import { Parser } from "htmlparser2";
10
+ import MagicString from "magic-string";
11
+ //#region src/config.ts
22
12
  function getDefaultConfig() {
23
- return {
24
- filter: () => true,
25
- config: void 0,
26
- // 倒叙插入
27
- directiveParams: ["utilities", "components"],
28
- cwd: process.cwd(),
29
- extensions: ["wxml", "js", "ts"],
30
- // 处理 @import 与 @use(SCSS)
31
- insertAfterAtRulesNames: ["import", "use"],
32
- insertAfterComments: ["@import"]
33
- };
13
+ return {
14
+ filter: () => true,
15
+ config: void 0,
16
+ directiveParams: ["utilities", "components"],
17
+ cwd: process.cwd(),
18
+ extensions: [
19
+ "wxml",
20
+ "js",
21
+ "ts"
22
+ ],
23
+ insertAfterAtRulesNames: ["import", "use"],
24
+ insertAfterComments: ["@import"]
25
+ };
34
26
  }
35
27
  function getConfig(options) {
36
- return defuOverrideArray(options, getDefaultConfig());
28
+ return defuOverrideArray(options, getDefaultConfig());
37
29
  }
38
-
39
- // src/constants.ts
40
- var postcssPlugin = "postcss-tailwindcss-injector";
41
-
42
- // src/wxml.ts
43
- import path from "path";
44
- import fs from "fs-extra";
45
- import { Parser } from "htmlparser2";
46
- import MagicString from "magic-string";
47
- var hashMap = /* @__PURE__ */ new Map();
48
- var depsMap = /* @__PURE__ */ new Map();
49
- var srcImportTagsMap = {
50
- // audio: ['src', 'poster'],
51
- // video: ['src', 'poster'],
52
- // image: ['src'],
53
- // 参考:https://developers.weixin.qq.com/miniprogram/dev/reference/wxs/01wxs-module.html
54
- // wxs: ['src'],
55
- // 参考:https://developers.weixin.qq.com/miniprogram/dev/reference/wxml/import.html
56
- import: ["src"],
57
- include: ["src"]
30
+ //#endregion
31
+ //#region src/constants.ts
32
+ const postcssPlugin = "postcss-tailwindcss-injector";
33
+ //#endregion
34
+ //#region src/wxml.ts
35
+ const hashMap = /* @__PURE__ */ new Map();
36
+ const depsMap = /* @__PURE__ */ new Map();
37
+ const srcImportTagsMap = {
38
+ import: ["src"],
39
+ include: ["src"]
58
40
  };
59
41
  function processWxml(wxml) {
60
- const ms = new MagicString(wxml.toString());
61
- const deps = [];
62
- let currentTagName = "";
63
- let importAttrs;
64
- let attrs = {};
65
- const parser = new Parser(
66
- {
67
- onopentagname(name) {
68
- currentTagName = name;
69
- importAttrs = srcImportTagsMap[currentTagName];
70
- },
71
- onattribute(name, value, quote) {
72
- attrs[name] = value;
73
- if (importAttrs) {
74
- for (const attrName of importAttrs) {
75
- if (attrName === name) {
76
- deps.push({
77
- name,
78
- value,
79
- quote,
80
- tagName: currentTagName,
81
- start: parser.startIndex,
82
- end: parser.endIndex,
83
- attrs
84
- });
85
- }
86
- }
87
- }
88
- },
89
- onclosetag() {
90
- currentTagName = "";
91
- attrs = {};
92
- importAttrs = void 0;
93
- }
94
- },
95
- {
96
- lowerCaseTags: false,
97
- xmlMode: true
98
- }
99
- );
100
- parser.write(
101
- ms.original
102
- );
103
- parser.end();
104
- return deps;
42
+ const ms = new MagicString(wxml.toString());
43
+ const deps = [];
44
+ let currentTagName = "";
45
+ let importAttrs;
46
+ let attrs = {};
47
+ const parser = new Parser({
48
+ onopentagname(name) {
49
+ currentTagName = name;
50
+ importAttrs = srcImportTagsMap[currentTagName];
51
+ },
52
+ onattribute(name, value, quote) {
53
+ attrs[name] = value;
54
+ if (importAttrs) {
55
+ for (const attrName of importAttrs) if (attrName === name) deps.push({
56
+ name,
57
+ value,
58
+ quote,
59
+ tagName: currentTagName,
60
+ start: parser.startIndex,
61
+ end: parser.endIndex,
62
+ attrs
63
+ });
64
+ }
65
+ },
66
+ onclosetag() {
67
+ currentTagName = "";
68
+ attrs = {};
69
+ importAttrs = void 0;
70
+ }
71
+ }, {
72
+ lowerCaseTags: false,
73
+ xmlMode: true
74
+ });
75
+ parser.write(ms.original);
76
+ parser.end();
77
+ return deps;
105
78
  }
106
79
  async function getDep(filepath, set) {
107
- if (await fs.exists(filepath)) {
108
- const dirname = path.dirname(filepath);
109
- set.add(filepath);
110
- const wxml = await fs.readFile(filepath, "utf8");
111
- const hash = md5(wxml);
112
- const oldHash = hashMap.get(filepath);
113
- const isChanged = hash !== oldHash;
114
- let deps = [];
115
- const cacheDeps = depsMap.get(filepath);
116
- if (isChanged || !cacheDeps) {
117
- hashMap.set(filepath, hash);
118
- deps = await processWxml(wxml);
119
- depsMap.set(filepath, deps);
120
- } else {
121
- deps = cacheDeps;
122
- }
123
- for (const { value } of deps) {
124
- const p = path.resolve(dirname, value);
125
- if (!set.has(p)) {
126
- await getDep(p, set);
127
- }
128
- }
129
- }
80
+ if (await fs.exists(filepath)) {
81
+ const dirname = path.dirname(filepath);
82
+ set.add(filepath);
83
+ const wxml = await fs.readFile(filepath, "utf8");
84
+ const hash = md5(wxml);
85
+ const isChanged = hash !== hashMap.get(filepath);
86
+ let deps = [];
87
+ const cacheDeps = depsMap.get(filepath);
88
+ if (isChanged || !cacheDeps) {
89
+ hashMap.set(filepath, hash);
90
+ deps = await processWxml(wxml);
91
+ depsMap.set(filepath, deps);
92
+ } else deps = cacheDeps;
93
+ for (const { value } of deps) {
94
+ const p = path.resolve(dirname, value);
95
+ if (!set.has(p)) await getDep(p, set);
96
+ }
97
+ }
130
98
  }
131
99
  async function getDepFiles(file) {
132
- const set = /* @__PURE__ */ new Set();
133
- await getDep(file, set);
134
- return set;
100
+ const set = /* @__PURE__ */ new Set();
101
+ await getDep(file, set);
102
+ return set;
135
103
  }
136
-
137
- // src/postcss.ts
138
- var configCache = /* @__PURE__ */ new Map();
104
+ //#endregion
105
+ //#region src/postcss.ts
106
+ const configCache = /* @__PURE__ */ new Map();
139
107
  async function loadTailwindConfigOnce(cwd, configPath) {
140
- const cacheKey = `${cwd}::${configPath}`;
141
- let cached = configCache.get(cacheKey);
142
- if (!cached) {
143
- cached = loadConfig({
144
- cwd,
145
- config: configPath
146
- }).then((result) => result?.config);
147
- configCache.set(cacheKey, cached);
148
- }
149
- return cached;
108
+ const cacheKey = `${cwd}::${configPath}`;
109
+ let cached = configCache.get(cacheKey);
110
+ if (!cached) {
111
+ cached = loadConfig({
112
+ cwd,
113
+ config: configPath
114
+ }).then((result) => result?.config);
115
+ configCache.set(cacheKey, cached);
116
+ }
117
+ return cached;
150
118
  }
151
119
  function cloneConfig(config) {
152
- if (!config) {
153
- return config;
154
- }
155
- return {
156
- ...config
157
- };
120
+ if (!config) return config;
121
+ return { ...config };
158
122
  }
159
123
  async function resolveTailwindConfig(config, cwd, sourceInput) {
160
- if (!config) {
161
- return void 0;
162
- }
163
- const resolved = typeof config === "function" ? config(sourceInput) : config;
164
- if (typeof resolved === "string") {
165
- const loaded = await loadTailwindConfigOnce(cwd, resolved);
166
- return cloneConfig(loaded);
167
- }
168
- return cloneConfig(resolved);
124
+ if (!config) return;
125
+ const resolved = typeof config === "function" ? config(sourceInput) : config;
126
+ if (typeof resolved === "string") return cloneConfig(await loadTailwindConfigOnce(cwd, resolved));
127
+ return cloneConfig(resolved);
169
128
  }
170
- var creator = (options) => {
171
- const { config, filter, directiveParams, cwd, extensions, insertAfterAtRulesNames, insertAfterComments } = getConfig(options);
172
- const extensionsGlob = `{${extensions.join(",")}}`;
173
- return {
174
- postcssPlugin,
175
- plugins: [
176
- {
177
- postcssPlugin: `${postcssPlugin}:post`,
178
- async Once(root, helpers) {
179
- const sourceInput = root.source?.input;
180
- if (filter(sourceInput)) {
181
- const nodes = root.nodes ?? [];
182
- let atruleAnchorIndex = -1;
183
- let commentAnchorIndex = -1;
184
- const directivePresence = /* @__PURE__ */ new Set();
185
- nodes.forEach((node, index) => {
186
- if (node.type === "atrule") {
187
- const nameMatches = insertAfterAtRulesNames.includes(node.name);
188
- if (nameMatches) {
189
- atruleAnchorIndex = Math.max(atruleAnchorIndex, index);
190
- }
191
- if (typeof node.params === "string") {
192
- directivePresence.add(node.params);
193
- }
194
- } else if (node.type === "comment" && regExpTest(insertAfterComments, node.text)) {
195
- commentAnchorIndex = Math.max(commentAnchorIndex, index);
196
- }
197
- });
198
- const anchorIndex = Math.max(atruleAnchorIndex, commentAnchorIndex);
199
- const anchorNode = anchorIndex >= 0 ? nodes[anchorIndex] : void 0;
200
- let lastInserted = anchorNode;
201
- for (const params of directiveParams) {
202
- if (!directivePresence.has(params)) {
203
- const atRule = helpers.atRule({ name: "tailwind", params });
204
- if (lastInserted) {
205
- root.insertAfter(lastInserted, atRule);
206
- } else {
207
- root.prepend(atRule);
208
- }
209
- lastInserted = atRule;
210
- directivePresence.add(params);
211
- }
212
- }
213
- if (sourceInput?.file) {
214
- const tailwindcssConfig = await resolveTailwindConfig(config, cwd, sourceInput) ?? { content: [] };
215
- const basename = removeAllExtensions(sourceInput.file);
216
- const contentEntries = [`${basename}.${extensionsGlob}`];
217
- const deps = await getDepFiles(`${basename}.wxml`);
218
- for (const dep of deps) {
219
- contentEntries.push(`${removeAllExtensions(dep)}.${extensionsGlob}`);
220
- }
221
- const uniqueEntries = [...new Set(contentEntries)];
222
- const { content: existingContent } = tailwindcssConfig;
223
- if (!existingContent || Array.isArray(existingContent)) {
224
- tailwindcssConfig.content = uniqueEntries;
225
- } else if (typeof existingContent === "object" && existingContent !== null) {
226
- const normalizedContent = { ...existingContent };
227
- const currentFiles = normalizedContent.files;
228
- const normalizedFiles = Array.isArray(currentFiles) ? currentFiles : typeof currentFiles === "string" ? [currentFiles] : [];
229
- normalizedContent.files = [.../* @__PURE__ */ new Set([...normalizedFiles, ...uniqueEntries])];
230
- tailwindcssConfig.content = normalizedContent;
231
- } else {
232
- tailwindcssConfig.content = uniqueEntries;
233
- }
234
- await postcss([
235
- tailwindcss(tailwindcssConfig)
236
- ]).process(root, {
237
- from: sourceInput.file
238
- }).async();
239
- }
240
- }
241
- }
242
- }
243
- ]
244
- };
129
+ const creator = (options) => {
130
+ const { config, filter, directiveParams, cwd, extensions, insertAfterAtRulesNames, insertAfterComments } = getConfig(options);
131
+ const extensionsGlob = `{${extensions.join(",")}}`;
132
+ return {
133
+ postcssPlugin,
134
+ plugins: [{
135
+ postcssPlugin: `${postcssPlugin}:post`,
136
+ async Once(root, helpers) {
137
+ const sourceInput = root.source?.input;
138
+ if (filter(sourceInput)) {
139
+ const nodes = root.nodes ?? [];
140
+ let atruleAnchorIndex = -1;
141
+ let commentAnchorIndex = -1;
142
+ const directivePresence = /* @__PURE__ */ new Set();
143
+ nodes.forEach((node, index) => {
144
+ if (node.type === "atrule") {
145
+ if (insertAfterAtRulesNames.includes(node.name)) atruleAnchorIndex = Math.max(atruleAnchorIndex, index);
146
+ if (typeof node.params === "string") directivePresence.add(node.params);
147
+ } else if (node.type === "comment" && regExpTest(insertAfterComments, node.text)) commentAnchorIndex = Math.max(commentAnchorIndex, index);
148
+ });
149
+ const anchorIndex = Math.max(atruleAnchorIndex, commentAnchorIndex);
150
+ let lastInserted = anchorIndex >= 0 ? nodes[anchorIndex] : void 0;
151
+ for (const params of directiveParams) if (!directivePresence.has(params)) {
152
+ const atRule = helpers.atRule({
153
+ name: "tailwind",
154
+ params
155
+ });
156
+ if (lastInserted) root.insertAfter(lastInserted, atRule);
157
+ else root.prepend(atRule);
158
+ lastInserted = atRule;
159
+ directivePresence.add(params);
160
+ }
161
+ if (sourceInput?.file) {
162
+ const tailwindcssConfig = await resolveTailwindConfig(config, cwd, sourceInput) ?? { content: [] };
163
+ const basename = removeFileExtension(sourceInput.file);
164
+ const contentEntries = [`${basename}.${extensionsGlob}`];
165
+ const deps = await getDepFiles(`${basename}.wxml`);
166
+ for (const dep of deps) contentEntries.push(`${removeFileExtension(dep)}.${extensionsGlob}`);
167
+ const uniqueEntries = [...new Set(contentEntries)];
168
+ const { content: existingContent } = tailwindcssConfig;
169
+ if (!existingContent || Array.isArray(existingContent)) tailwindcssConfig.content = uniqueEntries;
170
+ else if (typeof existingContent === "object" && existingContent !== null) {
171
+ const normalizedContent = { ...existingContent };
172
+ const currentFiles = normalizedContent.files;
173
+ normalizedContent.files = [...new Set([...Array.isArray(currentFiles) ? currentFiles : typeof currentFiles === "string" ? [currentFiles] : [], ...uniqueEntries])];
174
+ tailwindcssConfig.content = normalizedContent;
175
+ } else tailwindcssConfig.content = uniqueEntries;
176
+ await postcss([tailwindcss(tailwindcssConfig)]).process(root, { from: sourceInput.file }).async();
177
+ }
178
+ }
179
+ }
180
+ }]
181
+ };
245
182
  };
246
183
  creator.postcss = true;
247
- var postcss_default = creator;
248
- export {
249
- postcss_default as default
250
- };
184
+ //#endregion
185
+ export { creator as default };
package/package.json CHANGED
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "name": "tailwindcss-injector",
3
3
  "type": "module",
4
- "version": "1.0.11-alpha.1",
5
- "description": "tsup(esbuild) build package template",
4
+ "version": "1.0.12-next.0",
5
+ "description": "tsdown build package template",
6
6
  "author": "ice breaker <1324318532@qq.com>",
7
7
  "license": "MIT",
8
8
  "repository": {
@@ -37,14 +37,14 @@
37
37
  "fs-extra": "^11.3.4",
38
38
  "htmlparser2": "^10.1.0",
39
39
  "magic-string": "^0.30.21",
40
- "postcss": "^8.5.8",
40
+ "postcss": "^8.5.13",
41
41
  "tailwindcss": "^3.4.19",
42
- "@weapp-tailwindcss/shared": "1.1.3-alpha.1",
43
- "tailwindcss-config": "1.1.5-alpha.1"
42
+ "@weapp-tailwindcss/shared": "1.1.3",
43
+ "tailwindcss-config": "1.1.6-next.0"
44
44
  },
45
45
  "scripts": {
46
- "dev": "tsup --watch --sourcemap",
47
- "build": "tsup",
46
+ "dev": "tsdown --watch --sourcemap",
47
+ "build": "tsdown",
48
48
  "test": "vitest run",
49
49
  "test:dev": "vitest",
50
50
  "release": "pnpm publish",
package/dist/index.d.cts DELETED
@@ -1,2 +0,0 @@
1
-
2
- export { }
@@ -1,19 +0,0 @@
1
- import postcss, { PluginCreator } from 'postcss';
2
- import { Config } from 'tailwindcss';
3
-
4
- type InlineTailwindcssOptions = string | Partial<Config> | undefined;
5
- interface Options {
6
- cwd: string;
7
- filter: (input?: postcss.Input) => boolean;
8
- config: InlineTailwindcssOptions | ((input?: postcss.Input) => InlineTailwindcssOptions);
9
- directiveParams: ('base' | 'components' | 'utilities' | 'variants')[];
10
- extensions: string[];
11
- insertAfterAtRulesNames: string[];
12
- insertAfterComments: (string | RegExp)[];
13
- }
14
-
15
- declare const creator: PluginCreator<Partial<Options>>;
16
-
17
- // @ts-ignore
18
- export = creator;
19
- export type { Options };