tailwindcss 0.0.0-insiders.fe08e91 → 0.0.0-oxide.6d7c311

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 (186) hide show
  1. package/CHANGELOG.md +384 -3
  2. package/LICENSE +1 -2
  3. package/README.md +12 -8
  4. package/colors.d.ts +3 -0
  5. package/defaultConfig.d.ts +3 -0
  6. package/defaultTheme.d.ts +4 -0
  7. package/lib/cli/build/deps.js +54 -0
  8. package/lib/cli/build/index.js +48 -0
  9. package/lib/cli/build/plugin.js +367 -0
  10. package/lib/cli/build/utils.js +78 -0
  11. package/lib/cli/build/watching.js +178 -0
  12. package/lib/cli/help/index.js +71 -0
  13. package/lib/cli/index.js +239 -0
  14. package/lib/cli/init/index.js +46 -0
  15. package/lib/cli/shared.js +13 -0
  16. package/lib/cli-peer-dependencies.js +20 -7
  17. package/lib/cli.js +4 -740
  18. package/lib/constants.js +27 -20
  19. package/lib/corePluginList.js +6 -3
  20. package/lib/corePlugins.js +2064 -1811
  21. package/lib/css/preflight.css +5 -5
  22. package/lib/featureFlags.js +31 -22
  23. package/lib/index.js +4 -28
  24. package/lib/lib/cacheInvalidation.js +90 -0
  25. package/lib/lib/collapseAdjacentRules.js +27 -9
  26. package/lib/lib/collapseDuplicateDeclarations.js +12 -9
  27. package/lib/lib/content.js +176 -0
  28. package/lib/lib/defaultExtractor.js +225 -31
  29. package/lib/lib/detectNesting.js +13 -10
  30. package/lib/lib/evaluateTailwindFunctions.js +118 -55
  31. package/lib/lib/expandApplyAtRules.js +439 -190
  32. package/lib/lib/expandTailwindAtRules.js +151 -134
  33. package/lib/lib/findAtConfigPath.js +44 -0
  34. package/lib/lib/generateRules.js +454 -187
  35. package/lib/lib/getModuleDependencies.js +11 -8
  36. package/lib/lib/normalizeTailwindDirectives.js +36 -32
  37. package/lib/lib/offsets.js +217 -0
  38. package/lib/lib/partitionApplyAtRules.js +56 -0
  39. package/lib/lib/regex.js +60 -0
  40. package/lib/lib/resolveDefaultsAtRules.js +89 -67
  41. package/lib/lib/setupContextUtils.js +667 -376
  42. package/lib/lib/setupTrackingContext.js +38 -67
  43. package/lib/lib/sharedState.js +27 -14
  44. package/lib/lib/substituteScreenAtRules.js +11 -9
  45. package/lib/oxide/cli.d.js +1 -0
  46. package/lib/oxide/cli.js +2 -0
  47. package/lib/oxide/postcss-plugin.d.js +1 -0
  48. package/lib/oxide/postcss-plugin.js +2 -0
  49. package/lib/plugin.js +48 -0
  50. package/{nesting → lib/postcss-plugins/nesting}/README.md +2 -2
  51. package/lib/postcss-plugins/nesting/index.js +19 -0
  52. package/lib/postcss-plugins/nesting/plugin.js +87 -0
  53. package/lib/processTailwindFeatures.js +35 -25
  54. package/lib/public/colors.js +247 -245
  55. package/lib/public/create-plugin.js +6 -4
  56. package/lib/public/default-config.js +7 -5
  57. package/lib/public/default-theme.js +7 -5
  58. package/lib/public/resolve-config.js +8 -5
  59. package/lib/util/bigSign.js +4 -1
  60. package/lib/util/buildMediaQuery.js +11 -6
  61. package/lib/util/cloneDeep.js +7 -6
  62. package/lib/util/cloneNodes.js +21 -3
  63. package/lib/util/color.js +53 -54
  64. package/lib/util/configurePlugins.js +5 -2
  65. package/lib/util/createPlugin.js +6 -6
  66. package/lib/util/createUtilityPlugin.js +12 -14
  67. package/lib/util/dataTypes.js +119 -110
  68. package/lib/util/defaults.js +4 -1
  69. package/lib/util/escapeClassName.js +7 -4
  70. package/lib/util/escapeCommas.js +5 -2
  71. package/lib/util/flattenColorPalette.js +9 -12
  72. package/lib/util/formatVariantSelector.js +184 -85
  73. package/lib/util/getAllConfigs.js +27 -8
  74. package/lib/util/hashConfig.js +6 -3
  75. package/lib/util/isKeyframeRule.js +5 -2
  76. package/lib/util/isPlainObject.js +5 -2
  77. package/lib/util/{isValidArbitraryValue.js → isSyntacticallyValidPropertyValue.js} +23 -15
  78. package/lib/util/log.js +20 -14
  79. package/lib/util/nameClass.js +20 -9
  80. package/lib/util/negateValue.js +23 -8
  81. package/lib/util/normalizeConfig.js +116 -72
  82. package/lib/util/normalizeScreens.js +120 -11
  83. package/lib/util/parseAnimationValue.js +42 -40
  84. package/lib/util/parseBoxShadowValue.js +30 -23
  85. package/lib/util/parseDependency.js +38 -56
  86. package/lib/util/parseGlob.js +34 -0
  87. package/lib/util/parseObjectStyles.js +11 -8
  88. package/lib/util/pluginUtils.js +147 -50
  89. package/lib/util/prefixSelector.js +10 -8
  90. package/lib/util/removeAlphaVariables.js +29 -0
  91. package/lib/util/resolveConfig.js +97 -85
  92. package/lib/util/resolveConfigPath.js +11 -9
  93. package/lib/util/responsive.js +8 -5
  94. package/lib/util/splitAtTopLevelOnly.js +43 -0
  95. package/lib/util/tap.js +4 -1
  96. package/lib/util/toColorValue.js +5 -3
  97. package/lib/util/toPath.js +20 -4
  98. package/lib/util/transformThemeValue.js +37 -29
  99. package/lib/util/validateConfig.js +24 -0
  100. package/lib/util/validateFormalSyntax.js +24 -0
  101. package/lib/util/withAlphaVariable.js +23 -15
  102. package/nesting/index.js +2 -12
  103. package/package.json +52 -46
  104. package/peers/index.js +11381 -7950
  105. package/plugin.d.ts +11 -0
  106. package/resolveConfig.d.ts +12 -0
  107. package/scripts/generate-types.js +105 -0
  108. package/scripts/release-channel.js +18 -0
  109. package/scripts/release-notes.js +21 -0
  110. package/scripts/type-utils.js +27 -0
  111. package/src/cli/build/deps.js +56 -0
  112. package/src/cli/build/index.js +49 -0
  113. package/src/cli/build/plugin.js +439 -0
  114. package/src/cli/build/utils.js +76 -0
  115. package/src/cli/build/watching.js +227 -0
  116. package/src/cli/help/index.js +70 -0
  117. package/src/cli/index.js +234 -0
  118. package/src/cli/init/index.js +50 -0
  119. package/src/cli/shared.js +6 -0
  120. package/src/cli-peer-dependencies.js +7 -1
  121. package/src/cli.js +4 -810
  122. package/src/corePluginList.js +1 -1
  123. package/src/corePlugins.js +532 -217
  124. package/src/css/preflight.css +5 -5
  125. package/src/featureFlags.js +15 -9
  126. package/src/index.js +4 -27
  127. package/src/lib/cacheInvalidation.js +52 -0
  128. package/src/lib/collapseAdjacentRules.js +21 -2
  129. package/src/lib/content.js +212 -0
  130. package/src/lib/defaultExtractor.js +196 -33
  131. package/src/lib/evaluateTailwindFunctions.js +78 -7
  132. package/src/lib/expandApplyAtRules.js +482 -183
  133. package/src/lib/expandTailwindAtRules.js +106 -85
  134. package/src/lib/findAtConfigPath.js +48 -0
  135. package/src/lib/generateRules.js +418 -129
  136. package/src/lib/normalizeTailwindDirectives.js +1 -0
  137. package/src/lib/offsets.js +270 -0
  138. package/src/lib/partitionApplyAtRules.js +52 -0
  139. package/src/lib/regex.js +74 -0
  140. package/src/lib/resolveDefaultsAtRules.js +51 -30
  141. package/src/lib/setupContextUtils.js +556 -208
  142. package/src/lib/setupTrackingContext.js +11 -48
  143. package/src/lib/sharedState.js +5 -0
  144. package/src/oxide/cli.d.ts +0 -0
  145. package/src/oxide/cli.ts +1 -0
  146. package/src/oxide/postcss-plugin.d.ts +0 -0
  147. package/src/oxide/postcss-plugin.ts +1 -0
  148. package/src/plugin.js +47 -0
  149. package/src/postcss-plugins/nesting/README.md +42 -0
  150. package/src/postcss-plugins/nesting/index.js +13 -0
  151. package/src/postcss-plugins/nesting/plugin.js +80 -0
  152. package/src/processTailwindFeatures.js +8 -0
  153. package/src/util/buildMediaQuery.js +5 -3
  154. package/src/util/cloneNodes.js +19 -2
  155. package/src/util/color.js +25 -21
  156. package/src/util/dataTypes.js +29 -21
  157. package/src/util/formatVariantSelector.js +184 -61
  158. package/src/util/getAllConfigs.js +19 -0
  159. package/src/util/{isValidArbitraryValue.js → isSyntacticallyValidPropertyValue.js} +1 -1
  160. package/src/util/log.js +8 -8
  161. package/src/util/nameClass.js +4 -0
  162. package/src/util/negateValue.js +11 -3
  163. package/src/util/normalizeConfig.js +44 -6
  164. package/src/util/normalizeScreens.js +99 -4
  165. package/src/util/parseBoxShadowValue.js +4 -3
  166. package/src/util/parseDependency.js +37 -42
  167. package/src/util/parseGlob.js +24 -0
  168. package/src/util/pluginUtils.js +132 -10
  169. package/src/util/prefixSelector.js +7 -5
  170. package/src/util/removeAlphaVariables.js +24 -0
  171. package/src/util/resolveConfig.js +70 -32
  172. package/src/util/splitAtTopLevelOnly.js +45 -0
  173. package/src/util/toPath.js +1 -1
  174. package/src/util/transformThemeValue.js +13 -3
  175. package/src/util/validateConfig.js +13 -0
  176. package/src/util/validateFormalSyntax.js +34 -0
  177. package/src/util/withAlphaVariable.js +1 -1
  178. package/stubs/defaultConfig.stub.js +167 -164
  179. package/stubs/simpleConfig.stub.js +1 -0
  180. package/types/config.d.ts +362 -0
  181. package/types/generated/.gitkeep +0 -0
  182. package/types/generated/colors.d.ts +276 -0
  183. package/types/generated/corePluginList.d.ts +1 -0
  184. package/types/generated/default-theme.d.ts +342 -0
  185. package/types/index.d.ts +7 -0
  186. package/nesting/plugin.js +0 -41
