-
-
Notifications
You must be signed in to change notification settings - Fork 221
/
cli-main.ts
609 lines (504 loc) · 19.4 KB
/
cli-main.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
import { findConfig } from '@pandacss/config'
import { colors, logger } from '@pandacss/logger'
import {
PandaContext,
analyzeTokens,
buildInfo,
codegen,
cssgen,
debug,
generate,
loadConfigAndCreateContext,
setLogStream,
setupConfig,
setupGitIgnore,
setupPostcss,
startProfiling,
writeAnalyzeJSON,
type CssGenOptions,
} from '@pandacss/node'
import { PandaError, compact } from '@pandacss/shared'
import type { CssArtifactType } from '@pandacss/types'
import { cac } from 'cac'
import { join, resolve } from 'path'
import { version } from '../package.json'
import { interactive } from './interactive'
import type {
AnalyzeCommandFlags,
CodegenCommandFlags,
CssGenCommandFlags,
DebugCommandFlags,
EmitPackageCommandFlags,
InitCommandFlags,
MainCommandFlags,
ShipCommandFlags,
StudioCommandFlags,
} from './types'
export async function main() {
const cli = cac('panda')
const cwd = process.cwd()
cli
.command('init', "Initialize the panda's config file")
.option('-i, --interactive', 'Run in interactive mode', { default: false })
.option('-f, --force', 'Force overwrite existing config file')
.option('-p, --postcss', 'Emit postcss config file')
.option('-c, --config <path>', 'Path to panda config file')
.option('--cwd <cwd>', 'Current working directory', { default: cwd })
.option('--silent', 'Suppress all messages except errors')
.option('--no-gitignore', "Don't update the .gitignore")
.option('--no-codegen', "Don't run the codegen logic")
.option('--out-extension <ext>', "The extension of the generated js files (default: 'mjs')")
.option('--outdir <dir>', 'The output directory for the generated files')
.option('--jsx-framework <framework>', 'The jsx framework to use')
.option('--syntax <syntax>', 'The css syntax preference')
.option('--strict-tokens', 'Using strictTokens: true')
.option('--logfile <file>', 'Outputs logs to a file')
.action(async (initFlags: Partial<InitCommandFlags> = {}) => {
let options = {}
if (initFlags.interactive) {
options = await interactive()
}
const flags = { ...initFlags, ...options }
const { force, postcss, silent, gitignore, outExtension, jsxFramework, config: configPath, syntax } = flags
const cwd = resolve(flags.cwd ?? '')
if (silent) {
logger.level = 'silent'
}
const stream = setLogStream({ cwd, logfile: flags.logfile })
logger.info('cli', `Panda v${version}\n`)
const done = logger.time.info('✨ Panda initialized')
if (postcss) {
await setupPostcss(cwd)
}
await setupConfig(
cwd,
compact({
force,
outExtension,
jsxFramework,
syntax,
outdir: flags.outdir,
}),
)
const ctx = await loadConfigAndCreateContext({
cwd,
configPath,
config: compact({ gitignore, outdir: flags.outdir }),
})
if (gitignore) {
setupGitIgnore(ctx)
}
if (flags.codegen) {
const { msg, box } = await codegen(ctx)
logger.log(msg + box)
} else {
logger.log(ctx.initMessage())
}
done()
stream.end()
})
cli
.command('codegen', 'Generate the panda system')
.option('--silent', "Don't print any logs")
.option('--clean', 'Clean the output directory before generating')
.option('-c, --config <path>', 'Path to panda config file')
.option('-w, --watch', 'Watch files and rebuild')
.option('-p, --poll', 'Use polling instead of filesystem events when watching')
.option('--cwd <cwd>', 'Current working directory', { default: cwd })
.option('--cpu-prof', 'Generates a `.cpuprofile` to help debug performance issues')
.option('--logfile <file>', 'Outputs logs to a file')
.action(async (flags: CodegenCommandFlags) => {
const { silent, clean, config: configPath, watch, poll } = flags
const cwd = resolve(flags.cwd ?? '')
const stream = setLogStream({ cwd, logfile: flags.logfile })
let stopProfiling: Function = () => void 0
if (flags.cpuProf) {
stopProfiling = await startProfiling(cwd, 'codegen', flags.watch)
}
if (silent) {
logger.level = 'silent'
}
let ctx = await loadConfigAndCreateContext({
cwd,
config: { clean },
configPath,
})
const { msg } = await codegen(ctx)
logger.log(msg)
if (watch) {
ctx.watchConfig(
async () => {
const affecteds = await ctx.diff.reloadConfigAndRefreshContext((conf) => {
ctx = new PandaContext(conf)
})
await ctx.hooks['config:change']?.({ config: ctx.config, changes: affecteds })
await codegen(ctx, Array.from(affecteds.artifacts))
logger.info('ctx:updated', 'config rebuilt ✅')
},
{ cwd, poll },
)
} else {
stream.end()
}
stopProfiling()
})
cli
.command(
'cssgen [globOrType]',
'Generate the css from files, or generate the css from the specified type which can be: preflight, tokens, static, global, keyframes',
)
.option('--silent', "Don't print any logs")
.option('-m, --minify', 'Minify generated code')
.option('--clean', 'Clean the output before generating')
.option('-c, --config <path>', 'Path to panda config file')
.option('-w, --watch', 'Watch files and rebuild')
.option('--minimal', 'Do not include CSS generation for theme tokens, preflight, keyframes, static and global css')
.option('--lightningcss', 'Use `lightningcss` instead of `postcss` for css optimization.')
.option('--polyfill', 'Polyfill CSS @layers at-rules for older browsers.')
.option('-p, --poll', 'Use polling instead of filesystem events when watching')
.option('-o, --outfile [file]', "Output file for extracted css, default to './styled-system/styles.css'")
.option('--cwd <cwd>', 'Current working directory', { default: cwd })
.option('--cpu-prof', 'Generates a `.cpuprofile` to help debug performance issues')
.option('--logfile <file>', 'Outputs logs to a file')
.action(async (maybeGlob?: string, flags: CssGenCommandFlags = {}) => {
const { silent, config: configPath, outfile, watch, poll, minimal, ...rest } = flags
const cwd = resolve(flags.cwd ?? '')
const stream = setLogStream({ cwd, logfile: flags.logfile })
let stopProfiling: Function = () => void 0
if (flags.cpuProf) {
stopProfiling = await startProfiling(cwd, 'cssgen', flags.watch)
}
const cssArtifact = ['preflight', 'tokens', 'static', 'global', 'keyframes'].find(
(type) => type === maybeGlob,
) as CssArtifactType | undefined
const glob = cssArtifact ? undefined : maybeGlob
if (silent) {
logger.level = 'silent'
}
const overrideConfig = {
...rest,
...(glob ? { include: [glob] } : undefined),
}
let ctx = await loadConfigAndCreateContext({
cwd,
config: overrideConfig,
configPath,
})
const options: CssGenOptions = {
cwd,
outfile,
type: cssArtifact,
minimal,
}
await cssgen(ctx, options)
if (watch) {
//
ctx.watchConfig(
async () => {
const affecteds = await ctx.diff.reloadConfigAndRefreshContext((conf) => {
ctx = new PandaContext(conf)
})
await ctx.hooks['config:change']?.({ config: ctx.config, changes: affecteds })
await cssgen(ctx, options)
logger.info('ctx:updated', 'config rebuilt ✅')
},
{ cwd, poll },
)
ctx.watchFiles(async (event, file) => {
if (event === 'unlink') {
ctx.project.removeSourceFile(ctx.runtime.path.abs(cwd, file))
} else if (event === 'change') {
ctx.project.reloadSourceFile(file)
await cssgen(ctx, options)
} else if (event === 'add') {
ctx.project.createSourceFile(file)
await cssgen(ctx, options)
}
})
} else {
stream.end()
stopProfiling()
}
})
cli
.command('[files]', 'Include file glob', { ignoreOptionDefaultValue: true })
.option('-o, --outdir <dir>', 'Output directory', { default: 'styled-system' })
.option('-m, --minify', 'Minify generated code')
.option('-w, --watch', 'Watch files and rebuild')
.option('-p, --poll', 'Use polling instead of filesystem events when watching')
.option('-c, --config <path>', 'Path to panda config file')
.option('--cwd <cwd>', 'Current working directory', { default: cwd })
.option('--preflight', 'Enable css reset')
.option('--silent', 'Suppress all messages except errors')
.option('-e, --exclude <files>', 'Exclude files', { default: [] })
.option('--clean', 'Clean output directory')
.option('--hash', 'Hash the generated classnames to make them shorter')
.option('--lightningcss', 'Use `lightningcss` instead of `postcss` for css optimization.')
.option('--polyfill', 'Polyfill CSS @layers at-rules for older browsers.')
.option('--emitTokensOnly', 'Whether to only emit the `tokens` directory')
.option('--cpu-prof', 'Generates a `.cpuprofile` to help debug performance issues')
.option('--logfile <file>', 'Outputs logs to a file')
.action(async (files: string[], flags: MainCommandFlags) => {
const { config: configPath, silent, ...rest } = flags
const cwd = resolve(flags.cwd ?? '')
const stream = setLogStream({ cwd, logfile: flags.logfile })
let stopProfiling: Function = () => void 0
if (flags.cpuProf) {
stopProfiling = await startProfiling(cwd, 'cli', flags.watch)
}
if (silent) {
logger.level = 'silent'
}
const config = compact({ include: files, ...rest, cwd })
await generate(config, configPath)
stopProfiling()
if (!flags.watch) {
stream.end()
}
})
cli
.command('studio', 'Realtime documentation for your design tokens')
.option('--build', 'Build')
.option('--preview', 'Preview')
.option('--port <port>', 'Port')
.option('--host', 'Host')
.option('-c, --config <path>', 'Path to panda config file')
.option('--cwd <cwd>', 'Current working directory', { default: cwd })
.option('--outdir <dir>', 'Output directory for static files')
.option('--base <path>', 'Base path of project')
.action(async (flags: StudioCommandFlags) => {
const { build, preview, port, host, outdir, config, base } = flags
const cwd = resolve(flags.cwd ?? '')
const ctx = await loadConfigAndCreateContext({
cwd,
configPath: config,
})
const buildOpts = {
configPath: findConfig({ cwd, file: config })!,
outDir: resolve(outdir || ctx.studio.outdir),
port,
host,
base,
}
let studio: any
try {
const studioPath = require.resolve('@pandacss/studio', { paths: [cwd] })
studio = require(studioPath)
} catch (error) {
logger.error('studio', error)
throw new PandaError('MISSING_STUDIO', "You need to install '@pandacss/studio' to use this command")
}
if (preview) {
await studio.previewStudio(buildOpts)
} else if (build) {
await studio.buildStudio(buildOpts)
} else {
await studio.serveStudio(buildOpts)
const note = `use ${colors.reset(colors.bold('--build'))} to build`
const port = `use ${colors.reset(colors.bold('--port'))} for a different port`
logger.log(colors.dim(` ${colors.green('➜')} ${colors.bold('Build')}: ${note}`))
logger.log(colors.dim(` ${colors.green('➜')} ${colors.bold('Port')}: ${port}`))
}
})
cli
.command('analyze [glob]', 'Analyze design token usage in glob')
.option('--outfile [filepath]', 'Output analyze report in JSON')
.option('--silent', "Don't print any logs")
.option('-c, --config <path>', 'Path to panda config file')
.option('--cwd <cwd>', 'Current working directory', { default: cwd })
.action(async (maybeGlob?: string, flags: AnalyzeCommandFlags = {}) => {
const { silent, config: configPath } = flags
const cwd = resolve(flags.cwd!)
if (silent) {
logger.level = 'silent'
}
const ctx = await loadConfigAndCreateContext({
cwd,
config: maybeGlob ? { include: [maybeGlob] } : undefined,
configPath,
})
const result = analyzeTokens(ctx, {
onResult(file) {
logger.info('cli', `Analyzed ${colors.bold(file)}`)
},
})
if (flags?.outfile && typeof flags.outfile === 'string') {
await writeAnalyzeJSON(flags.outfile, result, ctx)
logger.info('cli', `JSON report saved to ${resolve(flags.outfile)}`)
return
}
logger.info('cli', `Found ${result.propByIndex.size} token used in ${result.derived.byFilePathMaps.size} files`)
})
cli
.command('debug [glob]', 'Debug design token extraction & css generated from files in glob')
.option('--silent', "Don't print any logs")
.option('--dry', 'Output debug files in stdout without writing to disk')
.option('--outdir [dir]', "Output directory for debug files, default to './styled-system/debug'")
.option('--only-config', "Should only output the config file, default to 'false'")
.option('-c, --config <path>', 'Path to panda config file')
.option('--cwd <cwd>', 'Current working directory', { default: cwd })
.option('--cpu-prof', 'Generates a `.cpuprofile` to help debug performance issues')
.option('--logfile <file>', 'Outputs logs to a file')
.action(async (maybeGlob?: string, flags: DebugCommandFlags = {}) => {
const { silent, dry = false, outdir: outdirFlag, config: configPath } = flags ?? {}
const cwd = resolve(flags.cwd!)
const stream = setLogStream({ cwd, logfile: flags.logfile })
let stopProfiling: Function = () => void 0
if (flags.cpuProf) {
stopProfiling = await startProfiling(cwd, 'debug')
}
if (silent) {
logger.level = 'silent'
}
const ctx = await loadConfigAndCreateContext({
cwd,
config: maybeGlob ? { include: [maybeGlob] } : undefined,
configPath,
})
const outdir = outdirFlag ?? join(...ctx.paths.root, 'debug')
await debug(ctx, { outdir, dry, onlyConfig: flags.onlyConfig })
stopProfiling()
stream.end()
})
cli
.command('ship [glob]', 'Ship extract result from files in glob')
.option('--silent', "Don't print any logs")
.option(
'--o, --outfile [file]',
"Output path for the build info file, default to './styled-system/panda.buildinfo.json'",
)
.option('-m, --minify', 'Minify generated JSON file')
.option('-c, --config <path>', 'Path to panda config file')
.option('--cwd <cwd>', 'Current working directory', { default: cwd })
.option('-w, --watch', 'Watch files and rebuild')
.option('-p, --poll', 'Use polling instead of filesystem events when watching')
.action(async (maybeGlob?: string, flags: ShipCommandFlags = {}) => {
const { silent, outfile: outfileFlag, minify, config: configPath, watch, poll } = flags
const cwd = resolve(flags.cwd!)
if (silent) {
logger.level = 'silent'
}
let ctx = await loadConfigAndCreateContext({
cwd,
config: maybeGlob ? { include: [maybeGlob] } : undefined,
configPath,
})
const outfile = outfileFlag ?? join(...ctx.paths.root, 'panda.buildinfo.json')
if (minify) {
ctx.config.minify = true
}
await buildInfo(ctx, outfile)
if (watch) {
ctx.watchConfig(
async () => {
const affecteds = await ctx.diff.reloadConfigAndRefreshContext((conf) => {
ctx = new PandaContext(conf)
})
await ctx.hooks['config:change']?.({ config: ctx.config, changes: affecteds })
await buildInfo(ctx, outfile)
logger.info('ctx:updated', 'config rebuilt ✅')
},
{ cwd, poll },
)
ctx.watchFiles(async (event, file) => {
if (event === 'unlink') {
ctx.project.removeSourceFile(ctx.runtime.path.abs(cwd, file))
} else if (event === 'change') {
ctx.project.reloadSourceFile(file)
await buildInfo(ctx, outfile)
} else if (event === 'add') {
ctx.project.createSourceFile(file)
await buildInfo(ctx, outfile)
}
})
}
})
cli
.command('emit-pkg', 'Emit package.json with entrypoints')
.option('--outdir <dir>', 'Output directory', { default: '.' })
.option('--base <source>', 'The base directory of the package.json entrypoints')
.option('--silent', "Don't print any logs")
.option('--cwd <cwd>', 'Current working directory', { default: cwd })
.action(async (flags: EmitPackageCommandFlags) => {
const { outdir, silent, base } = flags
if (silent) {
logger.level = 'silent'
}
const cwd = resolve(flags.cwd!)
const ctx = await loadConfigAndCreateContext({
cwd,
config: { cwd },
})
const pkgPath = resolve(cwd, outdir, 'package.json')
const exists = ctx.runtime.fs.existsSync(pkgPath)
const exports = [] as any[]
const createDir = (...dir: string[]) => {
return ['.', base, ...dir].filter(Boolean).join('/')
}
const createEntry = (dir: string) => ({
types: ctx.file.extDts(createDir(dir, 'index')),
require: ctx.file.ext(createDir(dir, 'index')),
import: ctx.file.ext(createDir(dir, 'index')),
})
exports.push(
['./css', createEntry('css')],
['./tokens', createEntry('tokens')],
['./types', createEntry('types')],
)
if (!ctx.patterns.isEmpty()) {
exports.push(['./patterns', createEntry('patterns')])
}
if (!ctx.recipes.isEmpty()) {
exports.push(['./recipes', createEntry('recipes')])
}
if (!ctx.patterns.isEmpty()) {
exports.push(['./jsx', createEntry('jsx')])
}
if (ctx.config.themes) {
exports.push(['./themes', createEntry('themes')])
}
const stylesDir = createDir('styles.css')
if (!exists) {
//
const content = {
name: outdir,
description: 'This package is auto-generated by Panda CSS',
version: '0.1.0',
type: 'module',
keywords: ['pandacss', 'styled-system', 'codegen'],
license: 'ISC',
exports: {
...Object.fromEntries(exports),
'./styles.css': stylesDir,
},
scripts: {
prepare: 'panda codegen --clean',
},
}
await ctx.runtime.fs.writeFile(pkgPath, JSON.stringify(content, null, 2))
//
} else {
//
const content = JSON.parse(ctx.runtime.fs.readFileSync(pkgPath))
content.exports = {
...content.exports,
...Object.fromEntries(exports),
'./styles.css': stylesDir,
}
await ctx.runtime.fs.writeFile(pkgPath, JSON.stringify(content, null, 2))
}
logger.info('cli', `Emit package.json to ${pkgPath}`)
})
cli.help()
cli.version(version)
cli.parse(process.argv, { run: false })
try {
await cli.runMatchedCommand()
} catch (error) {
logger.error('cli', error)
if (logger.isDebug) {
console.error(error)
}
process.exit(1)
}
}