tailwindcss 0.0.0-insiders.7c337f2 → 0.0.0-insiders.7d8eb21

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 (161) hide show
  1. package/CHANGELOG.md +246 -6
  2. package/README.md +13 -9
  3. package/defaultTheme.d.ts +2 -1
  4. package/lib/cli/build/deps.js +54 -0
  5. package/lib/cli/build/index.js +48 -0
  6. package/lib/cli/build/plugin.js +362 -0
  7. package/lib/cli/build/utils.js +78 -0
  8. package/lib/cli/build/watching.js +178 -0
  9. package/lib/cli/help/index.js +71 -0
  10. package/lib/cli/index.js +18 -0
  11. package/lib/cli/init/index.js +46 -0
  12. package/lib/cli/shared.js +12 -0
  13. package/lib/cli-peer-dependencies.js +18 -5
  14. package/lib/cli.js +62 -592
  15. package/lib/constants.js +19 -12
  16. package/lib/corePluginList.js +5 -3
  17. package/lib/corePlugins.js +619 -347
  18. package/lib/css/preflight.css +7 -0
  19. package/lib/featureFlags.js +34 -22
  20. package/lib/index.js +16 -9
  21. package/lib/lib/cacheInvalidation.js +42 -21
  22. package/lib/lib/collapseAdjacentRules.js +16 -14
  23. package/lib/lib/collapseDuplicateDeclarations.js +13 -10
  24. package/lib/lib/content.js +177 -0
  25. package/lib/lib/defaultExtractor.js +230 -33
  26. package/lib/lib/detectNesting.js +13 -4
  27. package/lib/lib/evaluateTailwindFunctions.js +105 -42
  28. package/lib/lib/expandApplyAtRules.js +151 -92
  29. package/lib/lib/expandTailwindAtRules.js +134 -149
  30. package/lib/lib/findAtConfigPath.js +44 -0
  31. package/lib/lib/generateRules.js +404 -185
  32. package/lib/lib/getModuleDependencies.js +21 -18
  33. package/lib/lib/normalizeTailwindDirectives.js +11 -8
  34. package/lib/lib/offsets.js +285 -0
  35. package/lib/lib/partitionApplyAtRules.js +14 -11
  36. package/lib/lib/regex.js +60 -0
  37. package/lib/lib/remap-bitfield.js +87 -0
  38. package/lib/lib/resolveDefaultsAtRules.js +97 -79
  39. package/lib/lib/setupContextUtils.js +567 -242
  40. package/lib/lib/setupTrackingContext.js +77 -106
  41. package/lib/lib/sharedState.js +18 -10
  42. package/lib/lib/substituteScreenAtRules.js +9 -7
  43. package/lib/postcss-plugins/nesting/index.js +7 -5
  44. package/lib/postcss-plugins/nesting/plugin.js +10 -8
  45. package/lib/processTailwindFeatures.js +34 -31
  46. package/lib/public/colors.js +7 -5
  47. package/lib/public/create-plugin.js +6 -4
  48. package/lib/public/default-config.js +7 -5
  49. package/lib/public/default-theme.js +7 -5
  50. package/lib/public/resolve-config.js +13 -10
  51. package/lib/util/bigSign.js +4 -1
  52. package/lib/util/buildMediaQuery.js +10 -5
  53. package/lib/util/cloneDeep.js +6 -5
  54. package/lib/util/cloneNodes.js +9 -2
  55. package/lib/util/color.js +20 -17
  56. package/lib/util/configurePlugins.js +5 -2
  57. package/lib/util/createPlugin.js +6 -5
  58. package/lib/util/createUtilityPlugin.js +15 -13
  59. package/lib/util/dataTypes.js +75 -51
  60. package/lib/util/defaults.js +8 -5
  61. package/lib/util/escapeClassName.js +13 -10
  62. package/lib/util/escapeCommas.js +4 -1
  63. package/lib/util/flattenColorPalette.js +7 -8
  64. package/lib/util/formatVariantSelector.js +270 -103
  65. package/lib/util/getAllConfigs.js +34 -15
  66. package/lib/util/hashConfig.js +10 -7
  67. package/lib/util/isKeyframeRule.js +4 -1
  68. package/lib/util/isPlainObject.js +4 -1
  69. package/lib/util/{isValidArbitraryValue.js → isSyntacticallyValidPropertyValue.js} +34 -26
  70. package/lib/util/log.js +14 -8
  71. package/lib/util/nameClass.js +19 -8
  72. package/lib/util/negateValue.js +20 -5
  73. package/lib/util/normalizeConfig.js +94 -53
  74. package/lib/util/normalizeScreens.js +115 -4
  75. package/lib/util/parseAnimationValue.js +43 -41
  76. package/lib/util/parseBoxShadowValue.js +12 -45
  77. package/lib/util/parseDependency.js +37 -55
  78. package/lib/util/parseGlob.js +34 -0
  79. package/lib/util/parseObjectStyles.js +15 -12
  80. package/lib/util/pluginUtils.js +146 -42
  81. package/lib/util/prefixSelector.js +26 -9
  82. package/lib/util/removeAlphaVariables.js +29 -0
  83. package/lib/util/resolveConfig.js +104 -105
  84. package/lib/util/resolveConfigPath.js +20 -17
  85. package/lib/util/responsive.js +12 -9
  86. package/lib/util/splitAtTopLevelOnly.js +43 -0
  87. package/lib/util/tap.js +4 -1
  88. package/lib/util/toColorValue.js +4 -1
  89. package/lib/util/toPath.js +18 -2
  90. package/lib/util/transformThemeValue.js +23 -11
  91. package/lib/util/validateConfig.js +24 -0
  92. package/lib/util/validateFormalSyntax.js +24 -0
  93. package/lib/util/withAlphaVariable.js +32 -24
  94. package/package.json +32 -29
  95. package/peers/index.js +6693 -3036
  96. package/plugin.d.ts +10 -5
  97. package/resolveConfig.d.ts +12 -0
  98. package/scripts/generate-types.js +53 -0
  99. package/scripts/release-channel.js +18 -0
  100. package/scripts/release-notes.js +21 -0
  101. package/scripts/type-utils.js +27 -0
  102. package/src/cli/build/deps.js +56 -0
  103. package/src/cli/build/index.js +49 -0
  104. package/src/cli/build/plugin.js +434 -0
  105. package/src/cli/build/utils.js +76 -0
  106. package/src/cli/build/watching.js +227 -0
  107. package/src/cli/help/index.js +70 -0
  108. package/src/cli/index.js +3 -0
  109. package/src/cli/init/index.js +50 -0
  110. package/src/cli/shared.js +5 -0
  111. package/src/cli-peer-dependencies.js +7 -1
  112. package/src/cli.js +46 -659
  113. package/src/corePlugins.js +346 -79
  114. package/src/css/preflight.css +7 -0
  115. package/src/featureFlags.js +12 -2
  116. package/src/index.js +5 -0
  117. package/src/lib/content.js +213 -0
  118. package/src/lib/defaultExtractor.js +202 -35
  119. package/src/lib/detectNesting.js +9 -1
  120. package/src/lib/evaluateTailwindFunctions.js +78 -7
  121. package/src/lib/expandApplyAtRules.js +129 -34
  122. package/src/lib/expandTailwindAtRules.js +12 -50
  123. package/src/lib/findAtConfigPath.js +48 -0
  124. package/src/lib/generateRules.js +379 -126
  125. package/src/lib/offsets.js +351 -0
  126. package/src/lib/regex.js +74 -0
  127. package/src/lib/remap-bitfield.js +82 -0
  128. package/src/lib/resolveDefaultsAtRules.js +53 -36
  129. package/src/lib/setupContextUtils.js +510 -120
  130. package/src/lib/setupTrackingContext.js +8 -45
  131. package/src/lib/sharedState.js +2 -0
  132. package/src/util/buildMediaQuery.js +5 -3
  133. package/src/util/cloneNodes.js +5 -1
  134. package/src/util/dataTypes.js +51 -26
  135. package/src/util/formatVariantSelector.js +317 -101
  136. package/src/util/getAllConfigs.js +19 -0
  137. package/src/util/{isValidArbitraryValue.js → isSyntacticallyValidPropertyValue.js} +1 -1
  138. package/src/util/log.js +1 -1
  139. package/src/util/nameClass.js +4 -0
  140. package/src/util/negateValue.js +10 -2
  141. package/src/util/normalizeConfig.js +40 -10
  142. package/src/util/normalizeScreens.js +99 -4
  143. package/src/util/parseBoxShadowValue.js +3 -50
  144. package/src/util/parseDependency.js +37 -42
  145. package/src/util/parseGlob.js +24 -0
  146. package/src/util/pluginUtils.js +132 -10
  147. package/src/util/prefixSelector.js +28 -10
  148. package/src/util/removeAlphaVariables.js +24 -0
  149. package/src/util/resolveConfig.js +70 -62
  150. package/src/util/splitAtTopLevelOnly.js +45 -0
  151. package/src/util/toPath.js +1 -1
  152. package/src/util/transformThemeValue.js +13 -3
  153. package/src/util/validateConfig.js +13 -0
  154. package/src/util/validateFormalSyntax.js +34 -0
  155. package/src/util/withAlphaVariable.js +1 -1
  156. package/stubs/defaultConfig.stub.js +165 -164
  157. package/stubs/simpleConfig.stub.js +1 -0
  158. package/types/config.d.ts +77 -37
  159. package/types/generated/default-theme.d.ts +342 -0
  160. package/types/index.d.ts +7 -1
  161. package/types.d.ts +0 -1
