@master/css-cli 2.0.0-rc.15 → 2.0.0-rc.17

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.
@@ -0,0 +1,293 @@
1
+ #!/usr/bin/env node
2
+ import { resolve } from 'node:path';
3
+ import { Command } from 'commander';
4
+ import { readJSONFileSync } from '@techor/fs';
5
+ import { dirname } from 'path';
6
+ import { fileURLToPath } from 'url';
7
+ import CSSExtractor from '@master/css-extractor';
8
+ import log from '@techor/log';
9
+ import prettyHartime from 'pretty-hrtime';
10
+ import { explorePathsSync } from '@techor/glob';
11
+ import exploreConfig from 'explore-config';
12
+ import { readFile, writeFileSync } from 'fs';
13
+ import { brotliCompressSync } from 'zlib';
14
+ import { render } from '@master/css-server';
15
+
16
+ var commandExtract = ((program)=>program.command('extract').argument('[source paths]', 'The glob pattern path to extract sources').option('-w, --watch', 'Watch file changed and generate CSS rules.').option('-o, --output <path>', 'Specify your CSS file output path').option('-v, --verbose <level>', 'Verbose logging 0~N', '1').option('--no-export', 'Print only CSS results.').option('--options <path>', 'Specify your extractor options sources', 'master.css-extractor').action(async function(specifiedSourcePaths, options) {
17
+ const { watch, output, verbose, cwd, options: customOptions } = options || {};
18
+ const extractor = new CSSExtractor(customOptions, cwd);
19
+ extractor.on('init', (options)=>{
20
+ if (specifiedSourcePaths?.length) {
21
+ options.include = [];
22
+ options.exclude = [];
23
+ } else {
24
+ if (!options.exclude?.includes('**/node_modules/**')) {
25
+ options.exclude?.push('**/node_modules/**');
26
+ }
27
+ if (!options.exclude?.includes('node_modules')) {
28
+ options.exclude?.push('node_modules');
29
+ }
30
+ }
31
+ options.output = output;
32
+ options.verbose = verbose ? +verbose : options.verbose;
33
+ });
34
+ extractor.init();
35
+ const insert = async ()=>{
36
+ /**
37
+ * true: Ignore `.include` and `.exclude` when specifying sources explicitly.
38
+ * else: Insert according to the source of `.include` - `.exclude`.
39
+ */ if (specifiedSourcePaths?.length) {
40
+ await extractor.insertFiles(specifiedSourcePaths);
41
+ } else {
42
+ await extractor.insertFiles(extractor.allowedSourcePaths);
43
+ }
44
+ };
45
+ if (watch) {
46
+ const reset = async ()=>{
47
+ await insert();
48
+ /* If the specified source does not exist, watch the .include - .exclude */ if (!specifiedSourcePaths?.length && extractor.options.include) {
49
+ await extractor.watchSource(extractor.options.include, {
50
+ ignored: extractor.options.exclude
51
+ });
52
+ }
53
+ };
54
+ extractor.on('watchStart', async ()=>{
55
+ await extractor.prepare();
56
+ await reset();
57
+ log``;
58
+ log.t`Start watching source changes`;
59
+ }).on('reset', async ()=>{
60
+ await reset();
61
+ log``;
62
+ log.t`Restart watching source changes`;
63
+ }).on('change', ()=>{
64
+ if (options?.export) {
65
+ extractor.export();
66
+ } else {
67
+ console.log(extractor.css.text);
68
+ }
69
+ }).on('watchClose', ()=>{
70
+ log``;
71
+ log.t`Stop watching source changes`;
72
+ });
73
+ await extractor.startWatch();
74
+ } else {
75
+ await extractor.prepare();
76
+ await insert();
77
+ if (options?.export) {
78
+ extractor.export();
79
+ } else {
80
+ console.log(extractor.css.text);
81
+ }
82
+ }
83
+ }));
84
+
85
+ function getDefaultExportFromCjs (x) {
86
+ return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
87
+ }
88
+
89
+ var bytes$2 = {exports: {}};
90
+
91
+ /*!
92
+ * bytes
93
+ * Copyright(c) 2012-2014 TJ Holowaychuk
94
+ * Copyright(c) 2015 Jed Watson
95
+ * MIT Licensed
96
+ */
97
+ /**
98
+ * Module exports.
99
+ * @public
100
+ */ bytes$2.exports = bytes;
101
+ bytes$2.exports.format = format;
102
+ bytes$2.exports.parse = parse;
103
+ /**
104
+ * Module variables.
105
+ * @private
106
+ */ var formatThousandsRegExp = /\B(?=(\d{3})+(?!\d))/g;
107
+ var formatDecimalsRegExp = /(?:\.0*|(\.[^0]+)0+)$/;
108
+ var map = {
109
+ b: 1,
110
+ kb: 1 << 10,
111
+ mb: 1 << 20,
112
+ gb: 1 << 30,
113
+ tb: Math.pow(1024, 4),
114
+ pb: Math.pow(1024, 5)
115
+ };
116
+ var parseRegExp = /^((-|\+)?(\d+(?:\.\d+)?)) *(kb|mb|gb|tb|pb)$/i;
117
+ /**
118
+ * Convert the given value in bytes into a string or parse to string to an integer in bytes.
119
+ *
120
+ * @param {string|number} value
121
+ * @param {{
122
+ * case: [string],
123
+ * decimalPlaces: [number]
124
+ * fixedDecimals: [boolean]
125
+ * thousandsSeparator: [string]
126
+ * unitSeparator: [string]
127
+ * }} [options] bytes options.
128
+ *
129
+ * @returns {string|number|null}
130
+ */ function bytes(value, options) {
131
+ if (typeof value === 'string') {
132
+ return parse(value);
133
+ }
134
+ if (typeof value === 'number') {
135
+ return format(value, options);
136
+ }
137
+ return null;
138
+ }
139
+ /**
140
+ * Format the given value in bytes into a string.
141
+ *
142
+ * If the value is negative, it is kept as such. If it is a float,
143
+ * it is rounded.
144
+ *
145
+ * @param {number} value
146
+ * @param {object} [options]
147
+ * @param {number} [options.decimalPlaces=2]
148
+ * @param {number} [options.fixedDecimals=false]
149
+ * @param {string} [options.thousandsSeparator=]
150
+ * @param {string} [options.unit=]
151
+ * @param {string} [options.unitSeparator=]
152
+ *
153
+ * @returns {string|null}
154
+ * @public
155
+ */ function format(value, options) {
156
+ if (!Number.isFinite(value)) {
157
+ return null;
158
+ }
159
+ var mag = Math.abs(value);
160
+ var thousandsSeparator = options && options.thousandsSeparator || '';
161
+ var unitSeparator = options && options.unitSeparator || '';
162
+ var decimalPlaces = options && options.decimalPlaces !== undefined ? options.decimalPlaces : 2;
163
+ var fixedDecimals = Boolean(options && options.fixedDecimals);
164
+ var unit = options && options.unit || '';
165
+ if (!unit || !map[unit.toLowerCase()]) {
166
+ if (mag >= map.pb) {
167
+ unit = 'PB';
168
+ } else if (mag >= map.tb) {
169
+ unit = 'TB';
170
+ } else if (mag >= map.gb) {
171
+ unit = 'GB';
172
+ } else if (mag >= map.mb) {
173
+ unit = 'MB';
174
+ } else if (mag >= map.kb) {
175
+ unit = 'KB';
176
+ } else {
177
+ unit = 'B';
178
+ }
179
+ }
180
+ var val = value / map[unit.toLowerCase()];
181
+ var str = val.toFixed(decimalPlaces);
182
+ if (!fixedDecimals) {
183
+ str = str.replace(formatDecimalsRegExp, '$1');
184
+ }
185
+ if (thousandsSeparator) {
186
+ str = str.split('.').map(function(s, i) {
187
+ return i === 0 ? s.replace(formatThousandsRegExp, thousandsSeparator) : s;
188
+ }).join('.');
189
+ }
190
+ return str + unitSeparator + unit;
191
+ }
192
+ /**
193
+ * Parse the string value into an integer in bytes.
194
+ *
195
+ * If no unit is given, it is assumed the value is in bytes.
196
+ *
197
+ * @param {number|string} val
198
+ *
199
+ * @returns {number|null}
200
+ * @public
201
+ */ function parse(val) {
202
+ if (typeof val === 'number' && !isNaN(val)) {
203
+ return val;
204
+ }
205
+ if (typeof val !== 'string') {
206
+ return null;
207
+ }
208
+ // Test if the string passed is valid
209
+ var results = parseRegExp.exec(val);
210
+ var floatValue;
211
+ var unit = 'b';
212
+ if (!results) {
213
+ // Nothing could be extracted from the given string
214
+ floatValue = parseInt(val, 10);
215
+ unit = 'b';
216
+ } else {
217
+ // Retrieve the value and the unit
218
+ floatValue = parseFloat(results[1]);
219
+ unit = results[4].toLowerCase();
220
+ }
221
+ if (isNaN(floatValue)) {
222
+ return null;
223
+ }
224
+ return Math.floor(map[unit] * floatValue);
225
+ }
226
+
227
+ var bytesExports = bytes$2.exports;
228
+ var bytes$1 = /*@__PURE__*/getDefaultExportFromCjs(bytesExports);
229
+
230
+ var commandRender = ((program)=>program.command('render').description('Scans HTML and injects generated CSS rules').argument('<source paths>', 'The path in glob patterns of the source of the HTML file').option('-c --config <path>', 'The source path of the Master CSS configuration', 'master.css').option('-a --analyze', 'Analyze injected CSS and HTML size ( brotli ) without writing to file').action(async function(filePatterns, options = {
231
+ config: 'master.css'
232
+ }) {
233
+ const sourcePaths = explorePathsSync(filePatterns);
234
+ if (sourcePaths.length) {
235
+ const renderStart = process.hrtime();
236
+ const col1Width = Math.max(sourcePaths.reduce((max, current)=>{
237
+ if (current.length > max.length) {
238
+ return current;
239
+ } else {
240
+ return max;
241
+ }
242
+ }).length + 10, 20);
243
+ const col2Width = 8;
244
+ const config = typeof options.config === 'string' ? exploreConfig(options.config, {
245
+ found: (basename)=>log.i`Loaded **${basename}**`
246
+ }) : undefined;
247
+ log``;
248
+ log`${' Source Files'.padEnd(col1Width)}${'CSS Size'.padStart(col2Width)}`;
249
+ await Promise.all(sourcePaths.map(async (filename)=>new Promise((resolve, reject)=>{
250
+ readFile(filename, {
251
+ encoding: 'utf-8'
252
+ }, (err, content)=>{
253
+ if (err) reject(err);
254
+ const { html, css } = render(content, config);
255
+ const renderedCSSText = css?.text;
256
+ const renderedCSSSize = renderedCSSText ? options.analyze ? brotliCompressSync(renderedCSSText).length : renderedCSSText.length : 0;
257
+ if (!options.analyze) {
258
+ if (content !== html) {
259
+ writeFileSync(filename, html);
260
+ }
261
+ }
262
+ const prettifiedCSSSize = bytes$1(renderedCSSSize, {
263
+ space: false
264
+ });
265
+ log.ok`**${filename}**${' '.repeat(col1Width - filename.length - 2)}${prettifiedCSSSize.padStart(col2Width)}`;
266
+ resolve();
267
+ });
268
+ })));
269
+ const renderTime = process.hrtime(renderStart);
270
+ if (options.analyze) {
271
+ log`${' '.repeat(col1Width)}${'(Brotli)'.padStart(col2Width)}`;
272
+ log``;
273
+ log.success`**${sourcePaths.length}** files analyzed in ${prettyHartime(renderTime).replace(' ', '')}`;
274
+ log``;
275
+ log.i`The CSS output will be smaller because it doesn't yet consider the bytes shared with HTML.`;
276
+ } else {
277
+ log`${' '.repeat(col1Width)}${'(Raw)'.padStart(col2Width)}`;
278
+ log``;
279
+ log.success`**${sourcePaths.length}** files rendered in ${prettyHartime(renderTime).replace(' ', '')}`;
280
+ }
281
+ } else {
282
+ log.i`No **${filePatterns}** files found`;
283
+ }
284
+ }));
285
+
286
+ const __filename = fileURLToPath(import.meta.url);
287
+ const __dirname = dirname(__filename);
288
+ const pkg = readJSONFileSync(resolve(__dirname, '../../package.json'));
289
+ const program = new Command();
290
+ program.name(pkg.name).description(pkg.description).version(pkg.version || '0.0.0');
291
+ commandExtract(program);
292
+ commandRender(program);
293
+ program.parse();
package/package.json CHANGED
@@ -1 +1 @@
1
- {"name":"@master/css-cli","scripts":{"build":"techor pack --platform node","dev":"pnpm run build --watch","lint":"eslint ./src","type-check":"tsc --noEmit","test":"jest"},"license":"MIT","description":"Master CSS CLI","author":"Aoyue Design LLC.","funding":"https://css.master.co/docs/donate","homepage":"https://css.master.co","bugs":{"url":"https://github.com/master-co/css/issues"},"repository":{"type":"git","url":"https://github.com/master-co/css.git","directory":"packages/cli"},"keywords":["cli","css","mastercss"],"bin":{"mcss":"./dist/bin/index.bundle.js","mastercss":"./dist/bin/index.bundle.js"},"files":["dist"],"publishConfig":{"access":"public"},"dependencies":{"@master/css":"^2.0.0-rc.15","@master/css-extractor":"^2.0.0-rc.15","@master/css-server":"^2.0.0-rc.15","@techor/extend":"^2.6.5","@techor/fs":"^2.6.5","@techor/glob":"^2.6.5","@techor/log":"^2.6.5","chokidar":"^3.5.3","commander":"^12.0.0","explore-config":"^2.6.5","minimatch":"^9.0.1","pretty-hrtime":"^1.0.3"},"devDependencies":{"@types/pretty-hrtime":"^1.0.3","fast-glob":"^3.3.2"},"version":"2.0.0-rc.15"}
1
+ {"name":"@master/css-cli","scripts":{"build":"techor build","dev":"pnpm build --watch","lint":"eslint ./src","type-check":"tsc --noEmit","test":"jest"},"type":"module","license":"MIT","description":"Master CSS CLI","author":"Aoyue Design LLC.","funding":"https://css.master.co/docs/donate","homepage":"https://css.master.co","bugs":{"url":"https://github.com/master-co/css/issues"},"repository":{"type":"git","url":"https://github.com/master-co/css.git","directory":"packages/cli"},"keywords":["cli","css","mastercss"],"bin":{"mcss":"./dist/bin/index.mjs","mastercss":"./dist/bin/index.mjs"},"files":["dist"],"publishConfig":{"access":"public"},"dependencies":{"@master/css":"^2.0.0-rc.17","@master/css-extractor":"^2.0.0-rc.17","@master/css-server":"^2.0.0-rc.17","@techor/extend":"^3.0.11","@techor/fs":"^3.0.11","@techor/glob":"^3.0.11","@techor/log":"^3.0.11","chokidar":"^3.5.3","commander":"^12.0.0","explore-config":"^3.0.11","minimatch":"^9.0.1","pretty-hrtime":"^1.0.3"},"devDependencies":{"@types/pretty-hrtime":"^1.0.3","fast-glob":"^3.3.2"},"version":"2.0.0-rc.17"}
@@ -1,12 +0,0 @@
1
- #!/usr/bin/env node
2
- "use strict";var I=Object.create;var M=Object.defineProperty;var J=Object.getOwnPropertyDescriptor;var K=Object.getOwnPropertyNames;var Q=Object.getPrototypeOf,U=Object.prototype.hasOwnProperty;var w=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var X=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let l of K(e))!U.call(t,l)&&l!==r&&M(t,l,{get:()=>e[l],enumerable:!(n=J(e,l))||n.enumerable});return t};var f=(t,e,r)=>(r=t!=null?I(Q(t)):{},X(e||!t||!t.__esModule?M(r,"default",{value:t,enumerable:!0}):r,t));var F=w((oe,B)=>{"use strict";var z=f(require("@master/css-extractor")),d=f(require("@techor/log"));B.exports=t=>t.command("extract").argument("[source paths]","The glob pattern path to extract sources").option("-w, --watch","Watch file changed and generate CSS rules.").option("-o, --output <path>","Specify your CSS file output path").option("-v, --verbose <level>","Verbose logging 0~N","1").option("--no-export","Print only CSS results.").option("--options <path>","Specify your extractor options sources","master.css-extractor.*").action(async function(e,r){let{watch:n,output:l,verbose:p,cwd:m,options:s}=r||{},a=new z.default(s,m);a.on("init",o=>{e?.length?(o.include=[],o.exclude=[]):(o.exclude?.includes("**/node_modules/**")||o.exclude?.push("**/node_modules/**"),o.exclude?.includes("node_modules")||o.exclude?.push("node_modules")),o.output=l,o.verbose=p?+p:o.verbose}),a.init();let i=async()=>{e?.length?await a.insertFiles(e):await a.insertFiles(a.allowedSourcePaths)};if(n){let o=async()=>{await i(),!e?.length&&a.options.include&&await a.watchSource(a.options.include,{ignored:a.options.exclude})};a.on("watchStart",async()=>{await a.prepare(),await o(),d.default``,d.default.t`Start watching source changes`}).on("reset",async()=>{await o(),d.default``,d.default.t`Restart watching source changes`}).on("change",()=>{r?.export?a.export():console.log(a.css.text)}).on("watchClose",()=>{d.default``,d.default.t`Stop watching source changes`}),await a.startWatch()}else await a.prepare(),await i(),r?.export?a.export():console.log(a.css.text)})});var L=w((ne,h)=>{"use strict";h.exports=te;h.exports.format=P;h.exports.parse=N;var Y=/\B(?=(\d{3})+(?!\d))/g,Z=/(?:\.0*|(\.[^0]+)0+)$/,u={b:1,kb:1024,mb:1<<20,gb:1<<30,tb:Math.pow(1024,4),pb:Math.pow(1024,5)},ee=/^((-|\+)?(\d+(?:\.\d+)?)) *(kb|mb|gb|tb|pb)$/i;function te(t,e){return typeof t=="string"?N(t):typeof t=="number"?P(t,e):null}function P(t,e){if(!Number.isFinite(t))return null;var r=Math.abs(t),n=e&&e.thousandsSeparator||"",l=e&&e.unitSeparator||"",p=e&&e.decimalPlaces!==void 0?e.decimalPlaces:2,m=!!(e&&e.fixedDecimals),s=e&&e.unit||"";(!s||!u[s.toLowerCase()])&&(r>=u.pb?s="PB":r>=u.tb?s="TB":r>=u.gb?s="GB":r>=u.mb?s="MB":r>=u.kb?s="KB":s="B");var a=t/u[s.toLowerCase()],i=a.toFixed(p);return m||(i=i.replace(Z,"$1")),n&&(i=i.split(".").map(function(o,b){return b===0?o.replace(Y,n):o}).join(".")),i+l+s}function N(t){if(typeof t=="number"&&!isNaN(t))return t;if(typeof t!="string")return null;var e=ee.exec(t),r,n="b";return e?(r=parseFloat(e[1]),n=e[4].toLowerCase()):(r=parseInt(t,10),n="b"),isNaN(r)?null:Math.floor(u[n]*r)}});var j=w((ie,R)=>{"use strict";var c=f(require("@techor/log")),x=f(require("pretty-hrtime")),k=require("@techor/glob"),_=f(require("explore-config")),g=require("fs"),E=require("zlib"),H=f(L()),O=require("@master/css-server");R.exports=t=>t.command("render").description("Scans HTML and injects generated CSS rules").argument("<source paths>","The path in glob patterns of the source of the HTML file").option("-c --config <path>","The source path of the Master CSS configuration","master.css.*").option("-a --analyze","Analyze injected CSS and HTML size ( brotli ) without writing to file").action(async function(e,r={config:"master.css.*"}){let n=(0,k.explorePathsSync)(e);if(n.length){let l=process.hrtime(),p=Math.max(n.reduce((i,o)=>o.length>i.length?o:i).length+10,20),m=8,s=typeof r.config=="string"?(0,_.default)(r.config):void 0;c.default``,c.default`${" Source Files".padEnd(p)}${"CSS Size".padStart(m)}`,await Promise.all(n.map(async i=>new Promise((o,b)=>{(0,g.readFile)(i,{encoding:"utf-8"},(v,$)=>{v&&b(v);let{html:T,css:V}=(0,O.render)($,s),y=V?.text,A=y?r.analyze?(0,E.brotliCompressSync)(y).length:y.length:0;r.analyze||$!==T&&(0,g.writeFileSync)(i,T);let G=(0,H.default)(A,{space:!1});c.default.ok`**${i}**${" ".repeat(p-i.length-2)}${G.padStart(m)}`,o()})})));let a=process.hrtime(l);r.analyze?(c.default`${" ".repeat(p)}${"(Brotli)".padStart(m)}`,c.default``,c.default.success`**${n.length}** files analyzed in ${(0,x.default)(a).replace(" ","")}`,c.default``,c.default.i`The CSS output will be smaller because it doesn't yet consider the bytes shared with HTML.`):(c.default`${" ".repeat(p)}${"(Raw)".padStart(m)}`,c.default``,c.default.success`**${n.length}** files rendered in ${(0,x.default)(a).replace(" ","")}`)}else c.default.i`No **${e}** files found`})});var W=require("node:path"),D=require("commander"),q=require("@techor/fs"),C=(0,q.readJSONFileSync)((0,W.resolve)(__dirname,"../../package.json")),S=new D.Command;S.name(C.name).description(C.description).version(C.version||"0.0.0");F()(S);j()(S);S.parse();
3
- /*! Bundled license information:
4
-
5
- bytes/index.js:
6
- (*!
7
- * bytes
8
- * Copyright(c) 2012-2014 TJ Holowaychuk
9
- * Copyright(c) 2015 Jed Watson
10
- * MIT Licensed
11
- *)
12
- */