tailwindcss 0.0.0-insiders.eebf529 → 0.0.0-insiders.ef2ebb2

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.
Files changed (227) hide show
  1. package/LICENSE +1 -2
  2. package/README.md +15 -7
  3. package/colors.d.ts +3 -0
  4. package/defaultConfig.d.ts +3 -0
  5. package/defaultTheme.d.ts +4 -0
  6. package/index.css +5 -0
  7. package/lib/cli/build/index.js +57 -0
  8. package/lib/cli/build/plugin.js +433 -0
  9. package/lib/cli/build/utils.js +88 -0
  10. package/lib/cli/build/watching.js +182 -0
  11. package/lib/cli/help/index.js +73 -0
  12. package/lib/cli/index.js +231 -0
  13. package/lib/cli/init/index.js +63 -0
  14. package/lib/cli.js +1 -704
  15. package/lib/corePluginList.js +13 -3
  16. package/lib/corePlugins.js +2399 -1867
  17. package/lib/css/preflight.css +17 -9
  18. package/lib/featureFlags.js +50 -26
  19. package/lib/index.js +1 -31
  20. package/lib/lib/cacheInvalidation.js +92 -0
  21. package/lib/lib/collapseAdjacentRules.js +30 -10
  22. package/lib/lib/collapseDuplicateDeclarations.js +60 -4
  23. package/lib/lib/content.js +207 -0
  24. package/lib/lib/defaultExtractor.js +243 -0
  25. package/lib/lib/detectNesting.js +21 -10
  26. package/lib/lib/evaluateTailwindFunctions.js +117 -50
  27. package/lib/lib/expandApplyAtRules.js +467 -161
  28. package/lib/lib/expandTailwindAtRules.js +200 -133
  29. package/lib/lib/findAtConfigPath.js +46 -0
  30. package/lib/lib/generateRules.js +550 -200
  31. package/lib/lib/getModuleDependencies.js +88 -37
  32. package/lib/lib/handleImportAtRules.js +50 -0
  33. package/lib/lib/load-config.js +42 -0
  34. package/lib/lib/normalizeTailwindDirectives.js +36 -38
  35. package/lib/lib/offsets.js +306 -0
  36. package/lib/lib/partitionApplyAtRules.js +58 -0
  37. package/lib/lib/regex.js +74 -0
  38. package/lib/lib/remap-bitfield.js +89 -0
  39. package/lib/lib/resolveDefaultsAtRules.js +98 -58
  40. package/lib/lib/setupContextUtils.js +767 -325
  41. package/lib/lib/setupTrackingContext.js +71 -75
  42. package/lib/lib/sharedState.js +70 -10
  43. package/lib/lib/substituteScreenAtRules.js +14 -10
  44. package/lib/plugin.js +166 -0
  45. package/{nesting → lib/postcss-plugins/nesting}/README.md +2 -2
  46. package/lib/postcss-plugins/nesting/index.js +21 -0
  47. package/lib/postcss-plugins/nesting/plugin.js +89 -0
  48. package/lib/processTailwindFeatures.js +39 -26
  49. package/lib/public/colors.js +272 -246
  50. package/lib/public/create-plugin.js +9 -5
  51. package/lib/public/default-config.js +10 -6
  52. package/lib/public/default-theme.js +10 -6
  53. package/lib/public/load-config.js +12 -0
  54. package/lib/public/resolve-config.js +11 -6
  55. package/lib/util/applyImportantSelector.js +36 -0
  56. package/lib/util/bigSign.js +6 -1
  57. package/lib/util/buildMediaQuery.js +13 -6
  58. package/lib/util/cloneDeep.js +9 -6
  59. package/lib/util/cloneNodes.js +23 -3
  60. package/lib/util/color.js +70 -38
  61. package/lib/util/colorNames.js +752 -0
  62. package/lib/util/configurePlugins.js +7 -2
  63. package/lib/util/createPlugin.js +8 -6
  64. package/lib/util/createUtilityPlugin.js +16 -16
  65. package/lib/util/dataTypes.js +182 -111
  66. package/lib/util/defaults.js +14 -3
  67. package/lib/util/escapeClassName.js +13 -8
  68. package/lib/util/escapeCommas.js +7 -2
  69. package/lib/util/flattenColorPalette.js +11 -12
  70. package/lib/util/formatVariantSelector.js +228 -151
  71. package/lib/util/getAllConfigs.js +33 -12
  72. package/lib/util/hashConfig.js +9 -4
  73. package/lib/util/isKeyframeRule.js +7 -2
  74. package/lib/util/isPlainObject.js +7 -2
  75. package/lib/util/{isValidArbitraryValue.js → isSyntacticallyValidPropertyValue.js} +25 -15
  76. package/lib/util/log.js +44 -13
  77. package/lib/util/nameClass.js +27 -10
  78. package/lib/util/negateValue.js +25 -8
  79. package/lib/util/normalizeConfig.js +167 -67
  80. package/lib/util/normalizeScreens.js +128 -11
  81. package/lib/util/parseAnimationValue.js +44 -40
  82. package/lib/util/parseBoxShadowValue.js +34 -23
  83. package/lib/util/parseDependency.js +39 -55
  84. package/lib/util/parseGlob.js +36 -0
  85. package/lib/util/parseObjectStyles.js +15 -10
  86. package/lib/util/pluginUtils.js +157 -69
  87. package/lib/util/prefixSelector.js +30 -12
  88. package/lib/util/pseudoElements.js +209 -0
  89. package/lib/util/removeAlphaVariables.js +31 -0
  90. package/lib/util/resolveConfig.js +101 -79
  91. package/lib/util/resolveConfigPath.js +30 -12
  92. package/lib/util/responsive.js +11 -6
  93. package/lib/util/splitAtTopLevelOnly.js +51 -0
  94. package/lib/util/tap.js +6 -1
  95. package/lib/util/toColorValue.js +7 -3
  96. package/lib/util/toPath.js +26 -3
  97. package/lib/util/transformThemeValue.js +40 -30
  98. package/lib/util/validateConfig.js +48 -0
  99. package/lib/util/validateFormalSyntax.js +26 -0
  100. package/lib/util/withAlphaVariable.js +27 -15
  101. package/lib/value-parser/LICENSE +22 -0
  102. package/lib/value-parser/README.md +3 -0
  103. package/lib/value-parser/index.d.js +2 -0
  104. package/lib/value-parser/index.js +22 -0
  105. package/lib/value-parser/parse.js +259 -0
  106. package/lib/value-parser/stringify.js +38 -0
  107. package/lib/value-parser/unit.js +86 -0
  108. package/lib/value-parser/walk.js +16 -0
  109. package/loadConfig.d.ts +4 -0
  110. package/loadConfig.js +2 -0
  111. package/nesting/index.js +2 -12
  112. package/package.json +63 -62
  113. package/plugin.d.ts +11 -0
  114. package/resolveConfig.d.ts +12 -0
  115. package/scripts/generate-types.js +105 -0
  116. package/scripts/release-channel.js +18 -0
  117. package/scripts/release-notes.js +21 -0
  118. package/scripts/type-utils.js +27 -0
  119. package/src/cli/build/index.js +53 -0
  120. package/src/cli/build/plugin.js +476 -0
  121. package/src/cli/build/utils.js +76 -0
  122. package/src/cli/build/watching.js +229 -0
  123. package/src/cli/help/index.js +70 -0
  124. package/src/cli/index.js +217 -0
  125. package/src/cli/init/index.js +79 -0
  126. package/src/cli.js +1 -766
  127. package/src/corePluginList.js +1 -1
  128. package/src/corePlugins.js +800 -296
  129. package/src/css/preflight.css +17 -9
  130. package/src/featureFlags.js +20 -6
  131. package/src/index.js +1 -34
  132. package/src/lib/cacheInvalidation.js +52 -0
  133. package/src/lib/collapseAdjacentRules.js +21 -2
  134. package/src/lib/collapseDuplicateDeclarations.js +66 -1
  135. package/src/lib/content.js +240 -0
  136. package/src/lib/defaultExtractor.js +217 -0
  137. package/src/lib/detectNesting.js +9 -1
  138. package/src/lib/evaluateTailwindFunctions.js +83 -9
  139. package/src/lib/expandApplyAtRules.js +515 -153
  140. package/src/lib/expandTailwindAtRules.js +147 -86
  141. package/src/lib/findAtConfigPath.js +48 -0
  142. package/src/lib/generateRules.js +541 -147
  143. package/src/lib/getModuleDependencies.js +70 -30
  144. package/src/lib/handleImportAtRules.js +34 -0
  145. package/src/lib/load-config.ts +31 -0
  146. package/src/lib/normalizeTailwindDirectives.js +5 -26
  147. package/src/lib/offsets.js +373 -0
  148. package/src/lib/partitionApplyAtRules.js +52 -0
  149. package/src/lib/regex.js +74 -0
  150. package/src/lib/remap-bitfield.js +82 -0
  151. package/src/lib/resolveDefaultsAtRules.js +59 -17
  152. package/src/lib/setupContextUtils.js +693 -176
  153. package/src/lib/setupTrackingContext.js +52 -65
  154. package/src/lib/sharedState.js +54 -7
  155. package/src/plugin.js +141 -0
  156. package/src/postcss-plugins/nesting/README.md +42 -0
  157. package/src/postcss-plugins/nesting/index.js +13 -0
  158. package/src/postcss-plugins/nesting/plugin.js +80 -0
  159. package/src/processTailwindFeatures.js +12 -2
  160. package/src/public/colors.js +22 -0
  161. package/src/public/default-config.js +1 -1
  162. package/src/public/default-theme.js +2 -2
  163. package/src/public/load-config.js +2 -0
  164. package/src/util/applyImportantSelector.js +27 -0
  165. package/src/util/buildMediaQuery.js +5 -3
  166. package/src/util/cloneNodes.js +19 -2
  167. package/src/util/color.js +44 -12
  168. package/src/util/colorNames.js +150 -0
  169. package/src/util/dataTypes.js +67 -23
  170. package/src/util/defaults.js +6 -0
  171. package/src/util/formatVariantSelector.js +264 -144
  172. package/src/util/getAllConfigs.js +21 -2
  173. package/src/util/{isValidArbitraryValue.js → isSyntacticallyValidPropertyValue.js} +1 -1
  174. package/src/util/log.js +35 -7
  175. package/src/util/nameClass.js +4 -0
  176. package/src/util/negateValue.js +11 -3
  177. package/src/util/normalizeConfig.js +86 -7
  178. package/src/util/normalizeScreens.js +99 -4
  179. package/src/util/parseBoxShadowValue.js +4 -3
  180. package/src/util/parseDependency.js +37 -42
  181. package/src/util/parseGlob.js +24 -0
  182. package/src/util/pluginUtils.js +118 -23
  183. package/src/util/prefixSelector.js +30 -10
  184. package/src/util/pseudoElements.js +167 -0
  185. package/src/util/removeAlphaVariables.js +24 -0
  186. package/src/util/resolveConfig.js +74 -26
  187. package/src/util/resolveConfigPath.js +12 -1
  188. package/src/util/splitAtTopLevelOnly.js +52 -0
  189. package/src/util/toPath.js +23 -1
  190. package/src/util/transformThemeValue.js +13 -3
  191. package/src/util/validateConfig.js +36 -0
  192. package/src/util/validateFormalSyntax.js +34 -0
  193. package/src/util/withAlphaVariable.js +1 -1
  194. package/src/value-parser/LICENSE +22 -0
  195. package/src/value-parser/README.md +3 -0
  196. package/src/value-parser/index.d.ts +177 -0
  197. package/src/value-parser/index.js +28 -0
  198. package/src/value-parser/parse.js +303 -0
  199. package/src/value-parser/stringify.js +41 -0
  200. package/src/value-parser/unit.js +118 -0
  201. package/src/value-parser/walk.js +18 -0
  202. package/stubs/.gitignore +1 -0
  203. package/stubs/.prettierrc.json +6 -0
  204. package/stubs/{defaultConfig.stub.js → config.full.js} +220 -167
  205. package/stubs/{simpleConfig.stub.js → config.simple.js} +1 -1
  206. package/stubs/{defaultPostCssConfig.stub.js → postcss.config.cjs} +0 -1
  207. package/stubs/postcss.config.js +5 -0
  208. package/stubs/tailwind.config.cjs +2 -0
  209. package/stubs/tailwind.config.js +2 -0
  210. package/stubs/tailwind.config.ts +3 -0
  211. package/types/config.d.ts +369 -0
  212. package/types/generated/.gitkeep +0 -0
  213. package/types/generated/colors.d.ts +298 -0
  214. package/types/generated/corePluginList.d.ts +1 -0
  215. package/types/generated/default-theme.d.ts +372 -0
  216. package/types/index.d.ts +7 -0
  217. package/CHANGELOG.md +0 -1853
  218. package/lib/cli-peer-dependencies.js +0 -15
  219. package/lib/constants.js +0 -37
  220. package/lib/lib/setupWatchingContext.js +0 -288
  221. package/nesting/plugin.js +0 -41
  222. package/peers/index.js +0 -76107
  223. package/scripts/install-integrations.js +0 -27
  224. package/scripts/rebuildFixtures.js +0 -68
  225. package/src/cli-peer-dependencies.js +0 -9
  226. package/src/constants.js +0 -17
  227. package/src/lib/setupWatchingContext.js +0 -311