@@ -0,0 +1,439 @@
1
+ // @ts-check
2
+
3
+ import path from 'path'
4
+ import fs from 'fs'
5
+ import postcssrc from 'postcss-load-config'
6
+ import { lilconfig } from 'lilconfig'
7
+ import loadPlugins from 'postcss-load-config/src/plugins' // Little bit scary, looking at private/internal API
8
+ import loadOptions from 'postcss-load-config/src/options' // Little bit scary, looking at private/internal API
9
+
10
+ import tailwind from '../../processTailwindFeatures'
11
+ import { loadAutoprefixer, loadCssNano, loadPostcss, loadPostcssImport } from './deps'
12
+ import { formatNodes, drainStdin, outputFile } from './utils'
13
+ import { env } from '../shared'
14
+ import resolveConfig from '../../../resolveConfig.js'
15
+ import getModuleDependencies from '../../lib/getModuleDependencies.js'
16
+ import { parseCandidateFiles } from '../../lib/content.js'
17
+ import { createWatcher } from './watching.js'
18
+ import fastGlob from 'fast-glob'
19
+ import { findAtConfigPath } from '../../lib/findAtConfigPath.js'
20
+ import log from '../../util/log'
21
+
22
+ /**
23
+ *
24
+ * @param {string} [customPostCssPath ]
25
+ * @returns
26
+ */
27
+ async function loadPostCssPlugins(customPostCssPath) {
28
+ let config = customPostCssPath
29
+ ? await (async () => {
30
+ let file = path.resolve(customPostCssPath)
31
+
32
+ // Implementation, see: https://unpkg.com/browse/postcss-load-config@3.1.0/src/index.js
33
+ // @ts-ignore
34
+ let { config = {} } = await lilconfig('postcss').load(file)
35
+ if (typeof config === 'function') {
36
+ config = config()
37
+ } else {
38
+ config = Object.assign({}, config)
39
+ }
40
+
41
+ if (!config.plugins) {
42
+ config.plugins = []
43
+ }
44
+
45
+ return {
46
+ file,
47
+ plugins: loadPlugins(config, file),
48
+ options: loadOptions(config, file),
49
+ }
50
+ })()
51
+ : await postcssrc()
52
+
53
+ let configPlugins = config.plugins
54
+
55
+ let configPluginTailwindIdx = configPlugins.findIndex((plugin) => {
56
+ if (typeof plugin === 'function' && plugin.name === 'tailwindcss') {
57
+ return true
58
+ }
59
+
60
+ if (typeof plugin === 'object' && plugin !== null && plugin.postcssPlugin === 'tailwindcss') {
61
+ return true
62
+ }
63
+
64
+ return false
65
+ })
66
+
67
+ let beforePlugins =
68
+ configPluginTailwindIdx === -1 ? [] : configPlugins.slice(0, configPluginTailwindIdx)
69
+ let afterPlugins =
70
+ configPluginTailwindIdx === -1
71
+ ? configPlugins
72
+ : configPlugins.slice(configPluginTailwindIdx + 1)
73
+
74
+ return [beforePlugins, afterPlugins, config.options]
75
+ }
76
+
77
+ function loadBuiltinPostcssPlugins() {
78
+ let postcss = loadPostcss()
79
+ let IMPORT_COMMENT = '__TAILWIND_RESTORE_IMPORT__: '
80
+ return [
81
+ [
82
+ (root) => {
83
+ root.walkAtRules('import', (rule) => {
84
+ if (rule.params.slice(1).startsWith('tailwindcss/')) {
85
+ rule.after(postcss.comment({ text: IMPORT_COMMENT + rule.params }))
86
+ rule.remove()
87
+ }
88
+ })
89
+ },
90
+ loadPostcssImport(),
91
+ (root) => {
92
+ root.walkComments((rule) => {
93
+ if (rule.text.startsWith(IMPORT_COMMENT)) {
94
+ rule.after(
95
+ postcss.atRule({
96
+ name: 'import',
97
+ params: rule.text.replace(IMPORT_COMMENT, ''),
98
+ })
99
+ )
100
+ rule.remove()
101
+ }
102
+ })
103
+ },
104
+ ],
105
+ [],
106
+ {},
107
+ ]
108
+ }
109
+
110
+ let state = {
111
+ /** @type {any} */
112
+ context: null,
113
+
114
+ /** @type {ReturnType<typeof createWatcher> | null} */
115
+ watcher: null,
116
+
117
+ /** @type {{content: string, extension: string}[]} */
118
+ changedContent: [],
119
+
120
+ configDependencies: new Set(),
121
+ contextDependencies: new Set(),
122
+
123
+ /** @type {import('../../lib/content.js').ContentPath[]} */
124
+ contentPaths: [],
125
+
126
+ refreshContentPaths() {
127
+ this.contentPaths = parseCandidateFiles(this.context, this.context?.tailwindConfig)
128
+ },
129
+
130
+ get config() {
131
+ return this.context.tailwindConfig
132
+ },
133
+
134
+ get contentPatterns() {
135
+ return {
136
+ all: this.contentPaths.map((contentPath) => contentPath.pattern),
137
+ dynamic: this.contentPaths
138
+ .filter((contentPath) => contentPath.glob !== undefined)
139
+ .map((contentPath) => contentPath.pattern),
140
+ }
141
+ },
142
+
143
+ loadConfig(configPath, content) {
144
+ if (this.watcher && configPath) {
145
+ this.refreshConfigDependencies(configPath)
146
+ }
147
+
148
+ let config = configPath ? require(configPath) : {}
149
+
150
+ // @ts-ignore
151
+ config = resolveConfig(config, { content: { files: [] } })
152
+
153
+ // Override content files if `--content` has been passed explicitly
154
+ if (content?.length > 0) {
155
+ config.content.files = content
156
+ }
157
+
158
+ return config
159
+ },
160
+
161
+ refreshConfigDependencies(configPath) {
162
+ env.DEBUG && console.time('Module dependencies')
163
+
164
+ for (let file of this.configDependencies) {
165
+ delete require.cache[require.resolve(file)]
166
+ }
167
+
168
+ if (configPath) {
169
+ let deps = getModuleDependencies(configPath).map(({ file }) => file)
170
+
171
+ for (let dependency of deps) {
172
+ this.configDependencies.add(dependency)
173
+ }
174
+ }
175
+
176
+ env.DEBUG && console.timeEnd('Module dependencies')
177
+ },
178
+
179
+ readContentPaths() {
180
+ let content = []
181
+
182
+ // Resolve globs from the content config
183
+ // TODO: When we make the postcss plugin async-capable this can become async
184
+ let files = fastGlob.sync(this.contentPatterns.all)
185
+
186
+ for (let file of files) {
187
+ if (env.OXIDE) {
188
+ content.push({
189
+ file,
190
+ extension: path.extname(file).slice(1),
191
+ })
192
+ } else {
193
+ content.push({
194
+ content: fs.readFileSync(path.resolve(file), 'utf8'),
195
+ extension: path.extname(file).slice(1),
196
+ })
197
+ }
198
+ }
199
+
200
+ // Resolve raw content in the tailwind config
201
+ let rawContent = this.config.content.files.filter((file) => {
202
+ return file !== null && typeof file === 'object'
203
+ })
204
+
205
+ for (let { raw: htmlContent, extension = 'html' } of rawContent) {
206
+ content.push({ content: htmlContent, extension })
207
+ }
208
+
209
+ return content
210
+ },
211
+
212
+ getContext({ createContext, cliConfigPath, root, result, content }) {
213
+ if (this.context) {
214
+ this.context.changedContent = this.changedContent.splice(0)
215
+
216
+ return this.context
217
+ }
218
+
219
+ env.DEBUG && console.time('Searching for config')
220
+ let configPath = findAtConfigPath(root, result) ?? cliConfigPath
221
+ env.DEBUG && console.timeEnd('Searching for config')
222
+
223
+ env.DEBUG && console.time('Loading config')
224
+ let config = this.loadConfig(configPath, content)
225
+ env.DEBUG && console.timeEnd('Loading config')
226
+
227
+ env.DEBUG && console.time('Creating context')
228
+ this.context = createContext(config, [])
229
+ Object.assign(this.context, {
230
+ userConfigPath: configPath,
231
+ })
232
+ env.DEBUG && console.timeEnd('Creating context')
233
+
234
+ env.DEBUG && console.time('Resolving content paths')
235
+ this.refreshContentPaths()
236
+ env.DEBUG && console.timeEnd('Resolving content paths')
237
+
238
+ if (this.watcher) {
239
+ env.DEBUG && console.time('Watch new files')
240
+ this.watcher.refreshWatchedFiles()
241
+ env.DEBUG && console.timeEnd('Watch new files')
242
+ }
243
+
244
+ for (let file of this.readContentPaths()) {
245
+ this.context.changedContent.push(file)
246
+ }
247
+
248
+ return this.context
249
+ },
250
+ }
251
+
252
+ export async function createProcessor(args, cliConfigPath) {
253
+ let postcss = loadPostcss()
254
+
255
+ let input = args['--input']
256
+ let output = args['--output']
257
+ let includePostCss = args['--postcss']
258
+ let customPostCssPath = typeof args['--postcss'] === 'string' ? args['--postcss'] : undefined
259
+
260
+ let [beforePlugins, afterPlugins, postcssOptions] = includePostCss
261
+ ? await loadPostCssPlugins(customPostCssPath)
262
+ : loadBuiltinPostcssPlugins()
263
+
264
+ if (args['--purge']) {
265
+ log.warn('purge-flag-deprecated', [
266
+ 'The `--purge` flag has been deprecated.',
267
+ 'Please use `--content` instead.',
268
+ ])
269
+
270
+ if (!args['--content']) {
271
+ args['--content'] = args['--purge']
272
+ }
273
+ }
274
+
275
+ let content = args['--content']?.split(/(?<!{[^}]+),/) ?? []
276
+
277
+ let tailwindPlugin = () => {
278
+ return {
279
+ postcssPlugin: 'tailwindcss',
280
+ Once(root, { result }) {
281
+ env.DEBUG && console.time('Compiling CSS')
282
+ tailwind(({ createContext }) => {
283
+ console.error()
284
+ console.error('Rebuilding...')
285
+
286
+ return () => {
287
+ return state.getContext({
288
+ createContext,
289
+ cliConfigPath,
290
+ root,
291
+ result,
292
+ content,
293
+ })
294
+ }
295
+ })(root, result)
296
+ env.DEBUG && console.timeEnd('Compiling CSS')
297
+ },
298
+ }
299
+ }
300
+
301
+ tailwindPlugin.postcss = true
302
+
303
+ let plugins = [
304
+ ...beforePlugins,
305
+ tailwindPlugin,
306
+ !args['--minify'] && formatNodes,
307
+ ...afterPlugins,
308
+ !args['--no-autoprefixer'] && loadAutoprefixer(),
309
+ args['--minify'] && loadCssNano(),
310
+ ].filter(Boolean)
311
+
312
+ /** @type {import('postcss').Processor} */
313
+ // @ts-ignore
314
+ let processor = postcss(plugins)
315
+
316
+ async function readInput() {
317
+ // Piping in data, let's drain the stdin
318
+ if (input === '-') {
319
+ return drainStdin()
320
+ }
321
+
322
+ // Input file has been provided
323
+ if (input) {
324
+ return fs.promises.readFile(path.resolve(input), 'utf8')
325
+ }
326
+
327
+ // No input file provided, fallback to default atrules
328
+ return '@tailwind base; @tailwind components; @tailwind utilities'
329
+ }
330
+
331
+ async function build() {
332
+ let start = process.hrtime.bigint()
333
+
334
+ return readInput()
335
+ .then((css) => processor.process(css, { ...postcssOptions, from: input, to: output }))
336
+ .then((result) => {
337
+ if (!state.watcher) {
338
+ return result
339
+ }
340
+
341
+ env.DEBUG && console.time('Recording PostCSS dependencies')
342
+ for (let message of result.messages) {
343
+ if (message.type === 'dependency') {
344
+ state.contextDependencies.add(message.file)
345
+ }
346
+ }
347
+ env.DEBUG && console.timeEnd('Recording PostCSS dependencies')
348
+
349
+ // TODO: This needs to be in a different spot
350
+ env.DEBUG && console.time('Watch new files')
351
+ state.watcher.refreshWatchedFiles()
352
+ env.DEBUG && console.timeEnd('Watch new files')
353
+
354
+ return result
355
+ })
356
+ .then((result) => {
357
+ if (!output) {
358
+ process.stdout.write(result.css)
359
+ return
360
+ }
361
+
362
+ return Promise.all([
363
+ outputFile(result.opts.to, result.css),
364
+ result.map && outputFile(result.opts.to + '.map', result.map.toString()),
365
+ ])
366
+ })
367
+ .then(() => {
368
+ let end = process.hrtime.bigint()
369
+ console.error()
370
+ console.error('Done in', (end - start) / BigInt(1e6) + 'ms.')
371
+ })
372
+ .then(
373
+ () => {},
374
+ (err) => {
375
+ // TODO: If an initial build fails we can't easily pick up any PostCSS dependencies
376
+ // that were collected before the error occurred
377
+ // The result is not stored on the error so we have to store it externally
378
+ // and pull the messages off of it here somehow
379
+
380
+ // This results in a less than ideal DX because the watcher will not pick up
381
+ // changes to imported CSS if one of them caused an error during the initial build
382
+ // If you fix it and then save the main CSS file so there's no error
383
+ // The watcher will start watching the imported CSS files and will be
384
+ // resilient to future errors.
385
+
386
+ console.error(err)
387
+ }
388
+ )
389
+ }
390
+
391
+ /**
392
+ * @param {{file: string, content(): Promise<string>, extension: string}[]} changes
393
+ */
394
+ async function parseChanges(changes) {
395
+ return Promise.all(
396
+ changes.map(async (change) => ({
397
+ content: await change.content(),
398
+ extension: change.extension,
399
+ }))
400
+ )
401
+ }
402
+
403
+ if (input !== undefined && input !== '-') {
404
+ state.contextDependencies.add(path.resolve(input))
405
+ }
406
+
407
+ return {
408
+ build,
409
+ watch: async () => {
410
+ state.watcher = createWatcher(args, {
411
+ state,
412
+
413
+ /**
414
+ * @param {{file: string, content(): Promise<string>, extension: string}[]} changes
415
+ */
416
+ async rebuild(changes) {
417
+ let needsNewContext = changes.some((change) => {
418
+ return (
419
+ state.configDependencies.has(change.file) ||
420
+ state.contextDependencies.has(change.file)
421
+ )
422
+ })
423
+
424
+ if (needsNewContext) {
425
+ state.context = null
426
+ } else {
427
+ for (let change of await parseChanges(changes)) {
428
+ state.changedContent.push(change)
429
+ }
430
+ }
431
+
432
+ return build()
433
+ },
434
+ })
435
+
436
+ await build()
437
+ },
438
+ }
439
+ }
@@ -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
+ }