package/src/cli.js CHANGED
@@ -1,134 +1,35 @@
1
1
  #!/usr/bin/env node
2
2
 
3
- import { postcss, lazyCssnano, lazyAutoprefixer } from '../peers/index.js'
4
-
5
- import chokidar from 'chokidar'
6
3
  import path from 'path'
7
4
  import arg from 'arg'
8
5
  import fs from 'fs'
9
- import postcssrc from 'postcss-load-config'
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
- import tailwind from './processTailwindFeatures'
14
- import resolveConfigInternal from '../resolveConfig'
15
- import fastGlob from 'fast-glob'
16
- import getModuleDependencies from './lib/getModuleDependencies'
17
- import log from './util/log'
18
- import packageJson from '../package.json'
19
- import normalizePath from 'normalize-path'
20
-
21
- let env = {
22
- DEBUG: process.env.DEBUG !== undefined && process.env.DEBUG !== '0',
23
- }
24
6
 
25
- // ---
26
-
27
- function indentRecursive(node, indent = 0) {
28
- node.each &&
29
- node.each((child, i) => {
30
- if (!child.raws.before || !child.raws.before.trim() || child.raws.before.includes('\n')) {
31
- child.raws.before = `\n${node.type !== 'rule' && i > 0 ? '\n' : ''}${' '.repeat(indent)}`
32
- }
33
- child.raws.after = `\n${' '.repeat(indent)}`
34
- indentRecursive(child, indent + 1)
35
- })
36
- }
7
+ import { build } from './cli/build'
8
+ import { help } from './cli/help'
9
+ import { init } from './cli/init'
37
10
 