@@ -0,0 +1,476 @@
1
+ // @ts-check
2
+
3
+ import pkg from '../../../package.json'
4
+ import path from 'path'
5
+ import fs from 'fs'
6
+ import postcss from 'postcss'
7
+ import postcssrc from 'postcss-load-config'
8
+ import browserslist from 'browserslist'
9
+ import lightning, { Features } from 'lightningcss'
10
+ import { lilconfig } from 'lilconfig'
11
+ import loadPlugins from 'postcss-load-config/src/plugins' // Little bit scary, looking at private/internal API
12
+ import loadOptions from 'postcss-load-config/src/options' // Little bit scary, looking at private/internal API
13
+
14
+ import tailwind from '../../processTailwindFeatures'
15
+ import { formatNodes, drainStdin, outputFile } from './utils'
16
+ import { env } from '../../lib/sharedState'
17
+ import resolveConfig from '../../../resolveConfig.js'
18
+ import { parseCandidateFiles } from '../../lib/content.js'
19
+ import { createWatcher } from './watching.js'
20
+ import fastGlob from 'fast-glob'
21
+ import { findAtConfigPath } from '../../lib/findAtConfigPath.js'
22
+ import log from '../../util/log'
23
+ import { loadConfig } from '../../lib/load-config'
24
+ import getModuleDependencies from '../../lib/getModuleDependencies'
25
+ import { validateConfig } from '../../util/validateConfig'
26
+ import { handleImportAtRules } from '../../lib/handleImportAtRules'
27
+ import { flagEnabled } from '../../featureFlags'
28
+
29
+ async function lightningcss(result, { map = true, minify = true } = {}) {
30
+ try {
31
+ let includeFeatures = Features.Nesting
32
+ let excludeFeatures = 0
33
+
34
+ let resolvedBrowsersListConfig = browserslist.findConfig(
35
+ result.opts.from ?? process.cwd()
36
+ )?.defaults
37
+ let defaultBrowsersListConfig = pkg.browserslist
38
+ let browsersListConfig = resolvedBrowsersListConfig ?? defaultBrowsersListConfig
39
+
40
+ if (browsersListConfig.join(',') === defaultBrowsersListConfig.join(',')) {
41
+ includeFeatures |=
42
+ Features.ColorFunction | Features.OklabColors | Features.LabColors | Features.P3Colors
43
+
44
+ excludeFeatures |=
45
+ Features.HexAlphaColors | Features.LogicalProperties | Features.SpaceSeparatedColorNotation
46
+ }
47
+
48
+ let transformed = lightning.transform({
49
+ filename: result.opts.from || 'input.css',
50
+ code: Buffer.from(result.css, 'utf-8'),
51
+ minify,
52
+ sourceMap: result.map === undefined ? map : !!result.map,
53
+ inputSourceMap: result.map ? result.map.toString() : undefined,
54
+ targets: lightning.browserslistToTargets(browserslist(browsersListConfig)),
55
+ drafts: {
56
+ nesting: true,
57
+ },
58
+ include: includeFeatures,
59
+ exclude: excludeFeatures,
60
+ })
61
+
62
+ return Object.assign(result, {
63
+ css: transformed.code.toString('utf8'),
64
+ map: result.map
65
+ ? Object.assign(result.map, {
66
+ toString() {
67
+ return transformed.map?.toString()
68
+ },
69
+ })
70
+ : result.map,
71
+ })
72
+ } catch (err) {
73
+ console.error('Unable to use Lightning CSS. Using raw version instead.')
74
+ console.error(err)
75
+
76
+ return result
77
+ }
78
+ }
79
+
80
+ /**
81
+ *
82
+ * @param {string} [customPostCssPath ]
83
+ * @returns
84
+ */
85
+ async function loadPostCssPlugins(customPostCssPath) {
86
+ let config = customPostCssPath
87
+ ? await (async () => {
88
+ let file = path.resolve(customPostCssPath)
89
+
90
+ // Implementation, see: https://unpkg.com/browse/postcss-load-config@3.1.0/src/index.js
91
+ // @ts-ignore
92
+ let { config = {} } = await lilconfig('postcss').load(file)
93
+ if (typeof config === 'function') {
94
+ config = config()
95
+ } else {
96
+ config = Object.assign({}, config)
97
+ }
98
+
99
+ if (!config.plugins) {
100
+ config.plugins = []
101
+ }
102
+
103
+ return {
104
+ file,
105
+ plugins: loadPlugins(config, file),
106
+ options: loadOptions(config, file),
107
+ }
108
+ })()
109
+ : await postcssrc()
110
+
111
+ let configPlugins = config.plugins
112
+
113
+ let configPluginTailwindIdx = configPlugins.findIndex((plugin) => {
114
+ if (typeof plugin === 'function' && plugin.name === 'tailwindcss') {
115
+ return true
116
+ }
117
+
118
+ if (typeof plugin === 'object' && plugin !== null && plugin.postcssPlugin === 'tailwindcss') {
119
+ return true
120
+ }
121
+
122
+ return false
123
+ })
124
+
125
+ let beforePlugins =
126
+ configPluginTailwindIdx === -1 ? [] : configPlugins.slice(0, configPluginTailwindIdx)
127
+ let afterPlugins =
128
+ configPluginTailwindIdx === -1
129
+ ? configPlugins
130
+ : configPlugins.slice(configPluginTailwindIdx + 1)
131
+
132
+ return [beforePlugins, afterPlugins, config.options]
133
+ }
134
+
135
+ let state = {
136
+ /** @type {any} */
137
+ context: null,
138
+
139
+ /** @type {ReturnType<typeof createWatcher> | null} */
140
+ watcher: null,
141
+
142
+ /** @type {{content: string, extension: string}[]} */
143
+ changedContent: [],
144
+
145
+ /** @type {{config: import('../../../types').Config, dependencies: Set<string>, dispose: Function } | null} */
146
+ configBag: null,
147
+
148
+ contextDependencies: new Set(),
149
+
150
+ /** @type {import('../../lib/content.js').ContentPath[]} */
151
+ contentPaths: [],
152
+
153
+ refreshContentPaths() {
154
+ this.contentPaths = parseCandidateFiles(this.context, this.context?.tailwindConfig)
155
+ },
156
+
157
+ get config() {
158
+ return this.context.tailwindConfig
159
+ },
160
+
161
+ get contentPatterns() {
162
+ return {
163
+ all: this.contentPaths.map((contentPath) => contentPath.pattern),
164
+ dynamic: this.contentPaths
165
+ .filter((contentPath) => contentPath.glob !== undefined)
166
+ .map((contentPath) => contentPath.pattern),
167
+ }
168
+ },
169
+
170
+ loadConfig(configPath, content) {
171
+ if (this.watcher && configPath) {
172
+ this.refreshConfigDependencies()
173
+ }
174
+
175
+ let config = loadConfig(configPath)
176
+ let dependencies = getModuleDependencies(configPath)
177
+ this.configBag = {
178
+ config,
179
+ dependencies,
180
+ dispose() {
181
+ for (let file of dependencies) {
182
+ delete require.cache[require.resolve(file)]
183
+ }
184
+ },
185
+ }
186
+
187
+ this.configBag.config = validateConfig(resolveConfig(this.configBag.config))
188
+
189
+ // Override content files if `--content` has been passed explicitly
190
+ if (content?.length > 0) {
191
+ this.configBag.config.content.files = content
192
+ }
193
+
194
+ return this.configBag.config
195
+ },
196
+
197
+ refreshConfigDependencies() {
198
+ env.DEBUG && console.time('Module dependencies')
199
+ this.configBag?.dispose()
200
+ env.DEBUG && console.timeEnd('Module dependencies')
201
+ },
202
+
203
+ readContentPaths() {
204
+ let content = []
205
+
206
+ // Resolve globs from the content config
207
+ // TODO: When we make the postcss plugin async-capable this can become async
208
+ let files = fastGlob.sync(this.contentPatterns.all)
209
+
210
+ for (let file of files) {
211
+ if (flagEnabled(this.config, 'oxideParser')) {
212
+ content.push({
213
+ file,
214
+ extension: path.extname(file).slice(1),
215
+ })
216
+ } else {
217
+ content.push({
218
+ content: fs.readFileSync(path.resolve(file), 'utf8'),
219
+ extension: path.extname(file).slice(1),
220
+ })
221
+ }
222
+ }
223
+
224
+ // Resolve raw content in the tailwind config
225
+ let rawContent = this.config.content.files.filter((file) => {
226
+ return file !== null && typeof file === 'object'
227
+ })
228
+
229
+ for (let { raw: htmlContent, extension = 'html' } of rawContent) {
230
+ content.push({ content: htmlContent, extension })
231
+ }
232
+
233
+ return content
234
+ },
235
+
236
+ getContext({ createContext, cliConfigPath, root, result, content }) {
237
+ if (this.context) {
238
+ this.context.changedContent = this.changedContent.splice(0)
239
+
240
+ return this.context
241
+ }
242
+
243
+ env.DEBUG && console.time('Searching for config')
244
+ let configPath = findAtConfigPath(root, result) ?? cliConfigPath
245
+ env.DEBUG && console.timeEnd('Searching for config')
246
+
247
+ env.DEBUG && console.time('Loading config')
248
+ let config = this.loadConfig(configPath, content)
249
+ env.DEBUG && console.timeEnd('Loading config')
250
+
251
+ env.DEBUG && console.time('Creating context')
252
+ this.context = createContext(config, [])
253
+ Object.assign(this.context, {
254
+ userConfigPath: configPath,
255
+ })
256
+ env.DEBUG && console.timeEnd('Creating context')
257
+
258
+ env.DEBUG && console.time('Resolving content paths')
259
+ this.refreshContentPaths()
260
+ env.DEBUG && console.timeEnd('Resolving content paths')
261
+
262
+ if (this.watcher) {
263
+ env.DEBUG && console.time('Watch new files')
264
+ this.watcher.refreshWatchedFiles()
265
+ env.DEBUG && console.timeEnd('Watch new files')
266
+ }
267
+
268
+ for (let file of this.readContentPaths()) {
269
+ this.context.changedContent.push(file)
270
+ }
271
+
272
+ return this.context
273
+ },
274
+ }
275
+
276
+ export async function createProcessor(args, cliConfigPath) {
277
+ let input = args['--input']
278
+ let output = args['--output']
279
+ let includePostCss = args['--postcss']
280
+ let customPostCssPath = typeof args['--postcss'] === 'string' ? args['--postcss'] : undefined
281
+
282
+ let [beforePlugins, afterPlugins, postcssOptions] = includePostCss
283
+ ? await loadPostCssPlugins(customPostCssPath)
284
+ : [[], [], {}]
285
+
286
+ beforePlugins.unshift(...handleImportAtRules())
287
+
288
+ if (args['--purge']) {
289
+ log.warn('purge-flag-deprecated', [
290
+ 'The `--purge` flag has been deprecated.',
291
+ 'Please use `--content` instead.',
292
+ ])
293
+
294
+ if (!args['--content']) {
295
+ args['--content'] = args['--purge']
296
+ }
297
+ }
298
+
299
+ let content = args['--content']?.split(/(?<!{[^}]+),/) ?? []
300
+
301
+ let tailwindPlugin = () => {
302
+ return {
303
+ postcssPlugin: 'tailwindcss',
304
+ Once(root, { result }) {
305
+ env.DEBUG && console.time('Compiling CSS')
306
+ tailwind(({ createContext }) => {
307
+ console.error()
308
+ console.error('Rebuilding...')
309
+
310
+ return () => {
311
+ return state.getContext({
312
+ createContext,
313
+ cliConfigPath,
314
+ root,
315
+ result,
316
+ content,
317
+ })
318
+ }
319
+ })(root, result)
320
+ env.DEBUG && console.timeEnd('Compiling CSS')
321
+ },
322
+ }
323
+ }
324
+
325
+ tailwindPlugin.postcss = true
326
+
327
+ let plugins = [
328
+ ...beforePlugins,
329
+ tailwindPlugin,
330
+ !args['--minify'] && formatNodes,
331
+ ...afterPlugins,
332
+ ].filter(Boolean)
333
+
334
+ /** @type {import('postcss').Processor} */
335
+ // @ts-ignore
336
+ let processor = postcss(plugins)
337
+
338
+ async function readInput() {
339
+ // Piping in data, let's drain the stdin
340
+ if (input === '-') {
341
+ return drainStdin()
342
+ }
343
+
344
+ // Input file has been provided
345
+ if (input) {
346
+ return fs.promises.readFile(path.resolve(input), 'utf8')
347
+ }
348
+
349
+ // No input file provided, fallback to default atrules
350
+ return '@tailwind base; @tailwind components; @tailwind utilities'
351
+ }
352
+
353
+ async function build() {
354
+ let start = process.hrtime.bigint()
355
+ let options = {
356
+ ...postcssOptions,
357
+ from: input,
358
+ to: output,
359
+ }
360
+
361
+ return readInput()
362
+ .then((css) => processor.process(css, options))
363
+ .then((result) =>
364
+ lightningcss(result, {
365
+ ...options,
366
+ minify: !!args['--minify'],
367
+ })
368
+ )
369
+ .then((result) => {
370
+ if (!state.watcher) {
371
+ return result
372
+ }
373
+
374
+ env.DEBUG && console.time('Recording PostCSS dependencies')
375
+ for (let message of result.messages) {
376
+ if (message.type === 'dependency') {
377
+ state.contextDependencies.add(message.file)
378
+ }
379
+ }
380
+ env.DEBUG && console.timeEnd('Recording PostCSS dependencies')
381
+
382
+ // TODO: This needs to be in a different spot
383
+ env.DEBUG && console.time('Watch new files')
384
+ state.watcher.refreshWatchedFiles()
385
+ env.DEBUG && console.timeEnd('Watch new files')
386
+
387
+ return result
388
+ })
389
+ .then((result) => {
390
+ if (!output) {
391
+ process.stdout.write(result.css)
392
+ return
393
+ }
394
+
395
+ return Promise.all([
396
+ outputFile(result.opts.to, result.css),
397
+ result.map && outputFile(result.opts.to + '.map', result.map.toString()),
398
+ ])
399
+ })
400
+ .then(() => {
401
+ let end = process.hrtime.bigint()
402
+ console.error()
403
+ console.error('Done in', (end - start) / BigInt(1e6) + 'ms.')
404
+ })
405
+ .then(
406
+ () => {},
407
+ (err) => {
408
+ // TODO: If an initial build fails we can't easily pick up any PostCSS dependencies
409
+ // that were collected before the error occurred
410
+ // The result is not stored on the error so we have to store it externally
411
+ // and pull the messages off of it here somehow
412
+
413
+ // This results in a less than ideal DX because the watcher will not pick up
414
+ // changes to imported CSS if one of them caused an error during the initial build
415
+ // If you fix it and then save the main CSS file so there's no error
416
+ // The watcher will start watching the imported CSS files and will be
417
+ // resilient to future errors.
418
+
419
+ if (state.watcher) {
420
+ console.error(err)
421
+ } else {
422
+ return Promise.reject(err)
423
+ }
424
+ }
425
+ )
426
+ }
427
+
428
+ /**
429
+ * @param {{file: string, content(): Promise<string>, extension: string}[]} changes
430
+ */
431
+ async function parseChanges(changes) {
432
+ return Promise.all(
433
+ changes.map(async (change) => ({
434
+ content: await change.content(),
435
+ extension: change.extension,
436
+ }))
437
+ )
438
+ }
439
+
440
+ if (input !== undefined && input !== '-') {
441
+ state.contextDependencies.add(path.resolve(input))
442
+ }
443
+
444
+ return {
445
+ build,
446
+ watch: async () => {
447
+ state.watcher = createWatcher(args, {
448
+ state,
449
+
450
+ /**
451
+ * @param {{file: string, content(): Promise<string>, extension: string}[]} changes
452
+ */
453
+ async rebuild(changes) {
454
+ let needsNewContext = changes.some((change) => {
455
+ return (
456
+ state.configBag?.dependencies.has(change.file) ||
457
+ state.contextDependencies.has(change.file)
458
+ )
459
+ })
460
+
461
+ if (needsNewContext) {
462
+ state.context = null
463
+ } else {
464
+ for (let change of await parseChanges(changes)) {
465
+ state.changedContent.push(change)
466
+ }
467
+ }
468
+
469
+ return build()
470
+ },
471
+ })
472
+
473
+ await build()
474
+ },
475
+ }
476
+ }
@@ -0,0 +1,76 @@
1
+ // @ts-check
2
+
3
+ import fs from 'fs'
4
+ import path from 'path'
5
+
6
+ export function indentRecursive(node, indent = 0) {
7
+ node.each &&
8
+ node.each((child, i) => {
9
+ if (!child.raws.before || !child.raws.before.trim() || child.raws.before.includes('\n')) {
10
+ child.raws.before = `\n${node.type !== 'rule' && i > 0 ? '\n' : ''}${' '.repeat(indent)}`
11
+ }
12
+ child.raws.after = `\n${' '.repeat(indent)}`
13
+ indentRecursive(child, indent + 1)
14
+ })
15
+ }
16
+
17
+ export function formatNodes(root) {
18
+ indentRecursive(root)
19
+ if (root.first) {
20
+ root.first.raws.before = ''
21
+ }
22
+ }
23
+
24
+ /**
25
+ * When rapidly saving files atomically a couple of situations can happen:
26
+ * - The file is missing since the external program has deleted it by the time we've gotten around to reading it from the earlier save.
27
+ * - The file is being written to by the external program by the time we're going to read it and is thus treated as busy because a lock is held.
28
+ *
29
+ * To work around this we retry reading the file a handful of times with a delay between each attempt
30
+ *
31
+ * @param {string} path
32
+ * @param {number} tries
33
+ * @returns {Promise<string | undefined>}
34
+ * @throws {Error} If the file is still missing or busy after the specified number of tries
35
+ */
36
+ export async function readFileWithRetries(path, tries = 5) {
37
+ for (let n = 0; n <= tries; n++) {
38
+ try {
39
+ return await fs.promises.readFile(path, 'utf8')
40
+ } catch (err) {
41
+ if (n !== tries) {
42
+ if (err.code === 'ENOENT' || err.code === 'EBUSY') {
43
+ await new Promise((resolve) => setTimeout(resolve, 10))
44
+
45
+ continue
46
+ }
47
+ }
48
+
49
+ throw err
50
+ }
51
+ }
52
+ }
53
+
54
+ export function drainStdin() {
55
+ return new Promise((resolve, reject) => {
56
+ let result = ''
57
+ process.stdin.on('data', (chunk) => {
58
+ result += chunk
59
+ })
60
+ process.stdin.on('end', () => resolve(result))
61
+ process.stdin.on('error', (err) => reject(err))
62
+ })
63
+ }
64
+
65
+ export async function outputFile(file, newContents) {
66
+ try {
67
+ let currentContents = await fs.promises.readFile(file, 'utf8')
68
+ if (currentContents === newContents) {
69
+ return // Skip writing the file
70
+ }
71
+ } catch {}
72
+
73
+ // Write the file
74
+ await fs.promises.mkdir(path.dirname(file), { recursive: true })
75
+ await fs.promises.writeFile(file, newContents, 'utf8')
76
+ }