aliascss 1.4.7 → 1.5.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.
@@ -1,81 +1,145 @@
1
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
2
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
3
+ return new (P || (P = Promise))(function (resolve, reject) {
4
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
8
+ });
9
+ };
1
10
  import extractClassNamesFromFile from "./extractClassNamesFromFile.js";
2
11
  import { compiler as statementMaker } from "../returnStatement.js";
3
- import config from '../config.js';
12
+ import config from "../config.js";
4
13
  import fs from "fs";
5
14
  import fg from "fast-glob";
6
- import path from 'path';
7
- import postcss from 'postcss';
8
- import postcssDiscardDuplicates from 'postcss-discard-duplicates';
9
- import cssnano from 'cssnano';
10
- import chokidar from 'chokidar';
11
- import sortMediaQueries from 'postcss-sort-media-queries';
12
- import { splitByCommaOutsideParens } from '../utils/helper.js';
15
+ import path from "path";
16
+ import postcss from "postcss";
17
+ import postcssDiscardDuplicates from "postcss-discard-duplicates";
18
+ import cssnano from "cssnano";
19
+ import chokidar from "chokidar";
20
+ import sortMediaQueries from "postcss-sort-media-queries";
21
+ import { splitByCommaOutsideParens } from "../utils/helper.js";
13
22
  const init = {
14
- classList: [], // hold className for MasterCSS to avoid repeating
23
+ classList: [],
15
24
  groups: [],
16
- input: '', // input glob pattern
17
- output: '', // location off output
18
- '--file': false, // if set true compileFileByFile to [filename].css
25
+ input: "",
26
+ output: "",
27
+ "--file": false,
19
28
  statementMaker,
20
29
  config,
21
- '--module': false,
22
- rawCSS: '',
30
+ "--module": false,
31
+ rawCSS: "",
23
32
  layers: [],
24
33
  initializedLayer: false,
25
- customGroupStatement: '',
34
+ customGroupStatement: "",
26
35
  minify: false,
27
- globPattern: '', // Use this to check valid new created file to add to watch during watch.on
36
+ globPattern: "",
28
37
  };
29
38
  export default function main(config) {
30
- // initialize
31
- initialize(config);
32
- if (init.config.prefix)
33
- init.statementMaker.prefix = init.config.prefix;
34
- if (init.input && (init.output || init['--file'])) {
35
- const input = fg.sync(init.input, { dot: true });
36
- // console.log(input);
37
- input.forEach((file) => {
38
- createCSSFileByFile(file);
39
- });
40
- postify(init.output, [postcssDiscardDuplicates], init.minify);
41
- }
42
- else {
43
- console.error("Please Provide input, output or set '--file' to true");
44
- }
39
+ return __awaiter(this, void 0, void 0, function* () {
40
+ initialize(config);
41
+ if (init.config.prefix)
42
+ init.statementMaker.prefix = init.config.prefix;
43
+ if (init.input && (init.output || init["--file"])) {
44
+ fileCache.clear();
45
+ // Per-file outputs (.css / .module.css) only when one of them is turned on,
46
+ // and awaited: before, these ran in the background and errors were lost.
47
+ if (init["--file"] || init["--module"]) {
48
+ const input = fg.sync(init.input, { dot: true });
49
+ yield Promise.all(input.map((file) => createCSSFileByFile(file, true)));
50
+ }
51
+ if (init.output) {
52
+ yield globalCSSCompiler();
53
+ }
54
+ }
55
+ else {
56
+ console.error("Please Provide input, output or set '--file' to true");
57
+ }
58
+ });
59
+ }
60
+ // ---------------------------------------------------------------------------
61
+ // Build state for the main output file
62
+ // ---------------------------------------------------------------------------
63
+ const fileCache = new Map(); // absolute file path → its compiled CSS
64
+ let building = null; // the build that is running right now
65
+ let rebuildQueued = false; // a change arrived during that build
66
+ function preamble() {
67
+ let css = "";
68
+ if (Array.isArray(init.layers) && init.layers.length > 0) {
69
+ css += `@layer ${init.layers.join(", ")};\n\n`;
70
+ init.initializedLayer = true;
71
+ }
72
+ if (init.rawCSS) {
73
+ css += `/* Start :-----------ACSS:From aliasCSSConfig.statement------------------------*/\n${init.rawCSS}\n/* End :-----------ACSS aliasCSSConfig.statement----------------------------*/\n\n`;
74
+ }
75
+ if (init.customGroupStatement) {
76
+ css += `/* Start :-----------ACSS:From aliasCSSConfig.group------------------------*/\n${init.customGroupStatement}\n/* End :-----------ACSS aliasCSSConfig.group----------------------------*/\n\n`;
77
+ }
78
+ return css;
45
79
  }