38
- function formatNodes(root) {
39
- indentRecursive(root)
40
- if (root.first) {
41
- root.first.raws.before = ''
42
- }
43
- }
11
+ function isESM() {
12
+ const pkgPath = path.resolve('./package.json')
44
13
 
45
- async function outputFile(file, contents) {
46
- if (fs.existsSync(file) && (await fs.promises.readFile(file, 'utf8')) === contents) {
47
- return // Skip writing the file
14
+ try {
15
+ let pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf8'))
16
+ return pkg.type && pkg.type === 'module'
17
+ } catch (err) {
18
+ return false
48
19
  }
49
-
50
- // Write the file
51
- await fs.promises.writeFile(file, contents, 'utf8')
52
- }
53
-
54
- 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
20
  }
64
21
 
65
- function help({ message, usage, commands, options }) {
66
- let indent = 2
67
-
68
- // Render header
69
- console.log()
70
- console.log(`${packageJson.name} v${packageJson.version}`)
71
-
72
- // Render message
73
- if (message) {
74
- console.log()
75
- for (let msg of message.split('\n')) {
76
- console.log(msg)
77
- }
78
- }
79
-
80
- // Render usage
81
- if (usage && usage.length > 0) {
82
- console.log()
83
- console.log('Usage:')
84
- for (let example of usage) {
85
- console.log(' '.repeat(indent), example)
86
- }
87
- }
88
-
89
- // Render commands
90
- if (commands && commands.length > 0) {
91
- console.log()
92
- console.log('Commands:')
93
- for (let command of commands) {
94
- console.log(' '.repeat(indent), command)
95
- }
96
- }
97
-
98
- // Render options
99
- if (options) {
100
- let groupedOptions = {}
101
- for (let [key, value] of Object.entries(options)) {
102
- if (typeof value === 'object') {
103
- groupedOptions[key] = { ...value, flags: [key] }
104
- } else {
105
- groupedOptions[value].flags.push(key)
106
- }
22
+ let configs = isESM()
23
+ ? {
24
+ tailwind: 'tailwind.config.cjs',
25
+ postcss: 'postcss.config.cjs',
107
26
  }
108
-
109
- console.log()
110
- console.log('Options:')
111
- for (let { flags, description, deprecated } of Object.values(groupedOptions)) {
112
- if (deprecated) continue
113
-
114
- if (flags.length === 1) {
115
- console.log(
116
- ' '.repeat(indent + 4 /* 4 = "-i, ".length */),
117
- flags.slice().reverse().join(', ').padEnd(20, ' '),
118
- description
119
- )
120
- } else {
121
- console.log(
122
- ' '.repeat(indent),
123
- flags.slice().reverse().join(', ').padEnd(24, ' '),
124
- description
125
- )
126
- }
27
+ : {
28
+ tailwind: 'tailwind.config.js',
29
+ postcss: 'postcss.config.js',
127
30
  }
128
- }
129
31
 
130
- console.log()
131
- }
32
+ // ---
132
33
 
133
34
  function oneOf(...options) {
134
35
  return Object.assign(
@@ -150,12 +51,8 @@ let commands = {
150
51
  init: {
151
52
  run: init,
152
53
  args: {
153
- '--full': { type: Boolean, description: 'Initialize a full `tailwind.config.js` file' },
154
- '--postcss': { type: Boolean, description: 'Initialize a `postcss.config.js` file' },
155
- '--types': {
156
- type: Boolean,
157
- description: 'Add TypeScript types for the `tailwind.config.js` file',
158
- },
54
+ '--full': { type: Boolean, description: `Initialize a full \`${configs.tailwind}\` file` },
55
+ '--postcss': { type: Boolean, description: `Initialize a \`${configs.postcss}\` file` },
159
56
  '-f': '--full',
160
57
  '-p': '--postcss',
161
58
  },
@@ -165,7 +62,10 @@ let commands = {
165
62
  args: {
166
63
  '--input': { type: String, description: 'Input file' },
167
64
  '--output': { type: String, description: 'Output file' },
168
- '--watch': { type: Boolean, description: 'Watch for changes and rebuild as needed' },
65
+ '--watch': {
66
+ type: oneOf(String, Boolean),
67
+ description: 'Watch for changes and rebuild as needed',
68
+ },
169
69
  '--poll': {
170
70
  type: Boolean,
171
71
  description: 'Use polling instead of filesystem events when watching',
@@ -214,7 +114,7 @@ if (
214
114
  help({
215
115
  usage: [
216
116
  'tailwindcss [--input input.css] [--output output.css] [--watch] [options...]',
217
- 'tailwindcss init [--full] [--postcss] [--types] [options...]',
117
+ 'tailwindcss init [--full] [--postcss] [options...]',
218
118
  ],
219
119
  commands: Object.keys(commands)
220
120
  .filter((command) => command !== 'build')
@@ -262,8 +162,8 @@ let args = (() => {
262
162
  let flag = result['_'][i]
263
163
  if (!flag.startsWith('-')) continue
264
164
 
265
- let flagName = flag
266
- let handler = flags[flag]
165
+ let [flagName, flagValue] = flag.split('=')
166
+ let handler = flags[flagName]
267
167
 
268
168
  // Resolve flagName & handler
269
169
  while (typeof handler === 'string') {
@@ -276,19 +176,27 @@ let args = (() => {
276
176
  let args = []
277
177
  let offset = i + 1
278
178
 
279
- // Parse args for current flag
280
- while (result['_'][offset] && !result['_'][offset].startsWith('-')) {
281
- args.push(result['_'][offset++])
282
- }
179
+ // --flag value syntax was used so we need to pull `value` from `args`
180
+ if (flagValue === undefined) {
181
+ // Parse args for current flag
182
+ while (result['_'][offset] && !result['_'][offset].startsWith('-')) {
183
+ args.push(result['_'][offset++])
184
+ }
185
+
186
+ // Cleanup manually parsed flags + args
187
+ result['_'].splice(i, 1 + args.length)
283
188
 
284
- // Cleanup manually parsed flags + args
285
- result['_'].splice(i, 1 + args.length)
189
+ // No args were provided, use default value defined in handler
190
+ // One arg was provided, use that directly
191
+ // Multiple args were provided so pass them all in an array
192
+ flagValue = args.length === 0 ? undefined : args.length === 1 ? args[0] : args
193
+ } else {
194
+ // Remove the whole flag from the args array
195
+ result['_'].splice(i, 1)
196
+ }
286
197
 
287
198
  // Set the resolved value in the `result` object
288
- result[flagName] = handler.type(
289
- args.length === 0 ? undefined : args.length === 1 ? args[0] : args,
290
- flagName
291
- )
199
+ result[flagName] = handler.type(flagValue, flagName)
292
200
  }
293
201
 
294
202
  // Ensure that the `command` is always the first argument in the `args`.
@@ -323,525 +231,4 @@ if (args['--help']) {
323
231
  process.exit(0)
324
232
  }
325
233
 
326
- run()
327
-
328
- // ---
329
-
330
- function init() {
331
- let messages = []
332
-
333
- let tailwindConfigLocation = path.resolve(args['_'][1] ?? './tailwind.config.js')
334
- if (fs.existsSync(tailwindConfigLocation)) {
335
- messages.push(`${path.basename(tailwindConfigLocation)} already exists.`)
336
- } else {
337
- let stubFile = fs.readFileSync(
338
- args['--full']
339
- ? path.resolve(__dirname, '../stubs/defaultConfig.stub.js')
340
- : path.resolve(__dirname, '../stubs/simpleConfig.stub.js'),
341
- 'utf8'
342
- )
343
-
344
- if (args['--types']) {
345
- let typesHeading = "/** @type {import('tailwindcss/types').Config} */"
346
- stubFile =
347
- stubFile.replace(`module.exports = `, `${typesHeading}\nconst config = `) +
348
- '\nmodule.exports = config'
349
- }
350
-
351
- // Change colors import
352
- stubFile = stubFile.replace('../colors', 'tailwindcss/colors')
353
-
354
- fs.writeFileSync(tailwindConfigLocation, stubFile, 'utf8')
355
-
356
- messages.push(`Created Tailwind CSS config file: ${path.basename(tailwindConfigLocation)}`)
357
- }
358
-
359
- if (args['--postcss']) {
360
- let postcssConfigLocation = path.resolve('./postcss.config.js')
361
- if (fs.existsSync(postcssConfigLocation)) {
362
- messages.push(`${path.basename(postcssConfigLocation)} already exists.`)
363
- } else {
364
- let stubFile = fs.readFileSync(
365
- path.resolve(__dirname, '../stubs/defaultPostCssConfig.stub.js'),
366
- 'utf8'
367
- )
368
-
369
- fs.writeFileSync(postcssConfigLocation, stubFile, 'utf8')
370
-
371
- messages.push(`Created PostCSS config file: ${path.basename(postcssConfigLocation)}`)
372
- }
373
- }
374
-
375
- if (messages.length > 0) {
376
- console.log()
377
- for (let message of messages) {
378
- console.log(message)
379
- }
380
- }
381
- }
382
-
383
- async function build() {
384
- let input = args['--input']
385
- let output = args['--output']
386
- let shouldWatch = args['--watch']
387
- let shouldPoll = args['--poll']
388
- let shouldCoalesceWriteEvents = shouldPoll || process.platform === 'win32'
389
- let includePostCss = args['--postcss']
390
-
391
- // Polling interval in milliseconds
392
- // Used only when polling or coalescing add/change events on Windows
393
- let pollInterval = 10
394
-
395
- // TODO: Deprecate this in future versions
396
- if (!input && args['_'][1]) {
397
- console.error('[deprecation] Running tailwindcss without -i, please provide an input file.')
398
- input = args['--input'] = args['_'][1]
399
- }
400
-
401
- if (input && input !== '-' && !fs.existsSync((input = path.resolve(input)))) {
402
- console.error(`Specified input file ${args['--input']} does not exist.`)
403
- process.exit(9)
404
- }
405
-
406
- if (args['--config'] && !fs.existsSync((args['--config'] = path.resolve(args['--config'])))) {
407
- console.error(`Specified config file ${args['--config']} does not exist.`)
408
- process.exit(9)
409
- }
410
-
411
- let configPath = args['--config']
412
- ? args['--config']
413
- : ((defaultPath) => (fs.existsSync(defaultPath) ? defaultPath : null))(
414
- path.resolve('./tailwind.config.js')
415
- )
416
-
417
- async function loadPostCssPlugins() {
418
- let customPostCssPath = typeof args['--postcss'] === 'string' ? args['--postcss'] : undefined
419
- let config = customPostCssPath
420
- ? await (async () => {
421
- let file = path.resolve(customPostCssPath)
422
-
423
- // Implementation, see: https://unpkg.com/browse/postcss-load-config@3.1.0/src/index.js
424
- let { config = {} } = await lilconfig('postcss').load(file)
425
- if (typeof config === 'function') {
426
- config = config()
427
- } else {
428
- config = Object.assign({}, config)
429
- }
430
-
431
- if (!config.plugins) {
432
- config.plugins = []
433
- }
434
-
435
- return {
436
- file,
437
- plugins: loadPlugins(config, file),
438
- options: loadOptions(config, file),
439
- }
440
- })()
441
- : await postcssrc()
442
-
443
- let configPlugins = config.plugins
444
-
445
- let configPluginTailwindIdx = configPlugins.findIndex((plugin) => {
446
- if (typeof plugin === 'function' && plugin.name === 'tailwindcss') {
447
- return true
448
- }
449
-
450
- if (typeof plugin === 'object' && plugin !== null && plugin.postcssPlugin === 'tailwindcss') {
451
- return true
452
- }
453
-
454
- return false
455
- })
456
-
457
- let beforePlugins =
458
- configPluginTailwindIdx === -1 ? [] : configPlugins.slice(0, configPluginTailwindIdx)
459
- let afterPlugins =
460
- configPluginTailwindIdx === -1
461
- ? configPlugins
462
- : configPlugins.slice(configPluginTailwindIdx + 1)
463
-
464
- return [beforePlugins, afterPlugins, config.options]
465
- }
466
-
467
- function resolveConfig() {
468
- let config = configPath ? require(configPath) : {}
469
-
470
- if (args['--purge']) {
471
- log.warn('purge-flag-deprecated', [
472
- 'The `--purge` flag has been deprecated.',
473
- 'Please use `--content` instead.',
474
- ])
475
- if (!args['--content']) {
476
- args['--content'] = args['--purge']
477
- }
478
- }
479
-
480
- if (args['--content']) {
481
- let files = args['--content'].split(/(?<!{[^}]+),/)
482
- let resolvedConfig = resolveConfigInternal(config, { content: { files } })
483
- resolvedConfig.content.files = files
484
- return resolvedConfig
485
- }
486
-
487
- return resolveConfigInternal(config)
488
- }
489
-
490
- function extractFileGlobs(config) {
491
- return config.content.files
492
- .filter((file) => {
493
- // Strings in this case are files / globs. If it is something else,
494
- // like an object it's probably a raw content object. But this object
495
- // is not watchable, so let's remove it.
496
- return typeof file === 'string'
497
- })
498
- .map((glob) => normalizePath(glob))
499
- }
500
-
501
- function extractRawContent(config) {
502
- return config.content.files.filter((file) => {
503
- return typeof file === 'object' && file !== null
504
- })
505
- }
506
-
507
- function getChangedContent(config) {
508
- let changedContent = []
509
-
510
- // Resolve globs from the content config
511
- let globs = extractFileGlobs(config)
512
- let files = fastGlob.sync(globs)
513
-
514
- for (let file of files) {
515
- changedContent.push({
516
- content: fs.readFileSync(path.resolve(file), 'utf8'),
517
- extension: path.extname(file).slice(1),
518
- })
519
- }
520
-
521
- // Resolve raw content in the tailwind config
522
- for (let { raw: content, extension = 'html' } of extractRawContent(config)) {
523
- changedContent.push({ content, extension })
524
- }
525
-
526
- return changedContent
527
- }
528
-
529
- async function buildOnce() {
530
- let config = resolveConfig()
531
- let changedContent = getChangedContent(config)
532
-
533
- let tailwindPlugin = () => {
534
- return {
535
- postcssPlugin: 'tailwindcss',
536
- Once(root, { result }) {
537
- tailwind(({ createContext }) => {
538
- return () => {
539
- return createContext(config, changedContent)
540
- }
541
- })(root, result)
542
- },
543
- }
544
- }
545
-
546
- tailwindPlugin.postcss = true
547
-
548
- let [beforePlugins, afterPlugins, postcssOptions] = includePostCss
549
- ? await loadPostCssPlugins()
550
- : [[], [], {}]
551
-
552
- let plugins = [
553
- ...beforePlugins,
554
- tailwindPlugin,
555
- !args['--minify'] && formatNodes,
556
- ...afterPlugins,
557
- !args['--no-autoprefixer'] &&
558
- (() => {
559
- // Try to load a local `autoprefixer` version first
560
- try {
561
- return require('autoprefixer')
562
- } catch {}
563
-
564
- return lazyAutoprefixer()
565
- })(),
566
- args['--minify'] &&
567
- (() => {
568
- let options = { preset: ['default', { cssDeclarationSorter: false }] }
569
-
570
- // Try to load a local `cssnano` version first
571
- try {
572
- return require('cssnano')
573
- } catch {}
574
-
575
- return lazyCssnano()(options)
576
- })(),
577
- ].filter(Boolean)
578
-
579
- let processor = postcss(plugins)
580
-
581
- function processCSS(css) {
582
- let start = process.hrtime.bigint()
583
- return Promise.resolve()
584
- .then(() => (output ? fs.promises.mkdir(path.dirname(output), { recursive: true }) : null))
585
- .then(() => processor.process(css, { ...postcssOptions, from: input, to: output }))
586
- .then((result) => {
587
- if (!output) {
588
- return process.stdout.write(result.css)
589
- }
590
-
591
- return Promise.all(
592
- [
593
- outputFile(output, result.css),
594
- result.map && outputFile(output + '.map', result.map.toString()),
595
- ].filter(Boolean)
596
- )
597
- })
598
- .then(() => {
599
- let end = process.hrtime.bigint()
600
- console.error()
601
- console.error('Done in', (end - start) / BigInt(1e6) + 'ms.')
602
- })
603
- }
604
-
605
- let css = await (() => {
606
- // Piping in data, let's drain the stdin
607
- if (input === '-') {
608
- return drainStdin()
609
- }
610
-
611
- // Input file has been provided
612
- if (input) {
613
- return fs.readFileSync(path.resolve(input), 'utf8')
614
- }
615
-
616
- // No input file provided, fallback to default atrules
617
- return '@tailwind base; @tailwind components; @tailwind utilities'
618
- })()
619
-
620
- return processCSS(css)
621
- }
622
-
623
- let context = null
624
-
625
- async function startWatcher() {
626
- let changedContent = []
627
- let configDependencies = []
628
- let contextDependencies = new Set()
629
- let watcher = null
630
-
631
- function refreshConfig() {
632
- env.DEBUG && console.time('Module dependencies')
633
- for (let file of configDependencies) {
634
- delete require.cache[require.resolve(file)]
635
- }
636
-
637
- if (configPath) {
638
- configDependencies = getModuleDependencies(configPath).map(({ file }) => file)
639
-
640
- for (let dependency of configDependencies) {
641
- contextDependencies.add(dependency)
642
- }
643
- }
644
- env.DEBUG && console.timeEnd('Module dependencies')
645
-
646
- return resolveConfig()
647
- }
648
-
649
- let [beforePlugins, afterPlugins] = includePostCss ? await loadPostCssPlugins() : [[], []]
650
-
651
- let plugins = [
652
- ...beforePlugins,
653
- '__TAILWIND_PLUGIN_POSITION__',
654
- !args['--minify'] && formatNodes,
655
- ...afterPlugins,
656
- !args['--no-autoprefixer'] &&
657
- (() => {
658
- // Try to load a local `autoprefixer` version first
659
- try {
660
- return require('autoprefixer')
661
- } catch {}
662
-
663
- return lazyAutoprefixer()
664
- })(),
665
- args['--minify'] &&
666
- (() => {
667
- let options = { preset: ['default', { cssDeclarationSorter: false }] }
668
-
669
- // Try to load a local `cssnano` version first
670
- try {
671
- return require('cssnano')
672
- } catch {}
673
-
674
- return lazyCssnano()(options)
675
- })(),
676
- ].filter(Boolean)
677
-
678
- async function rebuild(config) {
679
- env.DEBUG && console.time('Finished in')
680
-
681
- let tailwindPlugin = () => {
682
- return {
683
- postcssPlugin: 'tailwindcss',
684
- Once(root, { result }) {
685
- env.DEBUG && console.time('Compiling CSS')
686
- tailwind(({ createContext }) => {
687
- console.error()
688
- console.error('Rebuilding...')
689
-
690
- return () => {
691
- if (context !== null) {
692
- context.changedContent = changedContent.splice(0)
693
- return context
694
- }
695
-
696
- env.DEBUG && console.time('Creating context')
697
- context = createContext(config, changedContent.splice(0))
698
- env.DEBUG && console.timeEnd('Creating context')
699
- return context
700
- }
701
- })(root, result)
702
- env.DEBUG && console.timeEnd('Compiling CSS')
703
- },
704
- }
705
- }
706
-
707
- tailwindPlugin.postcss = true
708
-
709
- let tailwindPluginIdx = plugins.indexOf('__TAILWIND_PLUGIN_POSITION__')
710
- let copy = plugins.slice()
711
- copy.splice(tailwindPluginIdx, 1, tailwindPlugin)
712
- let processor = postcss(copy)
713
-
714
- function processCSS(css) {
715
- let start = process.hrtime.bigint()
716
- return Promise.resolve()
717
- .then(() =>
718
- output ? fs.promises.mkdir(path.dirname(output), { recursive: true }) : null
719
- )
720
- .then(() => processor.process(css, { from: input, to: output }))
721
- .then(async (result) => {
722
- for (let message of result.messages) {
723
- if (message.type === 'dependency') {
724
- contextDependencies.add(message.file)
725
- }
726
- }
727
- watcher.add([...contextDependencies])
728
-
729
- if (!output) {
730
- return process.stdout.write(result.css)
731
- }
732
-
733
- return Promise.all(
734
- [
735
- outputFile(output, result.css),
736
- result.map && outputFile(output + '.map', result.map.toString()),
737
- ].filter(Boolean)
738
- )
739
- })
740
- .then(() => {
741
- let end = process.hrtime.bigint()
742
- console.error('Done in', (end - start) / BigInt(1e6) + 'ms.')
743
- })
744
- .catch((err) => {
745
- if (err.name === 'CssSyntaxError') {
746
- console.error(err.toString())
747
- } else {
748
- console.error(err)
749
- }
750
- })
751
- }
752
-
753
- let css = await (() => {
754
- // Piping in data, let's drain the stdin
755
- if (input === '-') {
756
- return drainStdin()
757
- }
758
-
759
- // Input file has been provided
760
- if (input) {
761
- return fs.readFileSync(path.resolve(input), 'utf8')
762
- }
763
-
764
- // No input file provided, fallback to default atrules
765
- return '@tailwind base; @tailwind components; @tailwind utilities'
766
- })()
767
-
768
- let result = await processCSS(css)
769
- env.DEBUG && console.timeEnd('Finished in')
770
- return result
771
- }
772
-
773
- let config = refreshConfig(configPath)
774
-
775
- if (input) {
776
- contextDependencies.add(path.resolve(input))
777
- }
778
-
779
- watcher = chokidar.watch([...contextDependencies, ...extractFileGlobs(config)], {
780
- usePolling: shouldPoll,
781
- interval: shouldPoll ? pollInterval : undefined,
782
- ignoreInitial: true,
783
- awaitWriteFinish: shouldCoalesceWriteEvents
784
- ? {
785
- stabilityThreshold: 50,
786
- pollInterval: pollInterval,
787
- }
788
- : false,
789
- })
790
-
791
- let chain = Promise.resolve()
792
-
793
- watcher.on('change', async (file) => {
794
- if (contextDependencies.has(file)) {
795
- env.DEBUG && console.time('Resolve config')
796
- context = null
797
- config = refreshConfig(configPath)
798
- env.DEBUG && console.timeEnd('Resolve config')
799
-
800
- env.DEBUG && console.time('Watch new files')
801
- let globs = extractFileGlobs(config)
802
- watcher.add(configDependencies)
803
- watcher.add(globs)
804
- env.DEBUG && console.timeEnd('Watch new files')
805
-
806
- chain = chain.then(async () => {
807
- changedContent.push(...getChangedContent(config))
808
- await rebuild(config)
809
- })
810
- } else {
811
- chain = chain.then(async () => {
812
- changedContent.push({
813
- content: fs.readFileSync(path.resolve(file), 'utf8'),
814
- extension: path.extname(file).slice(1),
815
- })
816
-
817
- await rebuild(config)
818
- })
819
- }
820
- })
821
-
822
- watcher.on('add', async (file) => {
823
- chain = chain.then(async () => {
824
- changedContent.push({
825
- content: fs.readFileSync(path.resolve(file), 'utf8'),
826
- extension: path.extname(file).slice(1),
827
- })
828
-
829
- await rebuild(config)
830
- })
831
- })
832
-
833
- chain = chain.then(() => {
834
- changedContent.push(...getChangedContent(config))
835
- return rebuild(config)
836
- })
837
- }
838
-
839
- if (shouldWatch) {
840
- /* Abort the watcher if stdin is closed to avoid zombie processes */
841
- process.stdin.on('end', () => process.exit(0))
842
- process.stdin.resume()
843
- startWatcher()
844
- } else {
845
- buildOnce()
846
- }
847
- }
234
+ run(args, configs)