@pandacss/compiler 2.0.0-beta.8 → 2.0.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.
@@ -0,0 +1,1588 @@
1
+ // src/index.ts
2
+ import {
3
+ assertProjectHooks,
4
+ assertProjectCallbacks,
5
+ BuildInfo as BuildInfo2,
6
+ DesignSystem as DesignSystem2,
7
+ inspectFile,
8
+ inspectFiles,
9
+ mergeCallbacks,
10
+ mergeHooks,
11
+ prepareCompilerConfig
12
+ } from "@pandacss/compiler-shared";
13
+
14
+ // src/callbacks.ts
15
+ import {
16
+ createTransformHelpers,
17
+ getPatternDefaultValueRefsByTransformId,
18
+ mergePatternDefaultValues,
19
+ PATTERN_HELPERS
20
+ } from "@pandacss/compiler-shared";
21
+ function registerCallbacks(project, callbacks, hooks, tokenDictionary) {
22
+ const utilityTransforms = callbacks["utility.transform"];
23
+ const hasUtilityTransforms = !!utilityTransforms && Object.keys(utilityTransforms).length > 0;
24
+ const patternTransforms = callbacks["pattern.transform"];
25
+ const hasPatternTransforms = !!patternTransforms && Object.keys(patternTransforms).length > 0;
26
+ const config = project.config();
27
+ const patternDefaultValues = callbacks["pattern.defaultValues"];
28
+ const patternDefaultValueRefs = config && patternDefaultValues ? getPatternDefaultValueRefsByTransformId(config) : /* @__PURE__ */ new Map();
29
+ const { token, utils } = createTransformHelpers(tokenDictionary);
30
+ if (hasPatternTransforms && !project.registerPatternTransform) {
31
+ throw new Error("Native project does not support pattern.transform callbacks");
32
+ }
33
+ if (project.registerPatternTransform && patternTransforms) {
34
+ for (const [id, callback] of Object.entries(patternTransforms)) {
35
+ const defaultValueId = patternDefaultValueRefs.get(id);
36
+ const defaultValue = defaultValueId ? patternDefaultValues?.[defaultValueId] : void 0;
37
+ project.registerPatternTransform(id, (props) => {
38
+ const input = props;
39
+ const nextProps = defaultValue ? mergePatternDefaultValues(defaultValue(input), input) : input;
40
+ return callback(nextProps, PATTERN_HELPERS);
41
+ });
42
+ }
43
+ }
44
+ if (hasUtilityTransforms && !project.registerUtilityTransform) {
45
+ throw new Error("Native project does not support utility.transform callbacks");
46
+ }
47
+ if (project.registerUtilityTransform && utilityTransforms) {
48
+ for (const [id, callback] of Object.entries(utilityTransforms)) {
49
+ project.registerUtilityTransform(id, (resolved, original) => {
50
+ return callback(resolved, { raw: original, token, utils });
51
+ });
52
+ }
53
+ }
54
+ const sourceTransforms = hooks?.["parser:before"];
55
+ if (sourceTransforms?.length && !project.registerSourceTransform) {
56
+ throw new Error("Native project does not support parser:before callbacks");
57
+ }
58
+ if (project.registerSourceTransform && sourceTransforms) {
59
+ for (const hook of sourceTransforms) {
60
+ const callback = callbacks["parser:before"]?.[hook.id];
61
+ if (!callback) continue;
62
+ project.registerSourceTransform(hook.id, hook.filter, (filePath, content) => {
63
+ const result = callback({ filePath: String(filePath), content: String(content), original: String(content) });
64
+ if (isPromiseLike(result)) {
65
+ throw new Error(`parser:before callback \`${hook.id}\` must be synchronous`);
66
+ }
67
+ return typeof result === "string" ? result : void 0;
68
+ });
69
+ }
70
+ }
71
+ }
72
+ function isPromiseLike(value) {
73
+ return !!value && (typeof value === "object" || typeof value === "function") && typeof value.then === "function";
74
+ }
75
+
76
+ // src/fallback.ts
77
+ import { BuildInfo, DesignSystem } from "@pandacss/compiler-shared";
78
+ var fallbackBuildInfo = new BuildInfo({
79
+ serializeBuildInfo: () => ({
80
+ schemaVersion: -1,
81
+ panda: "",
82
+ configFingerprint: "",
83
+ strings: [],
84
+ atoms: [],
85
+ modules: {}
86
+ }),
87
+ applyBuildInfo: () => false,
88
+ buildInfoSchemaVersion: () => -1,
89
+ configFingerprint: () => ""
90
+ });
91
+ var fallbackDesignSystem = new DesignSystem(
92
+ {
93
+ createManifest: (input) => ({ ...input, schemaVersion: -1 }),
94
+ manifestSchemaVersion: () => -1
95
+ },
96
+ fallbackBuildInfo
97
+ );
98
+ var FallbackExtractor = class {
99
+ extract() {
100
+ return { calls: [], jsx: [], diagnostics: [] };
101
+ }
102
+ extractDebug() {
103
+ return { imports: [], matched: [], calls: [], jsx: [], diagnostics: [] };
104
+ }
105
+ matchImports() {
106
+ return [];
107
+ }
108
+ };
109
+ var FallbackCompiler = class _FallbackCompiler {
110
+ fs = {
111
+ readFile: (_path) => void 0,
112
+ exists: (_path) => false
113
+ };
114
+ path = {
115
+ realpath: (path) => path,
116
+ resolve: (path, cwd) => this.resolvePath(path, cwd),
117
+ join: (parts) => this.joinPath(parts),
118
+ dirname: (path) => this.dirname(path)
119
+ };
120
+ static fromConfig() {
121
+ return new _FallbackCompiler();
122
+ }
123
+ serializeBuildInfo() {
124
+ return fallbackBuildInfo.create({ panda: "" });
125
+ }
126
+ applyBuildInfo() {
127
+ return false;
128
+ }
129
+ buildInfoSchemaVersion() {
130
+ return -1;
131
+ }
132
+ configFingerprint() {
133
+ return "";
134
+ }
135
+ createDesignSystemManifest(input) {
136
+ return { ...input, schemaVersion: -1 };
137
+ }
138
+ designSystemManifestSchemaVersion() {
139
+ return -1;
140
+ }
141
+ config() {
142
+ return {};
143
+ }
144
+ extractFileSource() {
145
+ return { calls: [], jsx: [], diagnostics: [] };
146
+ }
147
+ parseFile(path) {
148
+ return { path, cssCalls: 0, cvaCalls: 0, svaCalls: 0, jsxUsages: 0, diagnostics: [] };
149
+ }
150
+ parseFileSource(path) {
151
+ return { path, cssCalls: 0, cvaCalls: 0, svaCalls: 0, jsxUsages: 0, diagnostics: [] };
152
+ }
153
+ refreshFile() {
154
+ return false;
155
+ }
156
+ refreshFileSource() {
157
+ return false;
158
+ }
159
+ removeFile() {
160
+ return false;
161
+ }
162
+ affectedFiles() {
163
+ return [];
164
+ }
165
+ clear() {
166
+ }
167
+ scan() {
168
+ return [];
169
+ }
170
+ designSystemImportSelections() {
171
+ return [];
172
+ }
173
+ realpath(path) {
174
+ return path;
175
+ }
176
+ readFile(_path) {
177
+ return void 0;
178
+ }
179
+ exists(_path) {
180
+ return false;
181
+ }
182
+ resolvePath(path, cwd) {
183
+ if (!cwd || path.startsWith("/")) return path;
184
+ return `${cwd.replace(/\/$/, "")}/${path}`;
185
+ }
186
+ joinPath(parts) {
187
+ return parts.filter(Boolean).join("/");
188
+ }
189
+ dirname(path) {
190
+ const index = path.lastIndexOf("/");
191
+ return index <= 0 ? "" : path.slice(0, index);
192
+ }
193
+ isSourceFile() {
194
+ return false;
195
+ }
196
+ parseFiles(_paths) {
197
+ return [];
198
+ }
199
+ layers() {
200
+ return { reset: "reset", base: "base", tokens: "tokens", recipes: "recipes", utilities: "utilities" };
201
+ }
202
+ hasLayerDeclaration() {
203
+ return false;
204
+ }
205
+ stripLayerOrderStatements(css) {
206
+ return css;
207
+ }
208
+ spec() {
209
+ return {
210
+ conditions: { keys: [], breakpoints: [], containers: [] },
211
+ tokens: { categories: {}, colorPalettes: [], values: {}, deprecated: {} },
212
+ utilities: { properties: {}, shorthands: {}, deprecated: {} },
213
+ keyframes: { keys: [] },
214
+ patterns: {},
215
+ recipes: {},
216
+ slotRecipes: {},
217
+ propertyOrder: []
218
+ };
219
+ }
220
+ sources() {
221
+ return [];
222
+ }
223
+ inspectFileSource(_path, _source) {
224
+ return { usages: [], diagnostics: [], calls: [], jsx: [], tokenRefs: [], componentEntries: [], styleEntries: [] };
225
+ }
226
+ transformSource(input) {
227
+ return {
228
+ code: input.source,
229
+ map: null,
230
+ changed: false,
231
+ bailed: false,
232
+ diagnostics: [],
233
+ dependencies: [],
234
+ helper: { needsCx: false, needsAttachRecipe: false, needsMemoRecipe: false }
235
+ };
236
+ }
237
+ inspectFile(input) {
238
+ return { ...this.inspectFileSource(input.path, input.source), path: input.path };
239
+ }
240
+ inspectFiles(files) {
241
+ return { sourceCount: files.length, files: files.map((file) => this.inspectFile(file)) };
242
+ }
243
+ resolveUtilityValue() {
244
+ return null;
245
+ }
246
+ suggestTokens() {
247
+ return [];
248
+ }
249
+ suggestSemanticTokens() {
250
+ return [];
251
+ }
252
+ writeArtifacts(_options) {
253
+ return [];
254
+ }
255
+ writeCss(options) {
256
+ return emptyWriteCssResult(options.outfile);
257
+ }
258
+ writeLayerCss(options) {
259
+ return emptyWriteCssResult(options.outfile);
260
+ }
261
+ writeSplitCss(options) {
262
+ return emptyWriteSplitCssResult(options.outdir ?? "");
263
+ }
264
+ isEmpty() {
265
+ return true;
266
+ }
267
+ atoms() {
268
+ return [];
269
+ }
270
+ recipes() {
271
+ return [];
272
+ }
273
+ slotRecipes() {
274
+ return [];
275
+ }
276
+ encodedRecipes() {
277
+ return { base: [], variants: [], atomic: [] };
278
+ }
279
+ staticPatternAtoms() {
280
+ return { atoms: [], diagnostics: [] };
281
+ }
282
+ getFile() {
283
+ return null;
284
+ }
285
+ fileManifest() {
286
+ return [];
287
+ }
288
+ summary() {
289
+ return { filesProcessed: 0, atomCount: 0, recipeCount: 0, slotRecipeCount: 0 };
290
+ }
291
+ compile() {
292
+ return emptyCompileOutput();
293
+ }
294
+ getLayerCss(_options) {
295
+ return emptyCompileOutput();
296
+ }
297
+ getKeyframeCss(_options) {
298
+ return emptyCompileOutput();
299
+ }
300
+ getSplitCss(_options) {
301
+ return { files: [], diagnostics: [] };
302
+ }
303
+ buildInfo = fallbackBuildInfo;
304
+ designSystem = fallbackDesignSystem;
305
+ generateArtifacts() {
306
+ return [];
307
+ }
308
+ generateArtifact() {
309
+ return void 0;
310
+ }
311
+ generateAffectedArtifacts() {
312
+ return [];
313
+ }
314
+ diagnostics() {
315
+ return [];
316
+ }
317
+ };
318
+ var fallback = {
319
+ startTracing() {
320
+ return false;
321
+ },
322
+ flushTracing() {
323
+ },
324
+ takeTimingsJson() {
325
+ return void 0;
326
+ },
327
+ shutdownTracing() {
328
+ return false;
329
+ },
330
+ compile() {
331
+ return emptyCompileOutput();
332
+ },
333
+ scanImports() {
334
+ return { imports: [], diagnostics: [] };
335
+ },
336
+ matchImports() {
337
+ return [];
338
+ },
339
+ extractCalls() {
340
+ return { calls: [], diagnostics: [] };
341
+ },
342
+ extractJsx() {
343
+ return { jsx: [], diagnostics: [] };
344
+ },
345
+ extract() {
346
+ return { calls: [], jsx: [], diagnostics: [] };
347
+ },
348
+ extractDebug() {
349
+ return { imports: [], matched: [], calls: [], jsx: [], diagnostics: [] };
350
+ },
351
+ Extractor: FallbackExtractor,
352
+ Compiler: FallbackCompiler
353
+ };
354
+ function emptyCompileOutput() {
355
+ return {
356
+ css: "",
357
+ manifest: { files: [], tokens: [] },
358
+ layerRanges: {},
359
+ diagnostics: []
360
+ };
361
+ }
362
+ function emptyWriteCssResult(path) {
363
+ return {
364
+ path,
365
+ ...emptyCompileOutput()
366
+ };
367
+ }
368
+ function emptyWriteSplitCssResult(root) {
369
+ return {
370
+ root,
371
+ paths: [],
372
+ files: [],
373
+ diagnostics: []
374
+ };
375
+ }
376
+
377
+ // src/load-binary.ts
378
+ import { execFileSync } from "node:child_process";
379
+ import { existsSync, mkdirSync, readFileSync, rmSync } from "node:fs";
380
+ import { createRequire } from "node:module";
381
+ import { dirname, join } from "node:path";
382
+ var webContainerWasiPackage = "@pandacss/compiler-wasm32-wasi";
383
+ function loadNativeBinding() {
384
+ const bindingPath = resolveBindingPath();
385
+ if (!bindingPath) return void 0;
386
+ const require2 = createRequire(bindingPath);
387
+ try {
388
+ return require2(bindingPath);
389
+ } catch (error) {
390
+ if (!isWebContainer()) throw error;
391
+ return loadWebContainerBinding(require2, bindingPath, error);
392
+ }
393
+ }
394
+ function resolveBindingPath(referrer = import.meta.url) {
395
+ const packageRoot = resolvePackageRoot(referrer);
396
+ if (packageRoot) {
397
+ const bindingPath = join(packageRoot, "binding.cjs");
398
+ if (existsSync(bindingPath)) return bindingPath;
399
+ }
400
+ return fallbackBindingPaths().find((path) => existsSync(path));
401
+ }
402
+ function resolvePackageRoot(referrer) {
403
+ try {
404
+ return dirname(createRequire(referrer).resolve("@pandacss/compiler/package.json"));
405
+ } catch {
406
+ return void 0;
407
+ }
408
+ }
409
+ function fallbackBindingPaths() {
410
+ const cwd = process.cwd();
411
+ const paths = [join(cwd, "packages/compiler/binding.cjs")];
412
+ if (isCompilerPackageRoot(cwd)) {
413
+ paths.unshift(join(cwd, "binding.cjs"));
414
+ }
415
+ return paths;
416
+ }
417
+ function isCompilerPackageRoot(cwd) {
418
+ try {
419
+ const packageJson = JSON.parse(readFileSync(join(cwd, "package.json"), "utf8"));
420
+ return packageJson.name === "@pandacss/compiler";
421
+ } catch {
422
+ return false;
423
+ }
424
+ }
425
+ function isWebContainer() {
426
+ const versions = process.versions;
427
+ return Boolean(versions.webcontainer);
428
+ }
429
+ function resolveWebContainerBinding(version, root = "/tmp") {
430
+ const baseDir = join(root, `pandacss-compiler-${version}`);
431
+ return {
432
+ baseDir,
433
+ bindingPackage: `${webContainerWasiPackage}@${version}`,
434
+ bindingEntry: join(baseDir, "node_modules", webContainerWasiPackage, "compiler.wasi.cjs")
435
+ };
436
+ }
437
+ function loadWebContainerBinding(require2, bindingPath, nativeError) {
438
+ const version = readCompilerVersion(require2, dirname(bindingPath));
439
+ const { baseDir, bindingPackage, bindingEntry } = resolveWebContainerBinding(version);
440
+ if (!existsSync(bindingEntry)) {
441
+ rmSync(baseDir, { recursive: true, force: true });
442
+ mkdirSync(baseDir, { recursive: true });
443
+ execFileSync("pnpm", ["i", bindingPackage], {
444
+ cwd: baseDir,
445
+ stdio: "inherit"
446
+ });
447
+ }
448
+ try {
449
+ return require2(bindingEntry);
450
+ } catch (fallbackError) {
451
+ throw new Error("Failed to load @pandacss/compiler WebContainer WASI fallback", {
452
+ cause: chainError(nativeError, fallbackError)
453
+ });
454
+ }
455
+ }
456
+ function readCompilerVersion(require2, packageRoot) {
457
+ try {
458
+ const packageJsonPath = require2.resolve("@pandacss/compiler/package.json");
459
+ const packageJson = JSON.parse(readFileSync(packageJsonPath, "utf8"));
460
+ return packageJson.version;
461
+ } catch {
462
+ const packageJson = JSON.parse(readFileSync(join(packageRoot, "package.json"), "utf8"));
463
+ return packageJson.version;
464
+ }
465
+ }
466
+ function chainError(primary, cause) {
467
+ if (primary instanceof Error) {
468
+ primary.cause = cause;
469
+ return primary;
470
+ }
471
+ return cause;
472
+ }
473
+
474
+ // src/index.ts
475
+ import { createUsageReport } from "@pandacss/compiler-shared";
476
+
477
+ // src/driver.ts
478
+ import {
479
+ BaseDriver,
480
+ collectParseDiagnostics,
481
+ diagnosticsPass,
482
+ fromCodegenPrepareArtifacts,
483
+ normalizeDiagnostics
484
+ } from "@pandacss/compiler-shared";
485
+ import {
486
+ buildCodegenOverlay,
487
+ compilePreset,
488
+ defaultImportMap,
489
+ diffConfig,
490
+ filterPublishableLibFiles,
491
+ loadConfig as loadConfig2,
492
+ mergeExcludes,
493
+ readPackageIdentity,
494
+ readPandaVersion as readPandaVersion2,
495
+ resolvePublishedPandaRange,
496
+ resolveSmartInclude,
497
+ syncExports,
498
+ toPosixRelative,
499
+ toRelativeKey
500
+ } from "@pandacss/config";
501
+ import { statSync } from "node:fs";
502
+ import { dirname as dirname2, resolve as resolvePath } from "node:path";
503
+
504
+ // src/design-system.ts
505
+ import "@pandacss/compiler-shared";
506
+ import {
507
+ collectArtifactConflicts,
508
+ readPandaVersion
509
+ } from "@pandacss/config";
510
+ function artifactConflictDiagnostics(metadata) {
511
+ return collectArtifactConflicts(metadata).flatMap((conflict) => [
512
+ ...conflict.recipes.map((name) => artifactConflict("Recipe", name, conflict.name)),
513
+ ...conflict.patterns.map((name) => artifactConflict("Pattern", name, conflict.name))
514
+ ]);
515
+ }
516
+ function artifactConflict(kind, name, designSystem) {
517
+ return {
518
+ code: "design_system_artifact_conflict",
519
+ severity: "warning",
520
+ category: "designSystem",
521
+ message: `${kind} ${JSON.stringify(name)} is defined by both ${JSON.stringify(designSystem)} and this config; your definition is merged over the design system's.`
522
+ };
523
+ }
524
+ function hydrateDesignSystem(compiler, options) {
525
+ const { chain, consumerTokenPaths = [], treeshake, importSelections } = options;
526
+ if (!chain || chain.length === 0) {
527
+ return { diagnostics: [], treeshakeKey: "" };
528
+ }
529
+ const pandaVersion = readPandaVersion();
530
+ const diagnostics = [];
531
+ const appSelections = treeshake ? importSelections ?? collectImportSelections(compiler, chain) : void 0;
532
+ const selections = appSelections && withDependencyImports(compiler, chain, appSelections);
533
+ for (let i = 0; i < chain.length; i++) {
534
+ const ds = chain[i];
535
+ const imports = selections ? selections[i] ?? void 0 : void 0;
536
+ diagnostics.push(...hydrateLevel(compiler, ds, pandaVersion, consumerTokenPaths, imports));
537
+ }
538
+ return {
539
+ diagnostics,
540
+ treeshakeKey: treeshakeKeyFromSelections(chain, appSelections)
541
+ };
542
+ }
543
+ var ALL_MODULES = { kind: "all" };
544
+ var NO_MODULES = { kind: "none" };
545
+ function withDependencyImports(compiler, chain, appSelections) {
546
+ const selections = appSelections.map(selectionFromScan);
547
+ for (let i = chain.length - 1; i > 0; i--) {
548
+ const selected = selections[i];
549
+ if (selected.kind === "none") continue;
550
+ const info = readBuildInfo(compiler, chain[i]);
551
+ for (let ancestorIndex = 0; ancestorIndex < i; ancestorIndex++) {
552
+ const imported = info ? compiler.designSystem.dependencyImports(info, selectionToImports(selected), chain[ancestorIndex].name) : void 0;
553
+ selections[ancestorIndex] = mergeSelection(selections[ancestorIndex], selectionFromImports(imported));
554
+ }
555
+ }
556
+ return selections.map(selectionToScan);
557
+ }
558
+ function selectionFromScan(selection) {
559
+ if (selection == null) return ALL_MODULES;
560
+ return selection.length === 0 ? NO_MODULES : { kind: "names", names: selection };
561
+ }
562
+ function selectionFromImports(imports) {
563
+ if (imports === void 0) return ALL_MODULES;
564
+ return imports.length === 0 ? NO_MODULES : { kind: "names", names: imports };
565
+ }
566
+ function selectionToImports(selection) {
567
+ if (selection.kind === "all") return void 0;
568
+ return selection.kind === "none" ? [] : selection.names;
569
+ }
570
+ function selectionToScan(selection) {
571
+ if (selection.kind === "all") return null;
572
+ return selection.kind === "none" ? [] : selection.names;
573
+ }
574
+ function mergeSelection(current, added) {
575
+ if (current.kind === "all" || added.kind === "all") return ALL_MODULES;
576
+ if (current.kind === "none") return added;
577
+ if (added.kind === "none") return current;
578
+ return { kind: "names", names: [.../* @__PURE__ */ new Set([...current.names, ...added.names])] };
579
+ }
580
+ function readBuildInfo(compiler, ds) {
581
+ if (ds.optionMismatch?.length) return void 0;
582
+ try {
583
+ const content = compiler.fs.readFile(ds.buildInfoPath);
584
+ if (content == null) return void 0;
585
+ const info = JSON.parse(content);
586
+ return compiler.buildInfo.validate(info).ok ? info : void 0;
587
+ } catch {
588
+ return void 0;
589
+ }
590
+ }
591
+ function designSystemDependencies(chain) {
592
+ return (chain ?? []).map((ds) => ({
593
+ name: ds.name,
594
+ packageRoots: getPackageRoots(ds),
595
+ excludeModules: getExcludedModules(ds)
596
+ }));
597
+ }
598
+ function collectImportSelections(compiler, chain) {
599
+ return compiler.designSystemImportSelections(
600
+ chain.map((ds) => ({
601
+ packageRoots: getPackageRoots(ds),
602
+ excludeModules: getExcludedModules(ds)
603
+ }))
604
+ );
605
+ }
606
+ function treeshakeKeyFromSelections(chain, selections) {
607
+ if (!selections?.length) return "";
608
+ return chain.map((ds, i) => `${ds.name}:${JSON.stringify(selections[i] ?? null)}`).join("|");
609
+ }
610
+ var STYLED_SYSTEM_SUBPATHS = ["css", "recipes", "patterns", "jsx", "tokens"];
611
+ function getPackageRoots(ds) {
612
+ return [...new Set([ds.specifier, ds.name].filter((value) => Boolean(value)))];
613
+ }
614
+ function getExcludedModules(ds) {
615
+ const excluded = /* @__PURE__ */ new Set();
616
+ for (const root of getPackageRoots(ds)) {
617
+ for (const sub of STYLED_SYSTEM_SUBPATHS) {
618
+ excluded.add(`${root}/${sub}`);
619
+ }
620
+ }
621
+ const map = ds.importMap;
622
+ if (map) {
623
+ for (const value of [map.css, map.recipes, map.patterns, map.jsx, map.tokens]) {
624
+ if (typeof value === "string" && value.length > 0) excluded.add(value);
625
+ }
626
+ }
627
+ return [...excluded];
628
+ }
629
+ function hydrateLevel(compiler, ds, pandaVersion, consumerTokenPaths, imports) {
630
+ const compat = compiler.designSystem.validate(ds.manifest, { pandaVersion });
631
+ if (!compat.ok) {
632
+ throw incompatibleManifestError(compiler, ds, compat.reason, pandaVersion);
633
+ }
634
+ const diagnostics = hydrateArtifacts(compiler, ds, pandaVersion, imports);
635
+ diagnostics.push(...tokenConflictDiagnostics(ds, consumerTokenPaths));
636
+ return diagnostics;
637
+ }
638
+ function hydrateArtifacts(compiler, ds, pandaVersion, imports) {
639
+ if (ds.optionMismatch && ds.optionMismatch.length > 0) {
640
+ const diagnostic = recoverFromSources(
641
+ compiler,
642
+ ds,
643
+ (sourceCount, severity) => optionMismatchDiagnostic(ds, sourceCount, severity)
644
+ );
645
+ return [diagnostic];
646
+ }
647
+ let buildInfo;
648
+ try {
649
+ const content = compiler.fs.readFile(ds.buildInfoPath);
650
+ if (content == null) {
651
+ throw new Error("file not found");
652
+ }
653
+ buildInfo = JSON.parse(content);
654
+ } catch (error) {
655
+ const issue = { kind: "read", detail: errorMessage(error) };
656
+ const diagnostic = recoverFromSources(
657
+ compiler,
658
+ ds,
659
+ (sourceCount, severity) => buildInfoDiagnostic(ds, issue, sourceCount, severity)
660
+ );
661
+ return [diagnostic];
662
+ }
663
+ const result = compiler.designSystem.load(ds.manifest, {
664
+ buildInfo,
665
+ pandaVersion,
666
+ ...imports !== void 0 ? { imports } : {}
667
+ });
668
+ if (!result.ok) {
669
+ const issue = result.reason === "schemaVersion" ? {
670
+ kind: "schemaVersion",
671
+ received: buildInfo.schemaVersion,
672
+ expected: compiler.buildInfo.schemaVersion
673
+ } : { kind: "corrupt" };
674
+ const diagnostic = recoverFromSources(
675
+ compiler,
676
+ ds,
677
+ (sourceCount, severity) => buildInfoDiagnostic(ds, issue, sourceCount, severity)
678
+ );
679
+ return [diagnostic];
680
+ }
681
+ return [];
682
+ }
683
+ function recoverFromSources(compiler, ds, createDiagnostic) {
684
+ const sources = extractFallbackSources(compiler, ds);
685
+ const severity = sources.length === 0 ? "error" : "warning";
686
+ const diagnostic = createDiagnostic(sources.length, severity);
687
+ if (sources.length === 0) {
688
+ throw diagnosticError(diagnostic);
689
+ }
690
+ compiler.parseFiles(sources);
691
+ return diagnostic;
692
+ }
693
+ function extractFallbackSources(compiler, ds) {
694
+ if (ds.files.length === 0) {
695
+ return [];
696
+ }
697
+ const filesCwd = compiler.path.resolve(compiler.path.join([compiler.path.dirname(ds.manifestPath), ".."]));
698
+ return compiler.scan({ include: ds.files, cwd: filesCwd });
699
+ }
700
+ function buildInfoDiagnostic(ds, issue, sourceCount, severity) {
701
+ const reason = buildInfoIssueMessage(issue);
702
+ const outcome = sourceCount > 0 ? ` Re-extracted ${sourceCount} source ${sourceCount === 1 ? "file" : "files"}.` : " No fallback source files were available.";
703
+ return {
704
+ code: "design_system_buildinfo_stale",
705
+ severity,
706
+ category: "designSystem",
707
+ file: ds.buildInfoPath,
708
+ message: `${JSON.stringify(ds.name)} build info ${reason}.${outcome}`,
709
+ help: [`Run \`panda lib\` in ${JSON.stringify(ds.name)} to rebuild panda/buildinfo.json.`]
710
+ };
711
+ }
712
+ function buildInfoIssueMessage(issue) {
713
+ if (issue.kind === "schemaVersion") {
714
+ return `uses schemaVersion ${formatValue(issue.received)}; expected ${issue.expected}`;
715
+ }
716
+ if (issue.kind === "read") {
717
+ return `could not be read: ${issue.detail}`;
718
+ }
719
+ return "is malformed or corrupt";
720
+ }
721
+ function optionMismatchDiagnostic(ds, sourceCount, severity) {
722
+ const options = ds.optionMismatch?.join(", ") ?? "class-name options";
723
+ const outcome = sourceCount > 0 ? ` Re-extracted ${sourceCount} source ${sourceCount === 1 ? "file" : "files"} with the consumer options.` : " No fallback source files were available, so the prebuilt class names cannot be used safely.";
724
+ return {
725
+ code: "design_system_option_mismatch",
726
+ severity,
727
+ category: "designSystem",
728
+ file: ds.manifestPath,
729
+ message: `${JSON.stringify(ds.name)} was built with different ${options}.${outcome}`,
730
+ help: [`Match ${options} with ${JSON.stringify(ds.name)}, or rebuild it with \`panda lib\`.`]
731
+ };
732
+ }
733
+ function tokenConflictDiagnostics(ds, consumerTokenPaths) {
734
+ if (consumerTokenPaths.length === 0 || ds.tokenPaths.length === 0) {
735
+ return [];
736
+ }
737
+ const designSystemTokenPaths = new Set(ds.tokenPaths);
738
+ const conflicts = [...new Set(consumerTokenPaths.filter((path) => designSystemTokenPaths.has(path)))].sort();
739
+ if (conflicts.length === 0) {
740
+ return [];
741
+ }
742
+ const preview = conflicts.slice(0, 3).map((path) => JSON.stringify(path)).join(", ");
743
+ const remainder = conflicts.length > 3 ? ` and ${conflicts.length - 3} more` : "";
744
+ return [
745
+ {
746
+ code: "design_system_token_conflict",
747
+ severity: "info",
748
+ category: "designSystem",
749
+ file: ds.manifestPath,
750
+ message: `${conflicts.length} token ${conflicts.length === 1 ? "path is" : "paths are"} defined by both ${JSON.stringify(ds.name)} and this config (${preview}${remainder}); the local values win.`
751
+ }
752
+ ];
753
+ }
754
+ function incompatibleManifestError(compiler, ds, reason, pandaVersion) {
755
+ if (reason === "schemaVersion") {
756
+ return diagnosticError({
757
+ code: "design_system_version_mismatch",
758
+ severity: "error",
759
+ category: "designSystem",
760
+ file: ds.manifestPath,
761
+ message: `${JSON.stringify(ds.name)} panda/lib.json uses schemaVersion ${ds.manifest.schemaVersion}; expected ${compiler.designSystem.schemaVersion}.`,
762
+ help: [`Upgrade ${JSON.stringify(ds.name)}, or rebuild it with a compatible version of Panda.`]
763
+ });
764
+ }
765
+ const running = pandaVersion ? `; the consumer uses ${pandaVersion}` : "";
766
+ return diagnosticError({
767
+ code: "design_system_peer_range_unsatisfied",
768
+ severity: "error",
769
+ category: "designSystem",
770
+ file: ds.manifestPath,
771
+ message: `${JSON.stringify(ds.name)} requires Panda ${ds.manifest.panda}${running}.`,
772
+ help: [`Install a compatible Panda version or update ${JSON.stringify(ds.name)}.`]
773
+ });
774
+ }
775
+ function diagnosticError(diagnostic) {
776
+ const error = new Error(diagnostic.message);
777
+ error.diagnostics = [diagnostic];
778
+ return error;
779
+ }
780
+ function formatValue(value) {
781
+ return typeof value === "number" || typeof value === "string" ? JSON.stringify(value) : String(value);
782
+ }
783
+ function errorMessage(error) {
784
+ return error instanceof Error ? error.message : String(error);
785
+ }
786
+
787
+ // src/tooling/create-project.ts
788
+ import { defaultConfig } from "@pandacss/compiler-shared";
789
+ import {
790
+ collectExportMissingDiagnostics,
791
+ collectNameCollisionDiagnostics,
792
+ loadConfig
793
+ } from "@pandacss/config";
794
+ function treeshakeDesignSystemEnabled(config) {
795
+ const optimize = config.optimize;
796
+ return optimize?.treeshakeDesignSystem === true;
797
+ }
798
+ function createProjectFromLoadedConfig(loaded) {
799
+ const compiler = createCompilerFromSnapshot({
800
+ config: loaded.config,
801
+ callbacks: loaded.callbacks,
802
+ hooks: loaded.hooks
803
+ });
804
+ const hydrated = hydrateDesignSystem(compiler, {
805
+ chain: loaded.metadata?.designSystem,
806
+ consumerTokenPaths: loaded.metadata?.userTokenPaths ?? [],
807
+ treeshake: treeshakeDesignSystemEnabled(loaded.config)
808
+ });
809
+ const designSystemDiagnostics = [
810
+ ...hydrated.diagnostics,
811
+ ...artifactConflictDiagnostics(loaded.metadata),
812
+ ...collectExportMissingDiagnostics(loaded.metadata),
813
+ ...collectNameCollisionDiagnostics(loaded.metadata)
814
+ ];
815
+ return {
816
+ compiler,
817
+ configPath: loaded.path,
818
+ dependencies: loaded.dependencies,
819
+ outdir: loaded.config.outdir ?? defaultConfig.outdir,
820
+ designSystemDiagnostics,
821
+ designSystemTreeshakeKey: hydrated.treeshakeKey
822
+ };
823
+ }
824
+
825
+ // src/driver.ts
826
+ var DEFAULT_DESIGN_SYSTEM_LIB_OUTDIR = "dist";
827
+ var DEFAULT_DESIGN_SYSTEM_LIB_FILES = ["./**/*.{js,mjs}"];
828
+ async function createNodeDriver(options) {
829
+ const loaded = await loadConfig2({ cwd: options.cwd, file: options.configPath, trackSources: options.trackSources });
830
+ if (options.include?.length) applyIncludeOverride(loaded, options.cwd, options.include);
831
+ return new NodeDriver(options, loaded);
832
+ }
833
+ function applyIncludeOverride(loaded, cwd, include) {
834
+ const deps = new Set(loaded.dependencies);
835
+ const resolved = resolveSmartInclude(include, cwd, deps);
836
+ loaded.config.include = resolved.include;
837
+ if (resolved.excludes.length > 0) {
838
+ const existing = Array.isArray(loaded.config.exclude) ? loaded.config.exclude : void 0;
839
+ loaded.config.exclude = mergeExcludes(existing, resolved.excludes);
840
+ }
841
+ loaded.dependencies = Array.from(deps);
842
+ }
843
+ var NodeDriver = class extends BaseDriver {
844
+ #options;
845
+ #loaded;
846
+ #designSystemDiagnostics;
847
+ #designSystemPreset;
848
+ #designSystemArtifactSnapshot;
849
+ #designSystemWatchTargets;
850
+ #codegenOverlay;
851
+ #codegenOverlayResolved = false;
852
+ #designSystemTreeshakeKey;
853
+ #configFilePaths;
854
+ #designSystemFileKinds;
855
+ #sourceGeneration = 0;
856
+ #treeshakeSyncedGeneration = -1;
857
+ constructor(options, loaded) {
858
+ const built = createProjectFromLoadedConfig(loaded);
859
+ super(built.compiler);
860
+ this.#options = options;
861
+ this.#loaded = loaded;
862
+ this.#designSystemDiagnostics = built.designSystemDiagnostics;
863
+ this.#designSystemArtifactSnapshot = designSystemArtifactSnapshot(loaded);
864
+ this.#designSystemTreeshakeKey = built.designSystemTreeshakeKey ?? "";
865
+ }
866
+ get designSystemDiagnostics() {
867
+ return this.#designSystemDiagnostics;
868
+ }
869
+ configSources() {
870
+ return this.#loaded.metadata?.sources;
871
+ }
872
+ codegenOverlay() {
873
+ if (!this.#codegenOverlayResolved) {
874
+ this.#codegenOverlay = buildCodegenOverlay(this.#loaded.metadata);
875
+ this.#codegenOverlayResolved = true;
876
+ }
877
+ return this.#codegenOverlay;
878
+ }
879
+ get config() {
880
+ return this.#loaded.config;
881
+ }
882
+ get configPath() {
883
+ return this.#loaded.path;
884
+ }
885
+ get configDependencies() {
886
+ return this.#loaded.dependencies;
887
+ }
888
+ designSystemWatchTargets() {
889
+ return this.#designSystemWatchTargets ??= (this.#loaded.metadata?.designSystem ?? []).map((ds) => {
890
+ const manifestDir = this.compiler.path.dirname(ds.manifestPath);
891
+ const presetPath = realpathIfExists(this.compiler, this.compiler.path.resolve(ds.manifest.preset, manifestDir));
892
+ const filesCwd = designSystemFilesCwd(this.compiler, ds.manifestPath);
893
+ const sourceFiles = ds.files.length > 0 ? this.compiler.scan({ include: ds.files, cwd: filesCwd }).map((file) => realpathIfExists(this.compiler, file)) : [];
894
+ return {
895
+ name: ds.name,
896
+ manifestPath: realpathIfExists(this.compiler, ds.manifestPath),
897
+ buildInfoPath: realpathIfExists(this.compiler, ds.buildInfoPath),
898
+ presetPath,
899
+ sourceFiles: [...new Set(sourceFiles)]
900
+ };
901
+ });
902
+ }
903
+ isDesignSystemFile(file) {
904
+ const kinds = this.#designSystemFileKinds ??= this.buildDesignSystemFileKinds();
905
+ return kinds.get(this.compiler.path.realpath(file)) ?? false;
906
+ }
907
+ buildDesignSystemFileKinds() {
908
+ const kinds = /* @__PURE__ */ new Map();
909
+ for (const watchTarget of this.#designSystemWatchTargets ?? this.designSystemWatchTargets()) {
910
+ for (const path of [watchTarget.manifestPath, watchTarget.buildInfoPath, watchTarget.presetPath]) {
911
+ kinds.set(this.compiler.path.realpath(path), "artifact");
912
+ }
913
+ for (const path of watchTarget.sourceFiles) {
914
+ kinds.set(this.compiler.path.realpath(path), "source");
915
+ }
916
+ }
917
+ return kinds;
918
+ }
919
+ async syncDesignSystemFileChange(change) {
920
+ const kind = this.isDesignSystemFile(change.path);
921
+ if (kind === "artifact") {
922
+ const diff = await this.reload();
923
+ if (diff.hasChanged) this.parseFiles();
924
+ return diff.hasChanged;
925
+ }
926
+ if (kind === "source") return this.applySourceChange(change, "design-system");
927
+ return false;
928
+ }
929
+ syncDesignSystemSources() {
930
+ const changes = [];
931
+ const activeFiles = new Map(
932
+ this.compiler.fileManifest().map((file) => [this.compiler.path.realpath(file.path), file.path])
933
+ );
934
+ for (const target of this.designSystemWatchTargets()) {
935
+ for (const path of target.sourceFiles) {
936
+ const activePath = activeFiles.get(this.compiler.path.realpath(path));
937
+ if (!activePath) continue;
938
+ changes.push({ path: activePath, kind: this.compiler.fs.exists(path) ? "change" : "unlink" });
939
+ }
940
+ }
941
+ return this.applyChanges(changes);
942
+ }
943
+ async reload() {
944
+ const next = await loadConfig2({
945
+ cwd: this.#options.cwd,
946
+ file: this.#options.configPath,
947
+ trackSources: this.#options.trackSources
948
+ });
949
+ if (this.#options.include?.length) applyIncludeOverride(next, this.#options.cwd, this.#options.include);
950
+ const diff = diffConfig(this.#loaded, next);
951
+ const nextDesignSystemArtifactSnapshot = designSystemArtifactSnapshot(next);
952
+ const designSystemArtifactsChanged = this.#designSystemArtifactSnapshot !== nextDesignSystemArtifactSnapshot;
953
+ if (diff.hasChanged || designSystemArtifactsChanged) {
954
+ this.#loaded = next;
955
+ const built = createProjectFromLoadedConfig(next);
956
+ this.setCompiler(built.compiler);
957
+ this.#designSystemDiagnostics = built.designSystemDiagnostics;
958
+ this.#designSystemPreset = void 0;
959
+ this.#designSystemArtifactSnapshot = nextDesignSystemArtifactSnapshot;
960
+ this.#designSystemWatchTargets = void 0;
961
+ this.#codegenOverlay = void 0;
962
+ this.#codegenOverlayResolved = false;
963
+ this.#designSystemTreeshakeKey = built.designSystemTreeshakeKey ?? "";
964
+ this.#configFilePaths = void 0;
965
+ this.#designSystemFileKinds = void 0;
966
+ this.#sourceGeneration++;
967
+ this.#treeshakeSyncedGeneration = -1;
968
+ }
969
+ return designSystemArtifactsChanged && !diff.hasChanged ? { ...diff, hasChanged: true } : diff;
970
+ }
971
+ /** Re-hydrate when treeshake import set changes. */
972
+ syncDesignSystemTreeShake() {
973
+ if (!treeshakeDesignSystemEnabled(this.#loaded.config)) return false;
974
+ const chain = this.#loaded.metadata?.designSystem;
975
+ if (!chain?.length) return false;
976
+ if (this.#treeshakeSyncedGeneration === this.#sourceGeneration) return false;
977
+ const selections = collectImportSelections(this.compiler, chain);
978
+ const nextKey = treeshakeKeyFromSelections(chain, selections);
979
+ this.#treeshakeSyncedGeneration = this.#sourceGeneration;
980
+ if (nextKey === this.#designSystemTreeshakeKey) return false;
981
+ const hydrated = hydrateDesignSystem(this.compiler, {
982
+ chain,
983
+ consumerTokenPaths: this.#loaded.metadata?.userTokenPaths ?? [],
984
+ treeshake: true,
985
+ importSelections: selections
986
+ });
987
+ this.#designSystemDiagnostics = hydrated.diagnostics;
988
+ this.#designSystemTreeshakeKey = hydrated.treeshakeKey;
989
+ return true;
990
+ }
991
+ prepareCssOutput() {
992
+ this.syncDesignSystemTreeShake();
993
+ }
994
+ applyChange(change) {
995
+ return this.applySourceChange(change, "project");
996
+ }
997
+ applySourceChange(change, admission) {
998
+ const changed = this.trackSourceChange(change, this.admitSourceChange(change, admission));
999
+ const refreshed = this.refreshAffectedFiles();
1000
+ return this.recordSourceChange(changed || refreshed);
1001
+ }
1002
+ /** Known files always refresh; unknown project paths must match the source globs. */
1003
+ admitSourceChange(change, admission) {
1004
+ if (change.kind === "unlink") return this.compiler.removeFile(change.path);
1005
+ const refreshed = change.content == null ? this.compiler.refreshFile(change.path) : this.compiler.refreshFileSource(change.path, change.content);
1006
+ if (refreshed) return true;
1007
+ if (admission === "project" && !this.isSourceFile(change.path)) return false;
1008
+ if (change.content == null) this.compiler.parseFile(change.path);
1009
+ else this.compiler.parseFileSource(change.path, change.content);
1010
+ return true;
1011
+ }
1012
+ recordSourceChange(applied) {
1013
+ if (applied) {
1014
+ this.#sourceGeneration++;
1015
+ this.#treeshakeSyncedGeneration = -1;
1016
+ }
1017
+ return applied;
1018
+ }
1019
+ getOutdir(outdir) {
1020
+ return this.compiler.path.resolve(this.getConfiguredOutdir(outdir));
1021
+ }
1022
+ async writeDesignSystemLib(options = {}) {
1023
+ if (!this.#loaded.path) {
1024
+ throw new Error(
1025
+ "panda lib requires a resolved config file to compile the design system preset. Run `panda init`, or check --config/--cwd."
1026
+ );
1027
+ }
1028
+ const parsed = this.parseDesignSystemLib();
1029
+ if (!diagnosticsPass(parsed.diagnostics, { maxWarnings: options.maxWarnings }))
1030
+ return skippedDesignSystemLib(parsed);
1031
+ const preset = await this.compileDesignSystemPreset();
1032
+ return this.writeDesignSystemLibArtifacts(options, preset, parsed);
1033
+ }
1034
+ codegen(options) {
1035
+ const outdir = this.getOutdir(options?.outdir);
1036
+ const cwd = options?.cwd ?? this.#options.cwd;
1037
+ const prepareHooks = this.#loaded.hostHooks?.["codegen:prepare"] ?? [];
1038
+ const doneHooks = this.#loaded.hostHooks?.["codegen:done"] ?? [];
1039
+ const files = prepareHooks.length > 0 ? this.codegenWithPrepareHooks(prepareHooks, outdir, cwd, options) : super.codegen(options);
1040
+ for (const entry of doneHooks) {
1041
+ const handler = resolveHookHandler(entry.value, "codegen:done");
1042
+ handler({ files, outdir, cwd });
1043
+ }
1044
+ return files;
1045
+ }
1046
+ cssgen(options) {
1047
+ const output = super.cssgen(options);
1048
+ this.runCssgenDone({
1049
+ artifact: "styles.css",
1050
+ content: output.css,
1051
+ cwd: this.#options.cwd,
1052
+ manifest: output.manifest,
1053
+ layerRanges: output.layerRanges
1054
+ });
1055
+ return output;
1056
+ }
1057
+ writeCss(options) {
1058
+ const result = super.writeCss(options);
1059
+ this.runCssgenDone({
1060
+ artifact: "styles.css",
1061
+ content: result.css,
1062
+ path: result.path,
1063
+ outfile: options.outfile,
1064
+ cwd: options.cwd ?? this.#options.cwd,
1065
+ manifest: result.manifest,
1066
+ layerRanges: result.layerRanges
1067
+ });
1068
+ return result;
1069
+ }
1070
+ writeLayerCss(options) {
1071
+ const result = super.writeLayerCss(options);
1072
+ this.runCssgenDone({
1073
+ artifact: "styles.layer",
1074
+ content: result.css,
1075
+ path: result.path,
1076
+ outfile: options.outfile,
1077
+ cwd: options.cwd ?? this.#options.cwd,
1078
+ manifest: result.manifest,
1079
+ layerRanges: result.layerRanges
1080
+ });
1081
+ return result;
1082
+ }
1083
+ writeSplitCss(options) {
1084
+ const result = super.writeSplitCss(options);
1085
+ const cwd = options?.cwd ?? this.#options.cwd;
1086
+ const outdir = result.root;
1087
+ for (const file of result.files) {
1088
+ const path = this.compiler.path.join([result.root, file.path]);
1089
+ this.runCssgenDone({
1090
+ artifact: "styles.split",
1091
+ content: file.code,
1092
+ path,
1093
+ outdir,
1094
+ cwd
1095
+ });
1096
+ }
1097
+ return result;
1098
+ }
1099
+ runCssgenDone(args) {
1100
+ const hooks = this.#loaded.hostHooks?.["cssgen:done"] ?? [];
1101
+ for (const entry of hooks) {
1102
+ const handler = resolveHookHandler(entry.value, "cssgen:done");
1103
+ handler(args);
1104
+ }
1105
+ }
1106
+ codegenWithPrepareHooks(hooks, outdir, cwd, options) {
1107
+ const overlay = this.codegenOverlay();
1108
+ let artifacts = this.compiler.generateArtifacts({ ...toGenerateArtifactOptions(options), overlay });
1109
+ for (const entry of hooks) {
1110
+ const handler = resolveHookHandler(entry.value, "codegen:prepare");
1111
+ const next = handler({ artifacts, outdir, cwd });
1112
+ if (next !== void 0) {
1113
+ if (!Array.isArray(next)) {
1114
+ throw new Error("Invalid codegen:prepare hook result. Expected an artifact array or undefined.");
1115
+ }
1116
+ artifacts = fromCodegenPrepareArtifacts(next);
1117
+ }
1118
+ }
1119
+ return this.compiler.writeArtifacts({
1120
+ outdir,
1121
+ cwd,
1122
+ forceImportExtension: options?.forceImportExtension,
1123
+ artifacts,
1124
+ overlay
1125
+ });
1126
+ }
1127
+ isConfigFile(file) {
1128
+ const paths = this.#configFilePaths ??= this.buildConfigFilePaths();
1129
+ return paths.has(this.compiler.path.realpath(file));
1130
+ }
1131
+ buildConfigFilePaths() {
1132
+ const paths = /* @__PURE__ */ new Set();
1133
+ if (this.#loaded.path) {
1134
+ paths.add(this.compiler.path.realpath(this.#loaded.path));
1135
+ }
1136
+ for (const dependency of this.#loaded.dependencies) {
1137
+ const dependencyPath = this.compiler.path.resolve(dependency, this.#options.cwd);
1138
+ paths.add(this.compiler.path.realpath(dependencyPath));
1139
+ }
1140
+ return paths;
1141
+ }
1142
+ parseDesignSystemLib() {
1143
+ const parsed = this.parseFiles();
1144
+ const parseDiagnostics = collectParseDiagnostics(parsed, {
1145
+ normalizeFile: (file) => stabilizePath(this.#options.cwd, file)
1146
+ });
1147
+ const diagnostics = normalizeDiagnostics([...parseDiagnostics, ...this.compiler.diagnostics()], {
1148
+ normalizeFile: (file) => stabilizePath(this.#options.cwd, file)
1149
+ });
1150
+ return { parsedFileCount: parsed.length, diagnostics };
1151
+ }
1152
+ async compileDesignSystemPreset() {
1153
+ return this.#designSystemPreset ??= await compilePreset({
1154
+ configPath: this.#loaded.path,
1155
+ cwd: this.#options.cwd
1156
+ });
1157
+ }
1158
+ writeDesignSystemLibArtifacts(options, preset, parsed) {
1159
+ const identity = readPackageIdentity(this.#options.cwd);
1160
+ const pandaRange = resolvePublishedPandaRange(options.panda ?? identity.pandaPeer, readPandaVersion2());
1161
+ const outdir = options.outdir ?? DEFAULT_DESIGN_SYSTEM_LIB_OUTDIR;
1162
+ const outRoot = this.compiler.path.resolve(outdir);
1163
+ const pandaDir = this.compiler.path.join([outRoot, "panda"]);
1164
+ const manifestPath = this.compiler.path.join([pandaDir, "lib.json"]);
1165
+ const buildInfoPath = this.compiler.path.join([pandaDir, "buildinfo.json"]);
1166
+ const presetPath = this.compiler.path.join([pandaDir, "preset.mjs"]);
1167
+ const info = this.compiler.buildInfo.create({
1168
+ panda: pandaRange,
1169
+ designSystemDependencies: designSystemDependencies(this.#loaded.metadata?.designSystem)
1170
+ });
1171
+ const buildInfo = this.compiler.buildInfo.normalize(info, {
1172
+ mapModuleKey: (key) => toRelativeKey(key, this.#options.cwd)
1173
+ });
1174
+ const { files: libFiles, diagnostics: filesDiagnostics } = resolveDesignSystemLibFiles({
1175
+ explicit: options.files,
1176
+ compiler: this.compiler,
1177
+ cwd: this.#options.cwd,
1178
+ filesBase: outRoot,
1179
+ buildInfo,
1180
+ packageRoot: this.compiler.path.dirname(identity.packagePath),
1181
+ publishFiles: identity.publishFiles,
1182
+ packageName: identity.name
1183
+ });
1184
+ const { spec, diagnostics: specDiagnostics } = resolvePublishableSpec({
1185
+ spec: options.spec,
1186
+ compiler: this.compiler,
1187
+ outRoot,
1188
+ pandaDir,
1189
+ packageRoot: this.compiler.path.dirname(identity.packagePath),
1190
+ publishFiles: identity.publishFiles,
1191
+ packageName: identity.name
1192
+ });
1193
+ const manifest = this.compiler.designSystem.create({
1194
+ name: identity.name,
1195
+ version: identity.version,
1196
+ panda: pandaRange,
1197
+ preset: "./preset.mjs",
1198
+ buildInfo: "./buildinfo.json",
1199
+ spec,
1200
+ importMap: defaultImportMap(identity.name),
1201
+ designSystem: typeof this.config.designSystem === "string" ? this.config.designSystem : void 0,
1202
+ files: libFiles
1203
+ });
1204
+ this.compiler.writeArtifacts({
1205
+ outdir,
1206
+ cwd: this.#options.cwd,
1207
+ artifacts: [
1208
+ {
1209
+ id: "design-system-lib",
1210
+ files: [
1211
+ {
1212
+ path: "panda/lib.json",
1213
+ code: `${JSON.stringify(manifest, null, 2)}
1214
+ `,
1215
+ dependencies: []
1216
+ },
1217
+ {
1218
+ path: "panda/buildinfo.json",
1219
+ code: JSON.stringify(buildInfo, null, options.minify ? 0 : 2),
1220
+ dependencies: []
1221
+ },
1222
+ {
1223
+ path: "panda/preset.mjs",
1224
+ code: preset.code,
1225
+ dependencies: []
1226
+ }
1227
+ ]
1228
+ }
1229
+ ]
1230
+ });
1231
+ const { changed: exportsChanged, conflicts } = syncPackageExports(this.compiler, identity.packagePath, {
1232
+ pandaDir,
1233
+ styledDir: this.getOutdir()
1234
+ });
1235
+ return {
1236
+ manifestPath,
1237
+ buildInfoPath,
1238
+ presetPath,
1239
+ exportsChanged,
1240
+ parsedFileCount: parsed.parsedFileCount,
1241
+ diagnostics: [
1242
+ ...parsed.diagnostics,
1243
+ ...filesDiagnostics,
1244
+ ...specDiagnostics,
1245
+ ...exportConflictDiagnostics(identity.name, conflicts)
1246
+ ]
1247
+ };
1248
+ }
1249
+ };
1250
+ function resolvePublishableSpec(options) {
1251
+ if (!options.spec) return { diagnostics: [] };
1252
+ const absolute = options.compiler.path.resolve(options.spec);
1253
+ const { unpublished } = filterPublishableLibFiles({
1254
+ files: [toPosixRelative(options.outRoot, absolute)],
1255
+ packageRoot: options.packageRoot,
1256
+ outRoot: options.outRoot,
1257
+ publishFiles: options.publishFiles
1258
+ });
1259
+ if (unpublished.length > 0) {
1260
+ return { diagnostics: [specNotPublishableDiagnostic(options.packageName, unpublished[0])] };
1261
+ }
1262
+ return { spec: toPosixRelative(options.pandaDir, absolute), diagnostics: [] };
1263
+ }
1264
+ function specNotPublishableDiagnostic(name, spec) {
1265
+ return {
1266
+ code: "design_system_spec_not_publishable",
1267
+ severity: "warning",
1268
+ category: "designSystem",
1269
+ message: `\`panda lib\` left the spec out of ${JSON.stringify(name)}'s manifest because package.json \`"files"\` would not publish ${JSON.stringify(spec)}. A bare \`--spec\` writes it beside preset.mjs, inside what you publish.`
1270
+ };
1271
+ }
1272
+ function resolveDesignSystemLibFiles(options) {
1273
+ if (options.explicit) {
1274
+ return { files: options.explicit, diagnostics: [] };
1275
+ }
1276
+ const inferred = inferDesignSystemLibFiles(options.compiler, options.cwd, options.filesBase, options.buildInfo);
1277
+ const { files, unpublished } = filterPublishableLibFiles({
1278
+ files: inferred,
1279
+ packageRoot: options.packageRoot,
1280
+ outRoot: options.filesBase,
1281
+ publishFiles: options.publishFiles
1282
+ });
1283
+ if (unpublished.length === 0) {
1284
+ return { files, diagnostics: [] };
1285
+ }
1286
+ return {
1287
+ files,
1288
+ diagnostics: [unpublishedLibFilesDiagnostic(options.packageName, unpublished)]
1289
+ };
1290
+ }
1291
+ function unpublishedLibFilesDiagnostic(name, unpublished) {
1292
+ const sample = unpublished.slice(0, 3).map((path) => JSON.stringify(path)).join(", ");
1293
+ const more = unpublished.length > 3 ? `, and ${unpublished.length - 3} more` : "";
1294
+ return {
1295
+ code: "design_system_files_not_publishable",
1296
+ severity: "warning",
1297
+ category: "designSystem",
1298
+ message: `\`panda lib\` omitted ${unpublished.length === 1 ? "a fallback file" : "fallback files"} from ${JSON.stringify(name)}'s manifest because package.json \`"files"\` would not publish ${sample}${more}. Happy-path consumers still hydrate build info. For dist-only recovery, re-run with \`panda lib --files './**/*.{js,mjs}'\` (or the globs you actually publish).`
1299
+ };
1300
+ }
1301
+ function exportConflictDiagnostics(name, conflicts) {
1302
+ if (conflicts.length === 0) return [];
1303
+ const paths = conflicts.map((path) => JSON.stringify(path)).join(", ");
1304
+ const plural = conflicts.length > 1;
1305
+ return [
1306
+ {
1307
+ code: "design_system_export_overwritten",
1308
+ severity: "warning",
1309
+ category: "designSystem",
1310
+ message: `\`panda lib\` overwrote the existing ${paths} export${plural ? "s" : ""} in ${JSON.stringify(name)}'s package.json. Restore or rename ${plural ? "them" : "it"} if you still need the previous target${plural ? "s" : ""}.`
1311
+ }
1312
+ ];
1313
+ }
1314
+ function resolveHookHandler(value, name) {
1315
+ if (typeof value === "function") return value;
1316
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
1317
+ throw new Error(`Invalid ${name} hook. Expected a function or { filter, handler }.`);
1318
+ }
1319
+ const handler = value.handler;
1320
+ if (typeof handler !== "function") {
1321
+ throw new Error(`Invalid ${name} hook. Expected a function or { filter, handler }.`);
1322
+ }
1323
+ return handler;
1324
+ }
1325
+ function skippedDesignSystemLib(parsed) {
1326
+ return {
1327
+ manifestPath: "",
1328
+ buildInfoPath: "",
1329
+ presetPath: "",
1330
+ exportsChanged: false,
1331
+ parsedFileCount: parsed.parsedFileCount,
1332
+ diagnostics: parsed.diagnostics
1333
+ };
1334
+ }
1335
+ var STYLED_SYSTEM_CATEGORIES = ["css", "recipes", "patterns", "jsx", "tokens", "helpers"];
1336
+ var DEEP_IMPORT_CATEGORIES = /* @__PURE__ */ new Set(["css", "recipes", "patterns", "jsx"]);
1337
+ var SINGLE_FILE_CATEGORIES = /* @__PURE__ */ new Set(["helpers"]);
1338
+ function syncPackageExports(compiler, packagePath, paths) {
1339
+ const base = compiler.path.dirname(packagePath);
1340
+ const pandaGlob = `${toPosixRelative(base, paths.pandaDir)}/*`;
1341
+ const entries = {
1342
+ "./panda/*": pandaGlob,
1343
+ ...styledSystemExports(compiler, base, paths.styledDir)
1344
+ };
1345
+ const packageJson = compiler.fs.readFile(packagePath);
1346
+ if (packageJson == null) {
1347
+ throw new Error(`Could not read package.json at ${JSON.stringify(packagePath)}.`);
1348
+ }
1349
+ const result = syncExports({ packageJson, entries });
1350
+ if (result.changed) {
1351
+ compiler.writeArtifacts({
1352
+ outdir: base,
1353
+ artifacts: [
1354
+ {
1355
+ id: "design-system-lib-package",
1356
+ files: [{ path: "package.json", code: result.json, dependencies: [] }]
1357
+ }
1358
+ ]
1359
+ });
1360
+ }
1361
+ return { changed: result.changed, conflicts: result.conflicts };
1362
+ }
1363
+ function styledSystemExports(compiler, base, styledDir) {
1364
+ const rel = (path) => toPosixRelative(base, path);
1365
+ const find = (dir, names) => names.map((name) => compiler.path.join([dir, name])).find((path) => compiler.fs.readFile(path) != null);
1366
+ const entries = {};
1367
+ for (const category of STYLED_SYSTEM_CATEGORIES) {
1368
+ if (SINGLE_FILE_CATEGORIES.has(category)) {
1369
+ const runtime2 = find(styledDir, [`${category}.mjs`, `${category}.js`, `${category}.ts`]);
1370
+ if (!runtime2) continue;
1371
+ const types2 = find(styledDir, [`${category}.d.mts`, `${category}.d.ts`]);
1372
+ entries[`./${category}`] = types2 ? { types: rel(types2), default: rel(runtime2) } : rel(runtime2);
1373
+ continue;
1374
+ }
1375
+ const dir = compiler.path.join([styledDir, category]);
1376
+ const runtime = find(dir, ["index.mjs", "index.js", "index.ts"]);
1377
+ if (!runtime) continue;
1378
+ const types = find(dir, ["index.d.mts", "index.d.ts"]);
1379
+ entries[`./${category}`] = types ? { types: rel(types), default: rel(runtime) } : rel(runtime);
1380
+ if (DEEP_IMPORT_CATEGORIES.has(category)) {
1381
+ const runtimeExt = runtime.endsWith(".mjs") ? "mjs" : runtime.endsWith(".ts") ? "ts" : "js";
1382
+ const runtimeGlob = `${rel(dir)}/*.${runtimeExt}`;
1383
+ const typesGlob = types ? `${rel(dir)}/*.${types.endsWith(".d.mts") ? "d.mts" : "d.ts"}` : void 0;
1384
+ entries[`./${category}/*`] = typesGlob ? { types: typesGlob, default: runtimeGlob } : runtimeGlob;
1385
+ }
1386
+ }
1387
+ return entries;
1388
+ }
1389
+ function stabilizePath(cwd, file) {
1390
+ const relativePath = toRelativeKey(file, cwd);
1391
+ return relativePath && !relativePath.startsWith("..") ? relativePath : file;
1392
+ }
1393
+ function designSystemArtifactSnapshot(loaded) {
1394
+ return JSON.stringify(
1395
+ loaded.metadata?.designSystem?.map((ds) => {
1396
+ const presetPath = resolvePath(dirname2(ds.manifestPath), ds.manifest.preset);
1397
+ return {
1398
+ name: ds.name,
1399
+ specifier: ds.specifier,
1400
+ manifest: ds.manifest,
1401
+ manifestPath: ds.manifestPath,
1402
+ buildInfoPath: ds.buildInfoPath,
1403
+ manifestStamp: diskFileStamp(ds.manifestPath),
1404
+ buildInfoStamp: diskFileStamp(ds.buildInfoPath),
1405
+ presetStamp: diskFileStamp(presetPath),
1406
+ files: ds.files,
1407
+ tokenPaths: ds.tokenPaths
1408
+ };
1409
+ }) ?? []
1410
+ );
1411
+ }
1412
+ function diskFileStamp(path) {
1413
+ try {
1414
+ const stat = statSync(path);
1415
+ return `${stat.mtimeMs}:${stat.size}`;
1416
+ } catch {
1417
+ return "missing";
1418
+ }
1419
+ }
1420
+ function realpathIfExists(compiler, path) {
1421
+ return compiler.fs.exists(path) ? compiler.path.realpath(path) : path;
1422
+ }
1423
+ function designSystemFilesCwd(compiler, manifestPath) {
1424
+ return compiler.path.resolve(compiler.path.join([compiler.path.dirname(manifestPath), ".."]));
1425
+ }
1426
+ function inferDesignSystemLibFiles(compiler, cwd, filesBase, buildInfo) {
1427
+ const files = Object.keys(buildInfo.modules).filter((key) => !key.startsWith("buildinfo:")).map((key) => {
1428
+ const file = compiler.path.resolve(key, cwd);
1429
+ return toPosixRelative(filesBase, file);
1430
+ });
1431
+ return files.length > 0 ? [...new Set(files)] : DEFAULT_DESIGN_SYSTEM_LIB_FILES;
1432
+ }
1433
+ function toGenerateArtifactOptions(options) {
1434
+ return options?.forceImportExtension === void 0 ? void 0 : { forceImportExtension: options.forceImportExtension };
1435
+ }
1436
+
1437
+ // src/index.ts
1438
+ var binding = loadNativeBinding() ?? fallback;
1439
+ var nativeCompilerFromConfig = "fromConfig" in binding.Compiler && typeof binding.Compiler.fromConfig === "function" ? binding.Compiler.fromConfig.bind(binding.Compiler) : void 0;
1440
+ function compile(input) {
1441
+ return binding.compile(input);
1442
+ }
1443
+ function startTracing(options) {
1444
+ return binding.startTracing?.(options) ?? false;
1445
+ }
1446
+ function flushTracing() {
1447
+ binding.flushTracing?.();
1448
+ }
1449
+ function takeTimingsJson() {
1450
+ return binding.takeTimingsJson?.() ?? void 0;
1451
+ }
1452
+ function shutdownTracing() {
1453
+ return binding.shutdownTracing?.() ?? false;
1454
+ }
1455
+ function createCompiler(config, options) {
1456
+ return build(config, options?.callbacks ?? {}, options);
1457
+ }
1458
+ function createCompilerFromSnapshot(snapshot, options) {
1459
+ const callbacks = mergeCallbacks(snapshot.callbacks, options?.callbacks);
1460
+ const hooks = mergeHooks(snapshot.hooks, options?.hooks);
1461
+ return build(snapshot.config, callbacks, { ...options, hooks });
1462
+ }
1463
+ function getBindingInfo() {
1464
+ return {
1465
+ native: binding !== fallback
1466
+ };
1467
+ }
1468
+ function assertNativeBinding(callbacks, hooks) {
1469
+ if (binding !== fallback) return;
1470
+ const needed = ["pattern.transform", "utility.transform"].filter(
1471
+ (key) => Object.keys(callbacks[key] ?? {}).length > 0
1472
+ );
1473
+ if (hooks?.["parser:before"]?.length) needed.push("parser:before");
1474
+ if (needed.length === 0) return;
1475
+ throw new Error(
1476
+ `Could not load the native @pandacss/compiler binding for ${process.platform}-${process.arch}, which ${needed.join(", ")} callbacks require. Reinstall your dependencies to fetch the platform package, or open an issue if your platform is unsupported.`
1477
+ );
1478
+ }
1479
+ function build(config, callbacks, options) {
1480
+ assertProjectCallbacks(config, callbacks);
1481
+ assertProjectHooks(options?.hooks, callbacks);
1482
+ if (!nativeCompilerFromConfig) {
1483
+ throw new Error("createCompiler is not available in this binding");
1484
+ }
1485
+ assertNativeBinding(callbacks, options?.hooks);
1486
+ const prepared = prepareCompilerConfig(config);
1487
+ const compiler = nativeCompilerFromConfig(prepared, toNativeOptions(options), createUtilityValuesCallbacks(callbacks));
1488
+ registerCallbacks(compiler, callbacks, options?.hooks, compiler.tokenDictionary?.());
1489
+ attachFileSystem(compiler);
1490
+ attachPathSystem(compiler);
1491
+ attachBuildInfo(compiler);
1492
+ attachDesignSystem(compiler);
1493
+ attachInspection(compiler);
1494
+ return compiler;
1495
+ }
1496
+ function attachFileSystem(compiler) {
1497
+ Object.defineProperty(compiler, "fs", {
1498
+ value: {
1499
+ readFile: (path) => compiler.readFile(path),
1500
+ exists: (path) => compiler.exists(path)
1501
+ },
1502
+ enumerable: false,
1503
+ configurable: true
1504
+ });
1505
+ }
1506
+ function attachPathSystem(compiler) {
1507
+ Object.defineProperty(compiler, "path", {
1508
+ value: {
1509
+ realpath: (path) => compiler.realpath(path),
1510
+ resolve: (path, cwd) => compiler.resolvePath(path, cwd),
1511
+ join: (parts) => compiler.joinPath(parts),
1512
+ dirname: (path) => compiler.dirname(path)
1513
+ },
1514
+ enumerable: false,
1515
+ configurable: true
1516
+ });
1517
+ }
1518
+ function attachBuildInfo(compiler) {
1519
+ Object.defineProperty(compiler, "buildInfo", {
1520
+ enumerable: false,
1521
+ configurable: true,
1522
+ get() {
1523
+ const api = new BuildInfo2(compiler);
1524
+ Object.defineProperty(compiler, "buildInfo", {
1525
+ value: api,
1526
+ enumerable: false,
1527
+ configurable: true
1528
+ });
1529
+ return api;
1530
+ }
1531
+ });
1532
+ }
1533
+ function attachDesignSystem(compiler) {
1534
+ Object.defineProperty(compiler, "designSystem", {
1535
+ enumerable: false,
1536
+ configurable: true,
1537
+ get() {
1538
+ const api = new DesignSystem2(toDesignSystemBinding(compiler), compiler.buildInfo);
1539
+ Object.defineProperty(compiler, "designSystem", {
1540
+ value: api,
1541
+ enumerable: false,
1542
+ configurable: true
1543
+ });
1544
+ return api;
1545
+ }
1546
+ });
1547
+ }
1548
+ function attachInspection(compiler) {
1549
+ Object.defineProperty(compiler, "inspectFile", {
1550
+ enumerable: false,
1551
+ configurable: true,
1552
+ value: (input) => inspectFile(compiler, input)
1553
+ });
1554
+ Object.defineProperty(compiler, "inspectFiles", {
1555
+ enumerable: false,
1556
+ configurable: true,
1557
+ value: (files) => inspectFiles(compiler, files)
1558
+ });
1559
+ }
1560
+ function toDesignSystemBinding(compiler) {
1561
+ return {
1562
+ createManifest: (input) => compiler.createDesignSystemManifest(input),
1563
+ manifestSchemaVersion: () => compiler.designSystemManifestSchemaVersion()
1564
+ };
1565
+ }
1566
+ function toNativeOptions(options) {
1567
+ if (!options || options.crossFile === void 0) return void 0;
1568
+ return { crossFile: options.crossFile };
1569
+ }
1570
+ function createUtilityValuesCallbacks(callbacks) {
1571
+ const utilityValues = callbacks["utility.values"];
1572
+ if (!utilityValues || Object.keys(utilityValues).length === 0) return void 0;
1573
+ return utilityValues;
1574
+ }
1575
+
1576
+ export {
1577
+ createNodeDriver,
1578
+ NodeDriver,
1579
+ compile,
1580
+ startTracing,
1581
+ flushTracing,
1582
+ takeTimingsJson,
1583
+ shutdownTracing,
1584
+ createCompiler,
1585
+ createCompilerFromSnapshot,
1586
+ getBindingInfo,
1587
+ createUsageReport
1588
+ };