80
+ function buildOnce() {
81
+ return __awaiter(this, void 0, void 0, function* () {
82
+ const files = fg.sync(init.globPattern, { dot: true, absolute: true });
83
+ const current = new Set(files);
84
+ for (const key of fileCache.keys())
85
+ if (!current.has(key))
86
+ fileCache.delete(key); // deleted files
87
+ let css = preamble();
88
+ for (const file of files) {
89
+ let fileCss = fileCache.get(file);
90
+ if (fileCss === undefined) {
91
+ try {
92
+ fileCss = compileFile(file, config, statementMaker, [])[0];
93
+ }
94
+ catch (error) {
95
+ console.log('\x1b[31m', "AliasCSS couldn't compile " + path.relative(".", file));
96
+ console.log(error);
97
+ fileCss = "";
98
+ }
99
+ fileCache.set(file, fileCss);
100
+ }
101
+ const name = path.relative(".", file);
102
+ css += `/* Start :-----------ACSS ${name}------------------------*/\n${fileCss}\n/* End :-----------ACSS ${name}----------------------------*/\n\n`;
103
+ }
104
+ // Same rule appearing in several files is removed here (postcss-discard-duplicates)
105
+ css = yield postcssProcess(css, [postcssDiscardDuplicates], init.minify);
106
+ // Write once, atomically: a dev server never sees a half-written or empty file
107
+ const tmp = init.output + ".tmp";
108
+ fs.writeFileSync(tmp, css);
109
+ fs.renameSync(tmp, init.output);
110
+ console.log(`AliasCSS compiled ${files.length} file(s) to ${init.output}`);
111
+ });
112
+ }
113
+ // Builds the main CSS file. Only files that changed since the last build are
114
+ // recompiled (the rest come from fileCache). Calls that arrive while a build is
115
+ // running don't start a second build that writes the same file at the same time:
116
+ // they mark the build as dirty and it runs once more when it finishes.
46
117
  export function globalCSSCompiler() {
47
- const classList = [];
48
- if (init.globPattern && init.output) {
49
- fs.truncateSync(init.output);
50
- // 1. Write @layer once at the top of the freshly truncated file
51
- if (Array.isArray(init.layers) && init.layers.length > 0) {
52
- fs.writeFileSync(init.output, `@layer ${init.layers.join(', ')};\n\n`, { flag: 'a+' });
53
- init.initializedLayer = true;
118
+ return __awaiter(this, void 0, void 0, function* () {
119
+ if (!init.globPattern || !init.output) {
120
+ console.error("Please Provide input, output or set '--file' to true");
121
+ return;
54
122
  }
55
- const input = fg.sync(init.globPattern, { dot: true });
56
- // console.log(input);
57
- input.forEach((file) => {
58
- const [gbContent,] = compileFile(file, config, statementMaker, classList);
59
- try {
60
- fs.writeFileSync(init.output, `/* Start :-----------ACSS ${path.relative('.', file)}------------------------*/\n${gbContent}
61
- \n/* End :-----------ACSS ${path.relative('.', file)}----------------------------*/\n
62
- `, { flag: 'a+' });
63
- console.log('AliasCSS compiled', path.relative('.', file), 'to main css file :' + init.output);
64
- }
65
- catch (error) {
66
- console.log('\x1b[31m', "Couldn't able to append/create to main css file :" + init.output);
67
- console.log(error);
68
- }
69
- });
70
- postify(init.output, [postcssDiscardDuplicates], init.minify);
71
- }
72
- else {
73
- console.error("Please Provide input, output or set '--file' to true");
74
- }
123
+ if (building) {
124
+ rebuildQueued = true;
125
+ return building;
126
+ }
127
+ building = (() => __awaiter(this, void 0, void 0, function* () {
128
+ do {
129
+ rebuildQueued = false;
130
+ yield buildOnce();
131
+ } while (rebuildQueued);
132
+ }))();
133
+ try {
134
+ yield building;
135
+ }
136
+ finally {
137
+ building = null;
138
+ }
139
+ });
75
140
  }
76
141
  export function compileFile(file, config, statementMaker, globalClassList) {
77
- let [globalStatement, compiledStatement, moduleStatement] = ['', '', ''];
78
- // inject config.group and config.statement
142
+ let [globalStatement, compiledStatement, moduleStatement] = ["", "", ""];
79
143
  if (statementMaker.rawCSS) {
80
144
  compiledStatement += `/* From:aliacss.config.statement */\n${statementMaker.rawCSS}\n/* -----End:aliacss.config.statement----- */\n\n`;
81
145
  moduleStatement += `/* From:aliacss.config.statement */\n${statementMaker.rawCSS}\n/* ------End:aliacss.config.statement----- */\n\n`;
@@ -85,295 +149,242 @@ export function compileFile(file, config, statementMaker, globalClassList) {
85
149
  moduleStatement += `/* From:aliacss.config.group */\n${statementMaker.customGroupStatement}\n/* -----End:aliacss.config.group----- */\n\n`;
86
150
  }
87
151
  const [classList, groups, keyframe, rawCSSStatement] = extractClassNamesFromFile(file, config);
88
- // 1. raw-css
89
152
  if (rawCSSStatement) {
90
- globalStatement += rawCSSStatement + '\n';
91
- compiledStatement += rawCSSStatement + '\n';
153
+ globalStatement += rawCSSStatement + "\n";
154
+ compiledStatement += rawCSSStatement + "\n";
92
155
  }
93
- // 2. group
94
156
  for (const key in groups) {
95
- if (groups.hasOwnProperty(key)) {
96
- // --------------ModuleStatement
157
+ if (Object.prototype.hasOwnProperty.call(groups, key)) {
97
158
  if (/^module=/.test(key)) {
98
- const mdStatement = statementMaker.group(groups[key], key.replace(/module=/, ''));
99
- moduleStatement += mdStatement + '\n';
159
+ moduleStatement += statementMaker.group(groups[key], key.replace(/module=/, "")) + "\n";
100
160
  }
101
- // -------------EndOfModule
102
161
  else {
103
162
  const gpStatement = statementMaker.group(groups[key], key);
104
- globalStatement += gpStatement + '\n';
105
- compiledStatement += gpStatement + '\n';
163
+ globalStatement += gpStatement + "\n";
164
+ compiledStatement += gpStatement + "\n";
106
165
  }
107
166
  }
108
167
  }
109
- // 2. ClassList
110
168
  classList.forEach((e) => {
111
169
  const statement = statementMaker.make(e);
112
170
  if (statement) {
113
- console.log('\x1b[32m', statement);
114
171
  if (globalClassList.indexOf(e) === -1) {
115
- globalStatement += statement + '\n';
172
+ globalStatement += statement + "\n";
116
173
  globalClassList.push(e);
117
- // console.log(e);
118
174
  }
119
- compiledStatement += statement + '\n';
175
+ compiledStatement += statement + "\n";
120
176
  }
121
177
  });
122
- // 3. Keyframe
123
178
  for (const key in keyframe) {
124
- if (keyframe.hasOwnProperty(key)) {
179
+ if (Object.prototype.hasOwnProperty.call(keyframe, key)) {
125
180
  const kfStatement = keyframesStatement(key, keyframe[key], statementMaker);
126
- globalStatement += kfStatement + '\n';
127
- compiledStatement += kfStatement + '\n';
181
+ globalStatement += kfStatement + "\n";
182
+ compiledStatement += kfStatement + "\n";
128
183
  }
129
184
  }
130
185
  return [globalStatement, compiledStatement, moduleStatement];
131
186
  }
132
187
  export function groupStatement(name, classNames, statementMaker) {
133
- return statementMaker.group(classNames, name) + '\n';
188
+ return statementMaker.group(classNames, name) + "\n";
134
189
  }
135
190
  export function keyframesStatement(name, timeLine, statementMaker) {
136
- let kfStatement = '@keyframes ' + name + "{\n";
191
+ let kfStatement = "@keyframes " + name + "{\n";
137
192
  const returnPnV = (e) => e.map((i) => statementMaker.make(i, null, true)).join(";");
138
193
  const split = timeLine.split(/\s+/);
139
194
  split.forEach((each) => {
140
195
  try {
141
- const [at, pNv] = each.replace(/\]\[/, ']-[').replace("-", "=").split("=");
142
- // kfStatement+=` ${at.replace('@','').replace(/:/g,',').replace(/,/g,"%,").replace(/[\[|\]]/g,'')}% {${returnPnV(pNv.replace(/^\[|\]$/g,'').split(','))}}`
143
- kfStatement += ` ${at.replace('@', '').replace(/:/g, ',').replace(/,/g, "%,").replace(/[\[|\]]/g, '')}% {${returnPnV(splitByCommaOutsideParens(pNv.replace(/^\[|\]$/g, '')))}}`;
196
+ const [at, pNv] = each.replace(/\]\[/, "]-[").replace("-", "=").split("=");
197
+ kfStatement += ` ${at.replace("@", "").replace(/:/g, ",").replace(/,/g, "%,").replace(/[\[|\]]/g, "")}% {${returnPnV(splitByCommaOutsideParens(pNv.replace(/^\[|\]$/g, "")))}}`;
144
198
  }
145
199
  catch (error) {
146
- console.error('Not a valid entry for AliasCSS keyframes processor : ' + each, error);
200
+ console.error("Not a valid entry for AliasCSS keyframes processor : " + each, error);
147
201
  }
148
202
  });
149
203
  return kfStatement + "\n}\n";
150
204
  }
151
- export function createCSSFileByFile(file, bool = false) {
152
- const [gbContent, content, module] = compileFile(file, config, statementMaker, init.classList);
153
- // console.log(init.classList);
154
- // If its fileByFile
155
- if (init["--module"] && module.trim()) {
156
- try {
157
- fs.writeFileSync(file + '.module.css', module);
158
- // console.log(content);
159
- console.log('AliasCSS compiled', path.relative('.', file), 'module Locally ');
160
- }
161
- catch (error) {
162
- console.log('\x1b[31m', "Couldn't able to append/create locally from " + file);
163
- console.log(error);
164
- }
165
- }
166
- if (init["--file"]) {
167
- try {
168
- fs.writeFileSync(file + '.css', content);
169
- postify(file + '.css', [postcssDiscardDuplicates], init.minify);
170
- // console.log(content);
171
- console.log('AliasCSS compiled', path.relative('.', file), 'Locally');
172
- }
173
- catch (error) {
174
- console.log('\x1b[31m', "Couldn't able to append/create locally from " + file);
175
- console.log(error);
176
- }
177
- }
178
- // Check for Global
179
- if (!bool && init.output) {
180
- try {
181
- fs.writeFileSync(init.output, `\n/* Start :-----------ACSS ${path.relative('.', file)}------------------------*/\n${postcss([postcssDiscardDuplicates]).process(gbContent)}
182
- \n/* End :-----------ACSS ${path.relative('.', file)}----------------------------*/\n
183
- `, { flag: 'a+' });
184
- console.log('AliasCSS compiled', path.relative('.', file), 'to main css file :' + init.output);
205
+ export function createCSSFileByFile(file_1) {
206
+ return __awaiter(this, arguments, void 0, function* (file, bool = false) {
207
+ if (!fs.existsSync(file))
208
+ return;
209
+ const [, content, module] = compileFile(file, config, statementMaker, []);
210
+ if (init["--module"] && module.trim()) {
211
+ try {
212
+ fs.writeFileSync(file + ".module.css", module);
213
+ console.log("AliasCSS compiled", path.relative(".", file), "module Locally ");
214
+ }
215
+ catch (error) {
216
+ console.log('\x1b[31m', "Couldn't able to append/create locally from " + file);
217
+ console.log(error);
218
+ }
185
219
  }
186
- catch (error) {
187
- console.log('\x1b[31m', "Couldn't able to append/create to main css file :" + init.output);
188
- console.log(error);
220
+ if (init["--file"]) {
221
+ try {
222
+ fs.writeFileSync(file + ".css", content);
223
+ yield postify(file + ".css", [postcssDiscardDuplicates], init.minify);
224
+ console.log("AliasCSS compiled", path.relative(".", file), "Locally");
225
+ }
226
+ catch (error) {
227
+ console.log('\x1b[31m', "Couldn't able to append/create locally from " + file);
228
+ console.log(error);
229
+ }
189
230
  }
190
- }
231
+ });
191
232
  }
192
- export function postify(file, plugin, minify = false, sort = "mobile-first") {
193
- const data = fs.readFileSync(file, 'utf-8');
194
- plugin.push(sortMediaQueries({
195
- sort
196
- }));
197
- if (fs.existsSync(file)) {
198
- if (minify === true)
199
- plugin.push(cssnano);
200
- postcss(plugin).process(data, { from: undefined }).then(result => {
201
- fs.truncateSync(file);
202
- fs.writeFileSync(file, result.css);
203
- });
204
- }
205
- // fs.readFile(file, (err, css) => {
206
- // postcss(plugin)
207
- // .process(css, { from: file, to: file+"post.css" })
208
- // .then(result => {
209
- // fs.writeFile(file+"post.css", result.css, () => true)
210
- // // if ( result.map ) {
211
- // // fs.writeFile(file+'.map', result.map.toString(), () => true)
212
- // // }
213
- // })
214
- // })
233
+ export function postcssProcess(css_1, plugin_1) {
234
+ return __awaiter(this, arguments, void 0, function* (css, plugin, minify = false, sort = "mobile-first") {
235
+ const plugins = [...plugin, sortMediaQueries({ sort })];
236
+ if (minify)
237
+ plugins.push(cssnano);
238
+ const result = yield postcss(plugins).process(css, { from: undefined });
239
+ return result.css;
240
+ });
241
+ }
242
+ export function postify(file_1, plugin_1) {
243
+ return __awaiter(this, arguments, void 0, function* (file, plugin, minify = false, sort = "mobile-first") {
244
+ if (!fs.existsSync(file))
245
+ return;
246
+ const data = fs.readFileSync(file, "utf-8");
247
+ fs.writeFileSync(file, yield postcssProcess(data, plugin, minify, sort));
248
+ });
215
249
  }
216
250
  export function writeStatementToFile(file, content, from) {
217
- // Check for Global
218
251
  if (init.output) {
219
252
  try {
220
- fs.writeFileSync(init.output, `\n/* Start :-----------ACSS:From aliasCSSConfig.${from}------------------------*/\n${content}
221
- \n/* End :-----------ACSS aliasCSSConfig.${from}----------------------------*/\n
222
- `, { flag: 'a+' });
223
- console.log('AliasCSS compiled', '[aliasCSSConfig.statement]', 'aliascss.config.js');
253
+ fs.writeFileSync(init.output, `\n/* Start :-----------ACSS:From aliasCSSConfig.${from}------------------------*/\n${content}\n/* End :-----------ACSS aliasCSSConfig.${from}----------------------------*/\n`, { flag: "a+" });
254
+ console.log("AliasCSS compiled", `[aliasCSSConfig.${from}]`, "aliascss.config.js");
224
255
  }
225
256
  catch (error) {
226
- console.log('\x1b[31m', "Couldn't able to append/create [key:statement] from alias.config.js ");
257
+ console.log('\x1b[31m', `Couldn't able to append/create [key:${from}] from alias.config.js`);
227
258
  console.log(error);
228
259
  }
229
260
  }
230
261
  }
231
- // Initialize
232
262
  export function initialize(configFile) {
233
- // ----------------input-------------------
234
- if (configFile.hasOwnProperty('input')) {
263
+ if (configFile.hasOwnProperty("input")) {
235
264
  init.input = configFile.input;
236
265
  init.globPattern = configFile.input;
237
266
  }
238
- // ----------------input-------------------
239
- if (configFile.hasOwnProperty('layers') && Array.isArray(configFile.layers)) {
267
+ if (configFile.hasOwnProperty("layers") && Array.isArray(configFile.layers)) {
240
268
  init.layers = configFile.layers;
241
269
  }
242
270
  else {
243
271
  init.layers = config.layers;
244
272
  }
245
- // ----------------Prefix-------------------
246
- if (configFile.hasOwnProperty('prefix')) {
273
+ if (configFile.hasOwnProperty("prefix")) {
247
274
  init.config.prefix = configFile.prefix;
248
275
  }
249
- // ----------------output-------------------
250
- if (configFile.hasOwnProperty('output')) {
276
+ if (configFile.hasOwnProperty("output")) {
251
277
  const op = configFile.output;
252
- if (op.hasOwnProperty('location')) {
278
+ if (op.hasOwnProperty("location"))
253
279
  init.output = op.location;
254
- }
255
- if (op.hasOwnProperty('--file') && op['--file'] === true) {
280
+ if (op.hasOwnProperty("--file") && op["--file"] === true)
256
281
  init["--file"] = true;
257
- }
258
282
  }
259
- // Adding Custom color, length etc
260
- if (configFile.hasOwnProperty('custom') && typeof configFile.custom === 'object') {
283
+ if (configFile.hasOwnProperty("custom") && typeof configFile.custom === "object") {
261
284
  Object.keys(configFile.custom).forEach((key) => {
262
285
  init.statementMaker.addCustom(key, configFile.custom[key]);
263
286
  });
264
287
  }
265
- // Extend custom class name define {'border-color-native":'border-color: skyBlue',}
266
- if (configFile.hasOwnProperty('prebuild')) {
288
+ if (configFile.hasOwnProperty("prebuild")) {
267
289
  init.statementMaker.prebuild(configFile.prebuild);
268
290
  }
269
- // Ignore these class name
270
- if (configFile.hasOwnProperty('ignore')) {
271
- if (Array.isArray(configFile.ignore)) {
272
- configFile.ignore.forEach((each) => init.config.ignore.push(each.trim()));
273
- }
291
+ if (configFile.hasOwnProperty("ignore") && Array.isArray(configFile.ignore)) {
292
+ configFile.ignore.forEach((each) => init.config.ignore.push(each.trim()));
274
293
  }
275
- // --module
276
- if (configFile.hasOwnProperty('--module') && configFile.hasOwnProperty('importModuleAs')) {
294
+ if (configFile.hasOwnProperty("--module") && configFile.hasOwnProperty("importModuleAs")) {
277
295
  init["--module"] = true;
278
- init.config.useCSSModule = init["--module"] ? true : false;
279
- if (init.config.useCSSModule)
280
- init.config.matchCSSModuleFunction = init.config.createCSSModuleRegex(configFile.importModuleAs);
296
+ init.config.useCSSModule = true;
297
+ init.config.matchCSSModuleFunction = init.config.createCSSModuleRegex(configFile.importModuleAs);
281
298
  }
282
- // ---------output Minify
283
- if (configFile.hasOwnProperty('minify')) {
299
+ if (configFile.hasOwnProperty("minify")) {
284
300
  init.minify = configFile.minify;
285
301
  }
286
- // ------------Extractor function-------
287
- if (configFile.hasOwnProperty('extractorFunction')) {
302
+ if (configFile.hasOwnProperty("extractorFunction")) {
288
303
  init.config.useExtractorFunction = configFile.extractorFunction.trim() ? true : false;
289
304
  if (init.config.useExtractorFunction)
290
305
  init.config.matchExtractorFunction = init.config.createExtractorRegex(configFile.extractorFunction);
291
306
  }
292
307
  else {
293
308
  init.config.useExtractorFunction = true;
294
- init.config.matchExtractorFunction = init.config.createExtractorRegex('String');
309
+ init.config.matchExtractorFunction = init.config.createExtractorRegex("String");
295
310
  }
296
- // ---------Extend----------------
297
- if (configFile.hasOwnProperty('extend') && typeof configFile.extend === 'object') {
298
- const filteredObj = {};
299
- Object.keys(configFile.extend).map((key) => {
300
- // if (configFile.extend[key].hasOwnProperty('compiler') && (typeof configFile.extend[key].compiler === 'function')){
301
- filteredObj[key] = configFile.extend[key];
302
- // }
303
- });
304
- init.statementMaker.extend(filteredObj);
311
+ if (configFile.hasOwnProperty("extend") && typeof configFile.extend === "object") {
312
+ init.statementMaker.extend(configFile.extend);
305
313
  }
306
- // -----------------useColon----------------------------
307
- if (configFile.hasOwnProperty('useColon')) {
314
+ if (configFile.hasOwnProperty("useColon")) {
308
315
  init.config.useColon = configFile.useColon;
309
316
  }
310
- // ---------------addMedia----------------
311
- if (configFile.hasOwnProperty('media') && typeof configFile.media === 'object') {
317
+ if (configFile.hasOwnProperty("media") && typeof configFile.media === "object") {
312
318
  init.statementMaker.addMedia(configFile.media);
313
319
  }
314
- // /Truncate File every time we bundle
315
- if (configFile.hasOwnProperty('truncate') && configFile.truncate === false) {
316
- // do nothing
317
- }
318
- else {
319
- if (fs.existsSync(init.output))
320
- fs.truncateSync(path.resolve(init.output));
321
- writeStatementToFile(init.output, `@layer ${init.layers.join(', ')};`, 'Initializating @layer,');
322
- }
323
- // Custom CSS statement
324
- if (configFile.hasOwnProperty('statement')) {
320
+ if (configFile.hasOwnProperty("statement")) {
325
321
  init.rawCSS = configFile.statement;
326
322
  init.statementMaker.rawCSS = configFile.statement;
327
- writeStatementToFile(init.output, configFile.statement, 'config.statement');
328
323
  }
329
- // Custom Groups bundling acss classnames in single class name
330
- if (configFile.hasOwnProperty('group')) {
324
+ if (configFile.hasOwnProperty("group")) {
331
325
  init.customGroupStatement = init.statementMaker.groupObj(configFile.group);
332
326
  init.statementMaker.customGroupStatement = init.statementMaker.groupObj(configFile.group);
333
- if (init.customGroupStatement)
334
- writeStatementToFile(init.output, init.customGroupStatement, 'config.group');
335
327
  }
336
328
  }
337
- // ----------------WATCH-------------------------------
338
329
  export function watch(config) {
339
- main(config);
340
- const watcher = chokidar.watch(init.input, {
341
- ignored: '*.css', // ignore dot-files
342
- persistent: true
343
- });
344
- const compileFile = (file) => {
345
- console.log(`--processing file : ${file}`);
346
- createCSSFileByFile(file, true);
347
- globalCSSCompiler();
348
- postify(init.output, [postcssDiscardDuplicates], init.minify);
349
- console.log('Done! ');
350
- };
351
- // Something to use when events are received.
352
- const log = console.log.bind(console);
353
- // Add event listeners.
354
- watcher
355
- .on('add', path => log(`File ${path} has been added to watch`))
356
- .on('change', path => compileFile(path));
357
- // .on('unlink', path => log(`File ${path} has been removed`));
358
- // More possible events.
359
- watcher
360
- .on('addDir', path => log(`Directory ${path} has been added`))
361
- .on('unlinkDir', path => log(`Directory ${path} has been removed`))
362
- // .on('error', error => log(`Watcher error: ${error}`))
363
- // .on('ready', () => log('Initial scan complete. Ready for changes'))
364
- .on('raw', (event, path, details) => {
365
- // log('Raw event info:', event, path, details);
366
- if (event === 'created' && details.type === 'file') {
367
- if (init.globPattern) {
368
- const files = fg.sync(init.globPattern, { absolute: true });
369
- if (files.indexOf(path) !== -1) {
370
- watcher.add(path);
371
- // console.log(path,123123);
330
+ return __awaiter(this, void 0, void 0, function* () {
331
+ yield main(config);
332
+ const outputAbs = init.output ? path.resolve(init.output) : "";
333
+ const patterns = [].concat(init.input);
334
+ // Watch the folders the globs start from. Passing globs to chokidar stopped
335
+ // working in chokidar 4; folders work in every version.
336
+ const bases = [...new Set(fg.generateTasks(patterns).map((t) => t.base || "."))];
337
+ let matched = new Set(fg.sync(patterns, { dot: true, absolute: true }));
338
+ const refreshMatched = () => { matched = new Set(fg.sync(patterns, { dot: true, absolute: true })); };
339
+ const watcher = chokidar.watch(bases, {
340
+ ignoreInitial: true,
341
+ persistent: true,
342
+ ignored: (p) => /(^|[\/\\])(node_modules|\.git)([\/\\]|$)/.test(p) ||
343
+ path.resolve(p) === outputAbs ||
344
+ path.resolve(p) === outputAbs + ".tmp" ||
345
+ /\.css$/.test(p),
346
+ });
347
+ // Editors often write a file several times in a row: wait 50 ms, then
348
+ // rebuild once for everything that changed.
349
+ const pending = new Set();
350
+ let timer;
351
+ const schedule = (file) => {
352
+ pending.add(file);
353
+ clearTimeout(timer);
354
+ timer = setTimeout(() => __awaiter(this, void 0, void 0, function* () {
355
+ const changed = [...pending];
356
+ pending.clear();
357
+ for (const f of changed) {
358
+ fileCache.delete(f);
359
+ if (init["--file"] || init["--module"])
360
+ yield createCSSFileByFile(f, true);
372
361
  }
362
+ if (init.output)
363
+ yield globalCSSCompiler();
364
+ console.log("AliasCSS updated:", changed.map((f) => path.relative(".", f)).join(", "));
365
+ }), 50);
366
+ };
367
+ watcher
368
+ .on("change", (p) => {
369
+ const file = path.resolve(p);
370
+ if (matched.has(file))
371
+ schedule(file);
372
+ })
373
+ .on("add", (p) => {
374
+ refreshMatched();
375
+ const file = path.resolve(p);
376
+ if (matched.has(file))
377
+ schedule(file);
378
+ })
379
+ .on("unlink", (p) => {
380
+ const file = path.resolve(p);
381
+ if (matched.has(file)) {
382
+ refreshMatched();
383
+ schedule(file);
373
384
  }
374
- else {
375
- watcher.add(path);
376
- }
377
- }
385
+ })
386
+ .on("ready", () => console.log("AliasCSS is watching", bases.join(", ")))
387
+ .on("error", (error) => console.error("AliasCSS watcher error:", error));
388
+ return watcher;
378
389
  });
379
390
  }