@stillwind/host 0.11.0 → 0.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- import { NativeDesignSystemLoader, completionDetail, editorCssSource, fingerprint, stylesheetPluginPaths } from "@stillwind/native";
1
+ import { NativeDesignSystemLoader, candidateSegments, completionDetail, editorCssSource, fingerprint, stylesheetCatalogInput, stylesheetPluginPaths } from "@stillwind/native";
2
2
  import { PreparationError, checkerEnvironment, prepareSource } from "@stillwind/projection";
3
3
  import { TraceMap, decodedMappings } from "@jridgewell/trace-mapping";
4
4
  import ts from "typescript-6";
@@ -70,19 +70,19 @@ function pluginLoader(session) {
70
70
  return sessions.get(session)?.loader;
71
71
  }
72
72
  /**
73
- * Finds plugin candidates across source texts before individual modules are compiled.
73
+ * Defines the plugin candidates of several sources before individual modules are compiled.
74
74
  *
75
75
  * @param session - Session attached to the project's plugin runtime.
76
76
  * @param loader - Initial loader of the same session.
77
- * @param texts - Original source documents, including templates and embedded scripts.
77
+ * @param candidates - Candidates and variant prefixes that the scans of the sources found, as
78
+ * `NativeModuleSummary.candidates` lists them.
78
79
  * @returns Completion of candidate resolution and any required CSS reload, without publishing modules.
79
80
  * @throws If a plugin or CSS reload fails. Discard this runtime before retrying individual modules.
80
81
  */
81
- async function prepareSourcePlugins(session, loader, texts) {
82
+ async function prepareSourcePlugins(session, loader, candidates) {
82
83
  if (!sessions.has(session)) return;
83
84
  await compileWithPlugins(session, () => {
84
- const query = (pluginLoader(session) ?? loader).editorQuery();
85
- return { modules: [{ dynamicCandidates: [...new Set(texts.flatMap((text) => query.dynamicCandidates(text)))] }] };
85
+ return { modules: [{ dynamicCandidates: (pluginLoader(session) ?? loader).editorQuery().dynamicCandidates([...new Set(candidates)].join(" ")) }] };
86
86
  }, 1);
87
87
  }
88
88
  // src/compilation/host.ts
@@ -263,6 +263,16 @@ var CompilationProject = class {
263
263
  #revision = 0;
264
264
  /** Advances when sources or import links change so checker inputs are installed again. */
265
265
  #generation = 0;
266
+ /**
267
+ * Normalized identities, as {@link sourceKey} defines them, of files that CSS order traversals
268
+ * scanned without retaining them as sources. They are not checker inputs.
269
+ */
270
+ #orderingReads = /* @__PURE__ */ new Set();
271
+ /** Maps that CSS order traversals share, and the revision that they belong to. */
272
+ #ordering = {
273
+ revision: 0,
274
+ maps: /* @__PURE__ */ new Map()
275
+ };
266
276
  /** Last backend and inputs installed by this project. */
267
277
  #installed;
268
278
  /**
@@ -282,6 +292,24 @@ var CompilationProject = class {
282
292
  return this.#revision;
283
293
  }
284
294
  /**
295
+ * Returns a map that CSS order traversals share until the next invalidation. Every change to a
296
+ * file advances the revision, so an entry never outlives the text that it was derived from.
297
+ *
298
+ * @param name - Name of the map. Include the resolver domain when the entries depend on import
299
+ * resolution.
300
+ * @returns The map for the current revision. Callers store only values derived from module text
301
+ * and import resolution.
302
+ */
303
+ orderingCache(name) {
304
+ if (this.#ordering.revision !== this.#revision) this.#ordering = {
305
+ revision: this.#revision,
306
+ maps: /* @__PURE__ */ new Map()
307
+ };
308
+ let map = this.#ordering.maps.get(name);
309
+ if (!map) this.#ordering.maps.set(name, map = /* @__PURE__ */ new Map());
310
+ return map;
311
+ }
312
+ /**
285
313
  * Finds a source prepared since its last invalidation.
286
314
  *
287
315
  * @param id - Full resolver ID. Windows path spelling may differ in case or slashes.
@@ -294,9 +322,29 @@ var CompilationProject = class {
294
322
  sourceKeys() {
295
323
  return [...this.#sources.keys()];
296
324
  }
297
- /** Returns the prepared documents' original text so plugins can find candidates together. */
298
- texts() {
299
- return [...this.#sources.values()].map((record) => record.source.document.code);
325
+ /**
326
+ * Records a file that a CSS order traversal read without retaining it as a source.
327
+ *
328
+ * @param id - Full resolver ID of the file.
329
+ */
330
+ recordOrderingRead(id) {
331
+ this.#orderingReads.add(sourceKey(id));
332
+ }
333
+ /**
334
+ * Returns the normalized identities of files that only CSS order traversals read, as
335
+ * {@link sourceKey} defines them. A full {@link invalidate} clears them.
336
+ */
337
+ orderingReadKeys() {
338
+ return [...this.#orderingReads];
339
+ }
340
+ /**
341
+ * Returns the candidates that the local scans of the prepared sources found, so that plugins
342
+ * can define them together.
343
+ *
344
+ * @returns Candidates and variant prefixes, possibly repeated.
345
+ */
346
+ candidates() {
347
+ return [...this.#sources.values()].flatMap((record) => record.summary.candidates);
300
348
  }
301
349
  /**
302
350
  * Finds the scan results for a prepared source.
@@ -449,6 +497,7 @@ var CompilationProject = class {
449
497
  if (ids === void 0) {
450
498
  this.#sources.clear();
451
499
  this.#reload.clear();
500
+ this.#orderingReads.clear();
452
501
  } else for (const id of typeof ids === "string" ? [ids] : ids) this.#sources.delete(sourceKey(id));
453
502
  for (const record of this.#sources.values()) {
454
503
  record.resolutions = [];
@@ -767,29 +816,49 @@ var CompilationFailure = class extends Error {
767
816
  * @param cause - Optional preparation or checker failure that produced these reports.
768
817
  */
769
818
  constructor(batches, cause) {
770
- super(batches.flatMap((batch) => batch.reports).map(formatReport).join("\n"), { cause });
819
+ super(batches.flatMap((batch) => batch.reports).map((report) => formatReport(report)).join("\n"), { cause });
771
820
  this.batches = batches;
772
821
  }
773
822
  };
774
823
  /**
824
+ * Converts a `file://` URI to a readable filesystem path without requiring Node built-ins.
825
+ *
826
+ * @param uri - Source document URI or filesystem path.
827
+ * @returns Decoded filesystem path for `file://` URIs, or the original string otherwise.
828
+ */
829
+ function displayUri(uri) {
830
+ if (!uri.startsWith("file://")) return uri;
831
+ try {
832
+ const pathname = decodeURIComponent(new URL(uri).pathname);
833
+ return /^\/[A-Za-z]:\//.test(pathname) ? pathname.slice(1) : pathname;
834
+ } catch {
835
+ return uri;
836
+ }
837
+ }
838
+ /**
775
839
  * Formats a compiler report for an Error message or terminal output.
776
840
  *
777
841
  * @param report - Structured report with a primary label, related labels, and notes.
842
+ * @param options - `primaryLocation: false` omits the primary path and range, for hosts that
843
+ * display the primary location separately, such as the Vite error overlay.
778
844
  * @returns Text with one-based line and column ranges for source labels, followed by related labels
779
- * and notes. Document-scoped primary labels use only the URI.
845
+ * and notes. Document-scoped primary labels use only the path.
780
846
  */
781
- function formatReport(report) {
847
+ function formatReport(report, options = {}) {
782
848
  const { location, scope } = report.primary;
783
- const at = scope === "document" ? location.uri : `${location.uri}:${location.startLine + 1}:${location.startColumn + 1}-${location.endLine + 1}:${location.endColumn + 1}`;
784
- const related = report.related.map((label) => {
785
- const loc = label.location;
786
- return ` ${label.scope === "document" ? loc.uri : `${loc.uri}:${loc.startLine + 1}:${loc.startColumn + 1}`}${label.message ? `: ${label.message}` : ""}`;
787
- });
788
- return [
789
- `${at}: ${report.code}: ${report.message}`,
790
- ...related,
791
- ...report.notes.map((note) => ` ${note}`)
792
- ].join("\n");
849
+ const primaryPath = displayUri(location.uri);
850
+ const at = scope === "document" ? primaryPath : `${primaryPath}:${location.startLine + 1}:${location.startColumn + 1}-${location.endLine + 1}:${location.endColumn + 1}`;
851
+ const details = [
852
+ ...report.primary.message ? [` note: ${report.primary.message}`] : [],
853
+ ...report.related.map((label) => {
854
+ const loc = label.location;
855
+ const relatedPath = displayUri(loc.uri);
856
+ return ` related: ${label.scope === "document" ? relatedPath : `${relatedPath}:${loc.startLine + 1}:${loc.startColumn + 1}`}${label.message ? `: ${label.message}` : ""}`;
857
+ }),
858
+ ...report.notes.map((note) => ` note: ${note}`)
859
+ ];
860
+ const heading = `${report.code}: ${report.message}`;
861
+ return [options.primaryLocation === false ? heading : `${at}: ${heading}`, ...details].join("\n");
793
862
  }
794
863
  /** Collects prepared sources and semantic facts for one entry's demanded dependency graph. */
795
864
  var ModuleGraph = class {
@@ -803,6 +872,16 @@ var ModuleGraph = class {
803
872
  #attempted = /* @__PURE__ */ new Map();
804
873
  /** Successful scanner summaries keyed by compiler identity. */
805
874
  #summaries = /* @__PURE__ */ new Map();
875
+ /**
876
+ * Summaries of modules that only ordering imports reached, keyed by compiler identity, for a
877
+ * graph without a project.
878
+ */
879
+ #orderingSummaries = /* @__PURE__ */ new Map();
880
+ /**
881
+ * Complete ordering traversals keyed by resolved module and imported name, for a graph without a
882
+ * project.
883
+ */
884
+ #orderingReach = /* @__PURE__ */ new Map();
806
885
  /** Sources retained for compilation, keyed by full host identity. */
807
886
  #sources = /* @__PURE__ */ new Map();
808
887
  /** Correspondence from compiler identities to full host resolver identities. */
@@ -1178,6 +1257,162 @@ var ModuleGraph = class {
1178
1257
  }
1179
1258
  }
1180
1259
  /**
1260
+ * Returns the complete ordering traversals that this graph may reuse. A project shares them with
1261
+ * the other graphs of its current revision, separately for each resolver domain.
1262
+ *
1263
+ * @returns Traversals keyed by resolved module and imported name.
1264
+ */
1265
+ #orderingReaches() {
1266
+ return this.project?.orderingCache(`reach:${this.host.resolverDomain ?? ""}`) ?? this.#orderingReach;
1267
+ }
1268
+ /**
1269
+ * Returns the summaries of modules that only ordering imports reached. A project shares them
1270
+ * with the other graphs of its current revision.
1271
+ *
1272
+ * @returns Summaries keyed by compiler identity.
1273
+ */
1274
+ #orderingScans() {
1275
+ return this.project?.orderingCache("summaries") ?? this.#orderingSummaries;
1276
+ }
1277
+ /**
1278
+ * Resolves the ordering imports of a source to the modules whose CSS comes first.
1279
+ *
1280
+ * Each import resolves to the module that declares the imported value, after named and
1281
+ * `export *` re-exports. When that module does not import a Stillwind macro module, its own
1282
+ * value imports are followed instead, so a module that reaches a component through a module
1283
+ * without styles still comes after the component. Imports that do not resolve, or resolve to
1284
+ * an external or unsupported module, produce no entry. Every module that the traversal reads
1285
+ * is passed to the host's `watch`, so a change to it compiles the importer again.
1286
+ *
1287
+ * @param source - Importer whose ordering imports are resolved.
1288
+ * @param summary - Scan result of that importer.
1289
+ * @returns Ordering modules for the prepared source. Each entry keeps the authored import that
1290
+ * leads to it, in the order of the summary's imports.
1291
+ */
1292
+ async orderingModules(source, summary) {
1293
+ const modules = [];
1294
+ for (const ordering of summary.orderingImports) {
1295
+ const reached = await this.#orderingTargets(source.resolverId, ordering.source, ordering.imported, /* @__PURE__ */ new Set());
1296
+ for (const id of reached.reads) this.host.watch(id);
1297
+ for (const moduleId of reached.targets) if (moduleId !== source.moduleId) modules.push({
1298
+ source: ordering.source,
1299
+ imported: ordering.imported,
1300
+ moduleId
1301
+ });
1302
+ }
1303
+ return modules;
1304
+ }
1305
+ /**
1306
+ * Returns the modules with styles that one import reaches, and the modules that the traversal
1307
+ * reads to find them.
1308
+ *
1309
+ * A complete result is kept, keyed by the resolved module and the imported name, because the
1310
+ * imports of many sources reach the same shared modules. A result that stopped at a request in
1311
+ * `visited` is not kept. That request was followed earlier in the same traversal, so the importer
1312
+ * at the top of the traversal receives its targets through the earlier path, but this result can
1313
+ * miss them.
1314
+ *
1315
+ * @param importer - Full resolver identity of the importing module.
1316
+ * @param specifier - Authored module request.
1317
+ * @param imported - Imported name, or `*` for a namespace import.
1318
+ * @param visited - Requests that the traversal of one import of a source has followed. Each
1319
+ * request is followed once, which also stops re-export and import cycles.
1320
+ * @returns Compiler identities of the modules with styles, resolver identities of the modules
1321
+ * read, and whether the result is complete.
1322
+ */
1323
+ async #orderingTargets(importer, specifier, imported, visited) {
1324
+ const resolved = await this.#resolveOrdering(importer, specifier);
1325
+ if (!resolved) return {
1326
+ targets: /* @__PURE__ */ new Set(),
1327
+ reads: /* @__PURE__ */ new Set(),
1328
+ complete: true
1329
+ };
1330
+ const key = JSON.stringify([resolved.id, imported]);
1331
+ const kept = this.#orderingReaches().get(key);
1332
+ if (kept) return kept;
1333
+ if (visited.has(key)) return {
1334
+ targets: /* @__PURE__ */ new Set(),
1335
+ reads: /* @__PURE__ */ new Set(),
1336
+ complete: false
1337
+ };
1338
+ visited.add(key);
1339
+ const reach = {
1340
+ targets: /* @__PURE__ */ new Set(),
1341
+ reads: /* @__PURE__ */ new Set([resolved.id]),
1342
+ complete: true
1343
+ };
1344
+ const follow = async (next, name) => {
1345
+ const inner = await this.#orderingTargets(resolved.id, next, name, visited);
1346
+ for (const target of inner.targets) reach.targets.add(target);
1347
+ for (const id of inner.reads) reach.reads.add(id);
1348
+ reach.complete &&= inner.complete;
1349
+ };
1350
+ const summary = await this.#orderingSummary(resolved.id, resolved.moduleId);
1351
+ if (!summary) reach.targets.add(resolved.moduleId);
1352
+ else {
1353
+ const named = imported === "*" ? void 0 : summary.reExports.find((entry) => entry.exported === imported);
1354
+ const stars = summary.reExports.filter((entry) => entry.exported === "*");
1355
+ if (named) await follow(named.source, named.imported);
1356
+ else {
1357
+ if (imported === "*" || summary.localExports.includes(imported) || summary.localExports.length === 0 && summary.reExports.length === 0) {
1358
+ if (summary.macroImports > 0) reach.targets.add(resolved.moduleId);
1359
+ else for (const next of summary.orderingImports) await follow(next.source, next.imported);
1360
+ }
1361
+ for (const entry of imported === "*" ? summary.reExports : stars) await follow(entry.source, imported === "*" ? entry.imported : imported);
1362
+ }
1363
+ }
1364
+ if (reach.complete) this.#orderingReaches().set(key, reach);
1365
+ return reach;
1366
+ }
1367
+ /**
1368
+ * Returns the summary of a module that an ordering import reaches, scanning it when no
1369
+ * summary is retained.
1370
+ *
1371
+ * @param id - Full resolver identity of the module.
1372
+ * @param moduleId - Compiler identity of the module.
1373
+ * @returns The summary, or undefined when the module cannot be loaded or scanned.
1374
+ */
1375
+ async #orderingSummary(id, moduleId) {
1376
+ const retained = this.#summaries.get(moduleId) ?? this.#orderingScans().get(moduleId);
1377
+ if (retained) return retained;
1378
+ const target = this.project?.source(id);
1379
+ const projected = target && this.project?.summary(target);
1380
+ if (projected) return projected;
1381
+ try {
1382
+ const input = await this.#load(id);
1383
+ this.project?.recordOrderingRead(id);
1384
+ const prepared = "kind" in input ? input : await prepareSource(input);
1385
+ const result = tracePhase("scan", 1, () => this.session.scanSource(prepared));
1386
+ if (result.kind === "failed") return;
1387
+ this.#orderingScans().set(moduleId, result.summary);
1388
+ return result.summary;
1389
+ } catch {
1390
+ return;
1391
+ }
1392
+ }
1393
+ /**
1394
+ * Resolves one ordering specifier without loading the target.
1395
+ *
1396
+ * @param importer - Full resolver identity of the importing module.
1397
+ * @param specifier - Authored module request.
1398
+ * @returns The resolver identity and compiler identity of the target, or undefined when the
1399
+ * request does not resolve to a local source.
1400
+ */
1401
+ async #resolveOrdering(importer, specifier) {
1402
+ try {
1403
+ const resolved = await (this.host.resolveOrdering ? this.host.resolveOrdering(specifier, importer) : this.project ? this.project.resolveImport(this.host, specifier, importer) : this.host.resolve(specifier, importer, { skipSelf: true }));
1404
+ if (!resolved || resolved.external) return;
1405
+ const id = this.project?.source(resolved.id)?.resolverId ?? resolved.id;
1406
+ if (sourceSupport(this.host, id) !== "source") return;
1407
+ return {
1408
+ id,
1409
+ moduleId: this.project?.source(id)?.moduleId ?? this.host.describe(id).moduleId
1410
+ };
1411
+ } catch {
1412
+ return;
1413
+ }
1414
+ }
1415
+ /**
1181
1416
  * Uses host resolution first and a checker identity only when the host returns null.
1182
1417
  *
1183
1418
  * @param source - Importer whose full resolver identity is passed to the host.
@@ -1434,7 +1669,13 @@ async function compileGraph(session, factsService, code, id, host, options, anal
1434
1669
  if (entrySummary.macroImports > 0) entrySource.stylesheetImports = options.stylesheetImports;
1435
1670
  entrySource.moduleCssImport = hasModuleCssImport ? options.moduleCssImport : "stillwind/module-css";
1436
1671
  await graph.collectDependencies(entrySource, entrySummary);
1437
- const typedSources = await graph.collectTypedSources(entrySource);
1672
+ const typedSources = await Promise.all((await graph.collectTypedSources(entrySource)).map(async (source) => {
1673
+ const summary = source.moduleId === entrySource.moduleId ? entrySummary : graph.summary(source.moduleId);
1674
+ return summary && summary.orderingImports.length > 0 ? {
1675
+ ...source,
1676
+ orderingModules: await tracePhase("ordering", 1, () => graph.orderingModules(source, summary))
1677
+ } : source;
1678
+ }));
1438
1679
  const producer = analysis ? void 0 : entrySource.moduleId;
1439
1680
  const projectOutput = await tracePhase("native-compile", typedSources.length, () => compileWithPlugins(session, () => session.compile(typedSources, producer), PLUGIN_ROUNDS));
1440
1681
  if (analysis) recordAnalysis(analysis, projectOutput.modules, session, typedSources, graph);
@@ -1610,7 +1851,7 @@ function warnRejectedNames(rejected, warn) {
1610
1851
  function reportLintWarnings(output, host) {
1611
1852
  for (const finding of output.lintFindings ?? []) {
1612
1853
  if ((output.lintSettings?.[finding.rule] ?? "off") === "off") continue;
1613
- host.warn(`${finding.rule}: ${finding.message} (${finding.uri}:${finding.start})`);
1854
+ host.warn(`stillwind: ${finding.rule}: ${finding.message} (${displayUri(finding.uri)}:${finding.startLine + 1}:${finding.startColumn + 1})`);
1614
1855
  }
1615
1856
  }
1616
1857
  /**
@@ -1721,24 +1962,6 @@ function defaultPluginExport(module, specifier) {
1721
1962
  return plugin;
1722
1963
  }
1723
1964
  /**
1724
- * Returns the utility text before the cursor for plugin catalog lookup.
1725
- *
1726
- * @param text - Text before the cursor. The candidate ends at the cursor and starts after the
1727
- * last whitespace, quote, backtick, `;`, `{`, or `}`.
1728
- * @returns The candidate without its variants, such as `icon-mdi--cl` for `hover:icon-mdi--cl`.
1729
- */
1730
- function catalogInput(text) {
1731
- const candidate = /[^\s"'`;{}]*$/.exec(text)[0];
1732
- let depth = 0;
1733
- for (let index = candidate.length - 1; index >= 0; index--) {
1734
- const character = candidate[index];
1735
- if (character === "]" || character === ")") depth++;
1736
- else if ((character === "[" || character === "(") && depth > 0) depth--;
1737
- else if (character === ":" && depth === 0) return candidate.slice(index + 1);
1738
- }
1739
- return candidate;
1740
- }
1741
- /**
1742
1965
  * Identifies one `@plugin` statement independently of its request ID.
1743
1966
  *
1744
1967
  * @param request - Plugin request.
@@ -1916,7 +2139,7 @@ var PluginRuntime = class {
1916
2139
  kind: "plugin",
1917
2140
  name: request.specifier
1918
2141
  },
1919
- tailwind: nativePlugin(plugin) ? void 0 : (await import("./configuration-MQZe6ufN.js")).configurePlugin(plugin, request.pluginOptions ?? [])
2142
+ tailwind: nativePlugin(plugin) ? void 0 : (await import("./configuration-BckWlAj2.js")).configurePlugin(plugin, request.pluginOptions ?? [])
1920
2143
  };
1921
2144
  this.#instances.set(key, instance);
1922
2145
  }
@@ -1949,7 +2172,7 @@ var PluginRuntime = class {
1949
2172
  let current = loader;
1950
2173
  if (instances.length || project) {
1951
2174
  this.#tailwindInstances = instances;
1952
- const { TailwindRuntime } = await import("./plugin-CNOsrkrd.js");
2175
+ const { TailwindRuntime } = await import("./plugin-BG0VOzNB.js");
1953
2176
  const editor = loader.editorQuery();
1954
2177
  this.#tailwind = new TailwindRuntime(instances.map((instance) => instance.tailwind), editor.themeTokens(), editor.legacyThemeKeys(), project);
1955
2178
  if (this.previous) await this.resolve(this.previous.#requested);
@@ -2580,45 +2803,18 @@ var CandidateQueries = class {
2580
2803
  }
2581
2804
  };
2582
2805
  /**
2583
- * Splits at delimiters outside brackets, parentheses, single or double quotes, and escapes.
2584
- * The operation preserves source spelling and does not validate nesting syntax.
2806
+ * Splits at delimiters outside brackets, parentheses, single or double quotes, and escapes,
2807
+ * with the grouping rules of the native candidate parser.
2585
2808
  *
2586
- * @param text - Candidate text whose backslashes escape the following UTF-16 code unit.
2587
- * @param delimiter - One UTF-16 code unit, such as `:` or `/`, that is not a bracket,
2588
- * parenthesis, quote, or backslash.
2589
- * @returns Segments in their original order, including empty segments. Nothing is trimmed
2590
- * or unescaped, and an empty input returns one empty segment.
2809
+ * @param text - Candidate text whose backslashes escape the following character.
2810
+ * @param delimiter - One character, such as `:` or `/`, that is not a bracket, parenthesis,
2811
+ * quote, or backslash.
2812
+ * @returns Segments in their original order, including empty segments. Nothing is trimmed or
2813
+ * unescaped, and an empty input returns one empty segment. After a closing bracket without a
2814
+ * matching opener, the rest of the text stays in the last segment.
2591
2815
  */
2592
2816
  function segments(text, delimiter) {
2593
- const result = [];
2594
- let start = 0;
2595
- let depth = 0;
2596
- let quote = "";
2597
- let escaped = false;
2598
- for (let index = 0; index < text.length; index++) {
2599
- const character = text[index];
2600
- if (escaped) {
2601
- escaped = false;
2602
- continue;
2603
- }
2604
- if (character === "\\") {
2605
- escaped = true;
2606
- continue;
2607
- }
2608
- if (quote) {
2609
- if (character === quote) quote = "";
2610
- continue;
2611
- }
2612
- if (character === "'" || character === "\"") quote = character;
2613
- else if (character === "[" || character === "(") depth++;
2614
- else if (character === "]" || character === ")") depth--;
2615
- else if (character === delimiter && depth === 0) {
2616
- result.push(text.slice(start, index));
2617
- start = index + 1;
2618
- }
2619
- }
2620
- result.push(text.slice(start));
2621
- return result;
2817
+ return candidateSegments(text, delimiter);
2622
2818
  }
2623
2819
  /**
2624
2820
  * Describes an added marker class and the definitions that make it a marker.
@@ -2677,9 +2873,10 @@ function patternExpression(target) {
2677
2873
  * @returns Tokens that match, or every token for an empty target list, and unmatched targets.
2678
2874
  */
2679
2875
  function theme(context, request) {
2680
- const tokens = context.query.themeTokens().map(({ name, value, fallback, inline }) => ({
2876
+ const tokens = context.query.themeTokens().map(({ name, value, resolvedValue, fallback, inline }) => ({
2681
2877
  name,
2682
2878
  value,
2879
+ ...resolvedValue ? { resolvedValue } : {},
2683
2880
  source: fallback ? "default" : "project",
2684
2881
  inline
2685
2882
  })).filter(({ source }) => !request.source || source === request.source);
@@ -2704,14 +2901,14 @@ function theme(context, request) {
2704
2901
  * @returns The candidate, with a suggestion when it is invalid.
2705
2902
  * @throws If a matching utility definition is malformed.
2706
2903
  */
2707
- function describe(query, candidates, annotations, name, kind) {
2904
+ function describe(query, candidates, annotations, name, kind, namesOnly) {
2708
2905
  const css = kind === "variants" ? candidates.variant(name, "utility") : candidates.preview(name);
2709
2906
  const marker = kind === "utilities" ? candidates.marker(name) : null;
2710
2907
  if (css || marker) return {
2711
2908
  name,
2712
2909
  kind: kind === "variants" ? "variant" : marker ? "marker" : "utility",
2713
2910
  valid: true,
2714
- css: css ? query.formatCss(css, annotations) : ""
2911
+ css: !namesOnly && css ? query.formatCss(css, annotations) : ""
2715
2912
  };
2716
2913
  const suggestion = kind === "variants" ? query.suggestCandidate(`${name}:flex`)?.replace(/:flex$/, "") : query.suggestCandidate(name);
2717
2914
  return {
@@ -2744,7 +2941,7 @@ function canonicalSpelling(query, name, kind) {
2744
2941
  * @throws If a plugin fails or a matching utility definition is malformed.
2745
2942
  */
2746
2943
  async function candidates(context, request) {
2747
- const { kind } = request;
2944
+ const { kind, namesOnly = false } = request;
2748
2945
  const catalog = new CandidateQueries(context.query);
2749
2946
  const targets = request.targets.length ? request.targets : ["*"];
2750
2947
  const exact = targets.filter((target) => !isPattern(target));
@@ -2757,9 +2954,11 @@ async function candidates(context, request) {
2757
2954
  const name = variant ? label.slice(0, -1) : label;
2758
2955
  return variant === (kind === "variants") && !name.endsWith("-") && expression.test(name) ? [name] : [];
2759
2956
  });
2957
+ const shapes = kind === "utilities" ? context.query.functionalUtilityPatterns(prefix).filter((shape) => expression.test(shape)) : [];
2760
2958
  patterns.push({
2761
2959
  target,
2762
- names: [...new Set(names)].sort()
2960
+ names: [...new Set(names)].sort(),
2961
+ shapes: [...new Set(shapes)].sort()
2763
2962
  });
2764
2963
  }
2765
2964
  const dynamic = [...exact, ...patterns.flatMap(({ names }) => names)].map((name) => kind === "variants" ? `${name}:` : name).filter((text) => context.query.dynamicCandidates(text).length > 0);
@@ -2768,26 +2967,43 @@ async function candidates(context, request) {
2768
2967
  const seen = new Set(exact);
2769
2968
  const listed = [];
2770
2969
  const unmatched = [];
2771
- for (const { target, names } of patterns) {
2970
+ for (const { target, names, shapes } of patterns) {
2772
2971
  let matched = false;
2972
+ const entries = [];
2773
2973
  for (const name of names) {
2774
2974
  if (seen.has(name)) {
2775
2975
  matched = true;
2776
2976
  continue;
2777
2977
  }
2778
- const candidate = describe(query, queries, context.annotations, name, kind);
2978
+ const candidate = describe(query, queries, context.annotations, name, kind, namesOnly);
2779
2979
  if (candidate.valid) {
2780
2980
  matched = true;
2781
2981
  seen.add(name);
2782
- listed.push(candidate);
2982
+ entries.push(candidate);
2983
+ }
2984
+ }
2985
+ for (const shape of shapes) {
2986
+ if (seen.has(shape)) {
2987
+ matched = true;
2988
+ continue;
2783
2989
  }
2990
+ matched = true;
2991
+ seen.add(shape);
2992
+ entries.push({
2993
+ name: shape,
2994
+ kind: "pattern",
2995
+ valid: true,
2996
+ css: ""
2997
+ });
2784
2998
  }
2999
+ entries.sort((a, b) => a.name.localeCompare(b.name));
3000
+ listed.push(...entries);
2785
3001
  if (!matched) unmatched.push(target);
2786
3002
  }
2787
3003
  return {
2788
3004
  tokens: [],
2789
3005
  candidates: [...exact.map((name) => {
2790
- const candidate = describe(query, queries, context.annotations, name, kind);
3006
+ const candidate = describe(query, queries, context.annotations, name, kind, namesOnly);
2791
3007
  const canonical = candidate.valid ? canonicalSpelling(query, name, kind) : void 0;
2792
3008
  return canonical ? {
2793
3009
  ...candidate,
@@ -3227,7 +3443,8 @@ var CheckerSource = class {
3227
3443
  * @param ids - Resolved source identities mapped to their main checker filenames for import
3228
3444
  * rewriting.
3229
3445
  * @throws If a byte boundary is invalid, producer identities conflict, a mapped producer does not
3230
- * end with a closing parenthesis, edits overlap, or projection decoding fails.
3446
+ * end with a closing parenthesis or does not parse as a call, edits overlap, or projection
3447
+ * decoding fails.
3231
3448
  */
3232
3449
  constructor(source, buffer, index, assets, ids) {
3233
3450
  this.source = source;
@@ -3255,9 +3472,9 @@ var CheckerSource = class {
3255
3472
  });
3256
3473
  const call = buffer.source.slice(start, end);
3257
3474
  if (!call.endsWith(")")) throw new Error(`Cannot locate producer in ${source.moduleId}`);
3258
- const separator = [...call.matchAll(/[,(]/g)].some((match) => skipTrivia(call, match.index + 1) === call.length - 1) ? "" : ",";
3259
- const identity = `{readonly __stillwindDeclarationIdentity:${JSON.stringify(key)}}`;
3260
3475
  const syntax = source.kind === "direct" ? source.syntax : source.projection.syntax;
3476
+ const separator = endsArgumentList(call, scriptKinds[syntax.language]) ? "" : ",";
3477
+ const identity = `{readonly __stillwindDeclarationIdentity:${JSON.stringify(key)}}`;
3261
3478
  const argument = syntax.language === "js" || syntax.language === "jsx" ? `/** @type {${identity}} */ (/** @type {unknown} */ (undefined))` : `undefined as unknown as ${identity}`;
3262
3479
  this.#edits.push({
3263
3480
  at: end - 1,
@@ -3448,19 +3665,29 @@ function projectionPoints(source) {
3448
3665
  function base64url(text) {
3449
3666
  return btoa(String.fromCharCode(...new TextEncoder().encode(text))).replaceAll("+", "-").replaceAll("/", "_").replace(/=+/, "");
3450
3667
  }
3668
+ /** Script kinds of the checker buffer languages. */
3669
+ const scriptKinds = {
3670
+ js: ts.ScriptKind.JS,
3671
+ jsx: ts.ScriptKind.JSX,
3672
+ ts: ts.ScriptKind.TS,
3673
+ tsx: ts.ScriptKind.TSX,
3674
+ dts: ts.ScriptKind.TS
3675
+ };
3451
3676
  /**
3452
- * Finds the next token start after whitespace and comments.
3677
+ * Reports whether a new argument can follow the existing arguments of a call without a comma.
3453
3678
  *
3454
- * @param text - Checker call text to scan.
3455
- * @param offset - UTF-16 position at which scanning starts.
3456
- * @returns UTF-16 start of the next token, or text.length at end of input.
3679
+ * @param call - Text of one call expression, ending with its closing parenthesis.
3680
+ * @param kind - Script kind of the checker buffer that contains the call.
3681
+ * @returns Whether the call has no arguments or ends them with a trailing comma, as in `f()` or
3682
+ * `f(a,)`.
3683
+ * @throws If the text does not parse as a single call expression.
3457
3684
  */
3458
- function skipTrivia(text, offset) {
3459
- const scanner = ts.createScanner(ts.ScriptTarget.Latest, true);
3460
- scanner.setText(text);
3461
- scanner.resetTokenState(offset);
3462
- scanner.scan();
3463
- return scanner.getTokenStart();
3685
+ function endsArgumentList(call, kind) {
3686
+ const file = ts.createSourceFile("call.ts", call, ts.ScriptTarget.Latest, false, kind);
3687
+ const statement = file.statements.length === 1 ? file.statements[0] : void 0;
3688
+ const expression = statement && ts.isExpressionStatement(statement) ? statement.expression : void 0;
3689
+ if (!expression || !ts.isCallExpression(expression) || expression.end !== call.length) throw new Error("Cannot parse producer call");
3690
+ return expression.arguments.length === 0 || expression.arguments.hasTrailingComma === true;
3464
3691
  }
3465
3692
  // src/editor/previews.ts
3466
3693
  /** Captures compiler input plans and assembles their required declaration previews. */
@@ -3551,6 +3778,29 @@ var GeneratedPreviews = class {
3551
3778
  return site ? this.preview(site) : void 0;
3552
3779
  }
3553
3780
  /**
3781
+ * Assembles previews for a sequence of declaration identities in their supplied order,
3782
+ * deduplicating CSS parts and runtime expressions.
3783
+ *
3784
+ * @param identities - Declaration identities to combine.
3785
+ * @returns Combined preview, or undefined if no identity produces CSS.
3786
+ */
3787
+ previewIdentities(identities) {
3788
+ const parts = [];
3789
+ const runtimeNames = /* @__PURE__ */ new Set();
3790
+ for (const identity of identities) {
3791
+ const preview = this.previewIdentity(identity);
3792
+ if (!preview) continue;
3793
+ if (preview.css) parts.push(preview.css);
3794
+ for (const name of preview.runtimeNames) runtimeNames.add(name);
3795
+ }
3796
+ const css = [...new Set(parts)].join("\n");
3797
+ if (!css) return;
3798
+ return {
3799
+ css,
3800
+ runtimeNames: [...runtimeNames]
3801
+ };
3802
+ }
3803
+ /**
3554
3804
  * Assembles `site` and its dependencies from this capture batch. Composed styles precede
3555
3805
  * the site's CSS, and global definitions follow it. Each dependency identity is visited once.
3556
3806
  * Identical CSS parts and runtime expression text are deduplicated in traversal order.
@@ -3562,7 +3812,7 @@ var GeneratedPreviews = class {
3562
3812
  */
3563
3813
  preview(site) {
3564
3814
  const preview = this.assemble(site);
3565
- return preview?.css ? preview : void 0;
3815
+ return preview && (preview.css || preview.js || preview.documentation) ? preview : void 0;
3566
3816
  }
3567
3817
  /**
3568
3818
  * Assembles `site` as {@link preview} does and keeps a successful empty result.
@@ -3572,6 +3822,16 @@ var GeneratedPreviews = class {
3572
3822
  * or undefined if any required site is missing or invalid.
3573
3823
  */
3574
3824
  assemble(site) {
3825
+ if (site.kind === "media") return site.valid && site.css ? {
3826
+ css: "",
3827
+ js: site.css,
3828
+ runtimeNames: []
3829
+ } : void 0;
3830
+ if (site.kind === "ref") return site.valid ? {
3831
+ css: "",
3832
+ documentation: "Adds a generated marker class to the element for ref selectors and queries.",
3833
+ runtimeNames: []
3834
+ } : void 0;
3575
3835
  const parts = [];
3576
3836
  const runtimeNames = /* @__PURE__ */ new Set();
3577
3837
  const seen = /* @__PURE__ */ new Set();
@@ -3760,6 +4020,46 @@ var SourceBindings = class {
3760
4020
  return this.#nodeAssets.get(node);
3761
4021
  }
3762
4022
  /**
4023
+ * Follows a stable identifier or namespace-import reference to its final initializer
4024
+ * expression across the captured source graph. Mutated bindings and cyclic aliases stop
4025
+ * resolution.
4026
+ *
4027
+ * @param source - Prepared source whose checker AST contains `node`.
4028
+ * @param node - Reference expression to resolve.
4029
+ * @returns The declaring source and initializer expression, or undefined when `node` does
4030
+ * not reference a stable variable initializer.
4031
+ */
4032
+ initializer(source, node) {
4033
+ const seen = /* @__PURE__ */ new Set();
4034
+ let currentSource = source;
4035
+ let current = node;
4036
+ let resolved;
4037
+ for (;;) {
4038
+ while (ts.isParenthesizedExpression(current) || ts.isAsExpression(current) || ts.isSatisfiesExpression(current) || ts.isNonNullExpression(current)) current = current.expression;
4039
+ if (ts.isPropertyAccessExpression(current) && ts.isIdentifier(current.expression)) {
4040
+ if (!this.#checker.getSymbolAtLocation(current.expression)?.declarations?.some(ts.isNamespaceImport)) return resolved;
4041
+ } else if (!ts.isIdentifier(current)) return resolved;
4042
+ let symbol = this.#checker.getSymbolAtLocation(current);
4043
+ if (!symbol || this.#mutated.has(symbol) || seen.has(symbol)) return resolved;
4044
+ seen.add(symbol);
4045
+ if (symbol.flags & ts.SymbolFlags.Alias) {
4046
+ symbol = this.#checker.getAliasedSymbol(symbol);
4047
+ if (this.#mutated.has(symbol) || seen.has(symbol)) return resolved;
4048
+ seen.add(symbol);
4049
+ }
4050
+ const declaration = symbol.valueDeclaration;
4051
+ if (!declaration || !ts.isVariableDeclaration(declaration) || !declaration.initializer) return resolved;
4052
+ const owner = this.files.get(declaration.getSourceFile().fileName)?.source;
4053
+ if (!owner) return resolved;
4054
+ currentSource = owner;
4055
+ current = declaration.initializer;
4056
+ resolved = {
4057
+ source: currentSource,
4058
+ node: declaration.initializer
4059
+ };
4060
+ }
4061
+ }
4062
+ /**
3763
4063
  * Returns the comments that contain `swlint-*` directives in `source`'s original buffer.
3764
4064
  *
3765
4065
  * @param source - Prepared source of this index.
@@ -4010,8 +4310,8 @@ var SourceIndex = class {
4010
4310
  for (const argument of node.arguments) if (ts.isStringLiteralLike(argument)) this.#literal(source, argument, "", "elementVariants");
4011
4311
  return;
4012
4312
  }
4013
- if (this.#bindings.producer(node.expression, "cva")) {
4014
- this.#cva(source, node);
4313
+ if (this.#bindings.producer(node.expression, "recipe")) {
4314
+ this.#recipe(source, node);
4015
4315
  return;
4016
4316
  }
4017
4317
  if (this.asset(source, node.expression)?.identity.kind === "keyframes") {
@@ -4087,6 +4387,16 @@ var SourceIndex = class {
4087
4387
  return this.#bindings.asset(source, node);
4088
4388
  }
4089
4389
  /**
4390
+ * Follows a stable variable or import reference to its initializer expression.
4391
+ *
4392
+ * @param source - Prepared source whose checker AST contains `node`.
4393
+ * @param node - Reference expression to resolve.
4394
+ * @returns The declaring source and initializer expression, or undefined when unresolved.
4395
+ */
4396
+ initializer(source, node) {
4397
+ return this.#bindings.initializer(source, node);
4398
+ }
4399
+ /**
4090
4400
  * Recognizes a call of an imported Stillwind style producer or of one of its methods,
4091
4401
  * such as `style()` or `style.when()`.
4092
4402
  *
@@ -4269,52 +4579,76 @@ var SourceIndex = class {
4269
4579
  if (literal) literal.key = true;
4270
4580
  }
4271
4581
  /**
4272
- * Records the variant keys of a `style.cva()` call. The compiler captures the utility
4582
+ * Records the variant keys of a `style.recipe()` call. The compiler captures the utility
4273
4583
  * literals of the call, so this method adds only keys.
4274
4584
  *
4275
4585
  * @param source - Prepared source whose checker AST contains `call`.
4276
- * @param call - Call whose callee is the `cva` method of a Stillwind style import.
4277
- * Keys are read from the base input, from each option of `variants`, and from the
4278
- * `class` and `className` inputs of `compoundVariants`. Other syntax adds nothing.
4586
+ * @param call - Call whose callee is the `recipe` method of a Stillwind style import.
4587
+ * Keys are read from the base input, from each value of `slots`, from each option of
4588
+ * `variants`, and from the `class` and `className` inputs of `compoundVariants` and
4589
+ * `compoundSlots`. With `slots`, an object whose keys all name slots is read slot by slot.
4590
+ * Other syntax adds nothing.
4279
4591
  */
4280
- #cva(source, call) {
4592
+ #recipe(source, call) {
4281
4593
  const [base, config] = call.arguments;
4282
- this.#cvaInput(source, base, "");
4594
+ this.#recipeInput(source, base, "");
4283
4595
  if (!config || !ts.isObjectLiteralExpression(config)) return;
4284
- for (const property of config.properties) {
4285
- if (!ts.isPropertyAssignment(property) || ts.isComputedPropertyName(property.name)) continue;
4596
+ const entries = config.properties.filter((property) => ts.isPropertyAssignment(property) && !ts.isComputedPropertyName(property.name));
4597
+ const slots = /* @__PURE__ */ new Set();
4598
+ for (const property of entries) if (propertyName(property) === "slots" && ts.isObjectLiteralExpression(property.initializer)) {
4599
+ slots.add("base");
4600
+ for (const slot of property.initializer.properties) if (ts.isPropertyAssignment(slot) && !ts.isComputedPropertyName(slot.name)) {
4601
+ slots.add(propertyName(slot));
4602
+ this.#recipeInput(source, slot.initializer, "");
4603
+ }
4604
+ }
4605
+ for (const property of entries) {
4286
4606
  const name = propertyName(property);
4287
4607
  const value = property.initializer;
4288
4608
  if (name === "variants" && ts.isObjectLiteralExpression(value)) {
4289
4609
  for (const axis of value.properties) if (ts.isPropertyAssignment(axis) && ts.isObjectLiteralExpression(axis.initializer)) {
4290
- for (const option of axis.initializer.properties) if (ts.isPropertyAssignment(option)) this.#cvaInput(source, option.initializer, "");
4610
+ for (const option of axis.initializer.properties) if (ts.isPropertyAssignment(option)) this.#recipeSlotInput(source, option.initializer, slots);
4291
4611
  }
4292
- } else if (name === "compoundVariants" && ts.isArrayLiteralExpression(value)) for (const compound of value.elements) {
4612
+ } else if ((name === "compoundVariants" || name === "compoundSlots") && ts.isArrayLiteralExpression(value)) for (const compound of value.elements) {
4293
4613
  if (!ts.isObjectLiteralExpression(compound)) continue;
4294
- for (const entry of compound.properties) if (ts.isPropertyAssignment(entry) && !ts.isComputedPropertyName(entry.name) && ["class", "className"].includes(propertyName(entry))) this.#cvaInput(source, entry.initializer, "");
4614
+ for (const entry of compound.properties) if (ts.isPropertyAssignment(entry) && !ts.isComputedPropertyName(entry.name) && ["class", "className"].includes(propertyName(entry))) this.#recipeSlotInput(source, entry.initializer, name === "compoundVariants" ? slots : /* @__PURE__ */ new Set());
4295
4615
  }
4296
4616
  }
4297
4617
  }
4298
4618
  /**
4299
- * Records the variant keys in one CVA utility input, including keys in nested arrays and
4619
+ * Records the variant keys in a recipe input that may select inputs by slot.
4620
+ *
4621
+ * @param source - Prepared source whose checker AST contains `node`.
4622
+ * @param node - An input for the `base` slot, or an object whose keys all name slots.
4623
+ * @param slots - Declared slot names including `base`, or an empty set without slots.
4624
+ */
4625
+ #recipeSlotInput(source, node, slots) {
4626
+ if (slots.size > 0 && ts.isObjectLiteralExpression(node) && node.properties.length > 0 && node.properties.every((property) => ts.isPropertyAssignment(property) && !ts.isComputedPropertyName(property.name) && slots.has(propertyName(property)))) {
4627
+ for (const property of node.properties) this.#recipeInput(source, property.initializer, "");
4628
+ return;
4629
+ }
4630
+ this.#recipeInput(source, node, "");
4631
+ }
4632
+ /**
4633
+ * Records the variant keys in one recipe utility input, including keys in nested arrays and
4300
4634
  * variant groups.
4301
4635
  *
4302
4636
  * @param source - Prepared source whose checker AST contains `node`.
4303
- * @param node - CVA input, or undefined for an omitted argument.
4637
+ * @param node - recipe input, or undefined for an omitted argument.
4304
4638
  * @param prefix - Decoded variants of the enclosing keys, each ending in `:`.
4305
4639
  */
4306
- #cvaInput(source, node, prefix) {
4640
+ #recipeInput(source, node, prefix) {
4307
4641
  while (node && (ts.isParenthesizedExpression(node) || ts.isAsExpression(node) || ts.isSatisfiesExpression(node))) node = node.expression;
4308
4642
  if (!node) return;
4309
4643
  if (ts.isArrayLiteralExpression(node)) {
4310
- for (const element of node.elements) this.#cvaInput(source, element, prefix);
4644
+ for (const element of node.elements) this.#recipeInput(source, element, prefix);
4311
4645
  return;
4312
4646
  }
4313
4647
  if (ts.isObjectLiteralExpression(node)) for (const property of node.properties) {
4314
4648
  if (!ts.isPropertyAssignment(property) || ts.isComputedPropertyName(property.name)) continue;
4315
4649
  this.#key(source, property, prefix, "utility");
4316
4650
  const name = propertyName(property);
4317
- if (name === "" || name.endsWith(":")) this.#cvaInput(source, property.initializer, name === ":" ? prefix : prefix + name);
4651
+ if (name === "" || name.endsWith(":")) this.#recipeInput(source, property.initializer, name === ":" ? prefix : prefix + name);
4318
4652
  }
4319
4653
  }
4320
4654
  /**
@@ -4561,7 +4895,7 @@ var SourceQueries = class {
4561
4895
  const candidates = this.#resolved.get(request.candidate) ?? this.#candidates;
4562
4896
  const current = literal && request.snapshot === this.#revision;
4563
4897
  const css = current ? request.candidate.endsWith(":") ? candidates.variant(request.candidate, literal.context) : this.#preview(literal, request.candidate.slice(literal.prefix.length)) ?? candidates.preview(request.candidate, literal.context) : void 0;
4564
- const marker = current ? candidates.marker(request.candidate, literal.context) : null;
4898
+ const marker = current && !literal.site?.native.enclosingVariant ? candidates.marker(request.candidate, literal.context) : null;
4565
4899
  if (css || marker) {
4566
4900
  const formatted = css ? this.#query.formatCss(css, this.#annotations) : "";
4567
4901
  result.hover = {
@@ -4575,7 +4909,7 @@ var SourceQueries = class {
4575
4909
  return result;
4576
4910
  }
4577
4911
  if (request.kind === "previews") {
4578
- result.previews = this.#index.previews.sites(source).filter((site) => site.native.kind !== "input" && site.native.kind !== "variant").flatMap((site) => {
4912
+ result.previews = this.#index.previews.sites(source).filter((site) => site.native.kind !== "input" && site.native.kind !== "variant" && site.native.kind !== "media" && site.native.kind !== "ref").flatMap((site) => {
4579
4913
  const preview = this.#index.previews.assemble(site.native);
4580
4914
  const range = {
4581
4915
  start: site.start,
@@ -4635,7 +4969,7 @@ var SourceQueries = class {
4635
4969
  if (token) {
4636
4970
  const candidate = token.literal.prefix + token.text;
4637
4971
  const css = token.literal.key ? this.#candidates.variant(candidate, token.literal.context) : this.#preview(token.literal, token.text, token.site);
4638
- const marker = token.literal.key ? null : this.#candidates.marker(candidate, token.literal.context);
4972
+ const marker = token.literal.key || token.site?.native.enclosingVariant ? null : this.#candidates.marker(candidate, token.literal.context);
4639
4973
  if (css || marker) result.hover = {
4640
4974
  start: token.start,
4641
4975
  end: token.end,
@@ -4648,15 +4982,20 @@ var SourceQueries = class {
4648
4982
  const input = this.#completionInput(source, request.offset);
4649
4983
  if (!input) return result;
4650
4984
  const { literal, start, end, prefix } = input;
4651
- const native = this.#candidates.complete(literal.prefix + prefix, literal.context, request.snippets === true).filter(({ label, marker }) => literal.key ? !marker && label.endsWith(":") : marker || label.endsWith(":") || !literal.site || this.#preview(literal, label.slice(literal.prefix.length)));
4985
+ const native = this.#candidates.complete(literal.prefix + prefix, literal.context, request.snippets === true).filter(({ label, marker }) => literal.key ? !marker && label.endsWith(":") : marker && !literal.site?.native.enclosingVariant || label.endsWith(":") || !literal.site || this.#preview(literal, label.slice(literal.prefix.length)));
4652
4986
  const known = new Set(native.map(({ label }) => label));
4653
- const catalog = literal.key ? [] : this.#catalogCompletions(literal.prefix + prefix, literal.context);
4987
+ const { names: catalog, incomplete } = literal.key ? {
4988
+ names: [],
4989
+ incomplete: false
4990
+ } : this.#catalogCompletions(literal.prefix + prefix, literal.context);
4991
+ if (incomplete) result.completionsIncomplete = true;
4654
4992
  result.completions = [...native, ...catalog.filter((candidate) => !known.has(candidate)).map((label) => ({
4655
4993
  label,
4656
4994
  marker: false
4657
4995
  }))].map(({ label: candidate, marker }) => {
4658
4996
  const label = candidate.slice(literal.prefix.length);
4659
4997
  const source = (text) => escapeContent(text, literal);
4998
+ const color = marker || candidate.endsWith(":") ? void 0 : this.#color(candidate);
4660
4999
  return {
4661
5000
  label,
4662
5001
  candidate,
@@ -4666,6 +5005,7 @@ var SourceQueries = class {
4666
5005
  end,
4667
5006
  newText: escapeContent(label, literal),
4668
5007
  ...marker ? { marker } : {},
5008
+ ...color ? { color } : {},
4669
5009
  snippet: !request.snippets ? void 0 : marker && candidate.endsWith("/") ? markerModifierSnippet(label, source) : candidate.endsWith(":") ? completionSnippet(label, source) : void 0,
4670
5010
  retrigger: candidate.endsWith(":") || candidate.endsWith("-")
4671
5011
  };
@@ -4689,34 +5029,169 @@ var SourceQueries = class {
4689
5029
  let reference;
4690
5030
  while (node) {
4691
5031
  const site = this.#index.previewSite(source, node);
4692
- if (site) {
5032
+ if (site && (!reference || site.native.kind === "use")) {
4693
5033
  const preview = this.#index.previews.preview(site.native);
4694
5034
  const range = this.#index.range(source, node);
4695
- return preview && range ? {
4696
- start: range[0],
4697
- end: range[1],
4698
- css: this.#query.formatCss(preview.css, this.#annotations),
4699
- ...preview.runtimeNames.length ? { runtimeNames: preview.runtimeNames } : {}
4700
- } : void 0;
5035
+ return preview && range ? this.#formatExpressionPreview(preview, range) : void 0;
5036
+ }
5037
+ if (ts.isCallExpression(node)) {
5038
+ const recipeCall = this.#recipeCallPreview(source, node);
5039
+ const range = this.#index.range(source, node);
5040
+ if (recipeCall && range) return this.#formatExpressionPreview(recipeCall, range);
5041
+ break;
4701
5042
  }
4702
5043
  if (!reference) {
4703
5044
  const asset = this.#index.asset(source, node);
4704
- const preview = asset && this.#index.previews.previewIdentity(asset.identity);
5045
+ let preview = asset && this.#index.previews.previewIdentity(asset.identity);
5046
+ if (!preview) {
5047
+ const init = this.#index.initializer(source, node);
5048
+ if (init) {
5049
+ if (ts.isCallExpression(init.node)) preview = this.#recipeCallPreview(init.source, init.node);
5050
+ if (!preview) {
5051
+ const initSite = this.#index.previewSite(init.source, init.node);
5052
+ if (initSite) preview = this.#index.previews.preview(initSite.native);
5053
+ else {
5054
+ const initRange = this.#index.range(init.source, init.node);
5055
+ const variantSite = initRange && this.#index.previews.sites(init.source).find((site) => site.native.kind === "variant" && initRange[0] <= site.start && site.end <= initRange[1]);
5056
+ preview = variantSite && this.#index.previews.preview(variantSite.native);
5057
+ }
5058
+ }
5059
+ }
5060
+ }
5061
+ if (!preview) {
5062
+ const subtree = this.#subtreePreview(source, node);
5063
+ if (subtree) return this.#formatExpressionPreview(subtree.preview, subtree.range);
5064
+ }
4705
5065
  const range = this.#index.range(source, node);
4706
5066
  if (preview && range) reference = {
4707
5067
  preview,
4708
5068
  range
4709
5069
  };
4710
5070
  }
4711
- if (ts.isCallExpression(node)) break;
4712
5071
  node = node.parent;
4713
5072
  }
4714
- return reference ? {
4715
- start: reference.range[0],
4716
- end: reference.range[1],
4717
- css: this.#query.formatCss(reference.preview.css, this.#annotations),
4718
- ...reference.preview.runtimeNames.length ? { runtimeNames: reference.preview.runtimeNames } : {}
4719
- } : void 0;
5073
+ return reference ? this.#formatExpressionPreview(reference.preview, reference.range) : void 0;
5074
+ }
5075
+ /**
5076
+ * Filters a `recipe({ ... })` call to the values selected by its static arguments and
5077
+ * `defaultVariants`. Dynamic axes retain all their options; a spread or non-literal
5078
+ * argument falls back to the complete recipe preview.
5079
+ *
5080
+ * @param source - Prepared source containing `node`.
5081
+ * @param node - Call expression that may invoke a `style.recipe()` factory.
5082
+ * @returns Assembled preview for matching recipe values, or undefined if `node` is not a
5083
+ * recipe call.
5084
+ */
5085
+ #recipeCallPreview(source, node) {
5086
+ const init = this.#index.initializer(source, node.expression);
5087
+ const initSite = init && this.#index.previewSite(init.source, init.node);
5088
+ const recipe = initSite?.native.recipe;
5089
+ if (!recipe) return;
5090
+ const arg = node.arguments[0];
5091
+ const selected = /* @__PURE__ */ new Map();
5092
+ const dynamic = /* @__PURE__ */ new Set();
5093
+ if (arg && !(ts.isIdentifier(arg) && arg.text === "undefined")) {
5094
+ if (!ts.isObjectLiteralExpression(arg)) return this.#index.previews.preview(initSite.native);
5095
+ for (const property of arg.properties) {
5096
+ if (ts.isSpreadAssignment(property)) return this.#index.previews.preview(initSite.native);
5097
+ if (ts.isShorthandPropertyAssignment(property)) {
5098
+ dynamic.add(property.name.text);
5099
+ continue;
5100
+ }
5101
+ if (!ts.isPropertyAssignment(property) || ts.isComputedPropertyName(property.name)) return this.#index.previews.preview(initSite.native);
5102
+ const axis = ts.isStringLiteralLike(property.name) ? property.name.text : ts.isNumericLiteral(property.name) || ts.isIdentifier(property.name) ? property.name.text : void 0;
5103
+ if (!axis) return this.#index.previews.preview(initSite.native);
5104
+ const option = this.#staticRecipeOption(property.initializer);
5105
+ if (!option) dynamic.add(axis);
5106
+ else selected.set(axis, option.value);
5107
+ }
5108
+ }
5109
+ for (const { axis, value } of recipe.defaultVariants) if (!selected.has(axis) && !dynamic.has(axis)) selected.set(axis, value);
5110
+ const matching = recipe.values.filter((entry) => entry.conditions.every(({ axis, values }) => {
5111
+ if (dynamic.has(axis)) return true;
5112
+ const chosen = selected.get(axis);
5113
+ return chosen !== void 0 && values.includes(chosen);
5114
+ })).map((entry) => entry.identity);
5115
+ return this.#index.previews.previewIdentities(matching);
5116
+ }
5117
+ /**
5118
+ * Decodes a static recipe option literal (`string`, `boolean`, `number`, `null`, or
5119
+ * `undefined`), or returns `undefined` for runtime expressions.
5120
+ *
5121
+ * @param expr - Initializer expression of a recipe call option.
5122
+ * @returns Normalized option key wrapped in an object (`value: undefined` for nullish
5123
+ * literals), or `undefined` when the expression is dynamic.
5124
+ */
5125
+ #staticRecipeOption(expr) {
5126
+ const inner = ts.isParenthesizedExpression(expr) ? expr.expression : expr;
5127
+ if (ts.isStringLiteralLike(inner)) return { value: inner.text };
5128
+ if (ts.isNumericLiteral(inner)) return { value: String(Number(inner.text)) };
5129
+ if (inner.kind === ts.SyntaxKind.TrueKeyword) return { value: "true" };
5130
+ if (inner.kind === ts.SyntaxKind.FalseKeyword) return { value: "false" };
5131
+ if (inner.kind === ts.SyntaxKind.NullKeyword || ts.isIdentifier(inner) && inner.text === "undefined") return { value: void 0 };
5132
+ }
5133
+ /**
5134
+ * Assembles a scoped preview for a compound sub-expression inside a style or keyframes
5135
+ * call (such as `active && [...]`, `active ? a : b`, `{ "hover:": [...] }`, or a
5136
+ * keyframe frame property) by combining the captured input and use sites it contains.
5137
+ *
5138
+ * @param source - Prepared source containing `node`.
5139
+ * @param node - Candidate AST node during ancestor traversal.
5140
+ * @returns Combined preview and original UTF-16 range, or undefined when `node` is not a
5141
+ * compound sub-expression with captured inner sites.
5142
+ */
5143
+ #subtreePreview(source, node) {
5144
+ if (!(ts.isBinaryExpression(node) || ts.isConditionalExpression(node) || ts.isElementAccessExpression(node) || ts.isArrayLiteralExpression(node) || ts.isObjectLiteralExpression(node) || ts.isPropertyAssignment(node))) return;
5145
+ if (ts.isCallExpression(node.parent) && node.parent.arguments.length === 1 && node.parent.arguments[0] === node && this.#index.previewSite(source, node.parent)) return;
5146
+ const range = this.#index.range(source, node);
5147
+ if (!range) return;
5148
+ const inner = this.#index.previews.sites(source).filter((site) => (site.native.kind === "input" || site.native.kind === "use") && range[0] <= site.start && site.end <= range[1]).sort((a, b) => a.start - b.start || a.end - b.end);
5149
+ if (!inner.length) return;
5150
+ const parts = [];
5151
+ const runtimeNames = /* @__PURE__ */ new Set();
5152
+ for (const site of inner) {
5153
+ const preview = this.#index.previews.preview(site.native);
5154
+ if (!preview) continue;
5155
+ if (preview.css) parts.push(preview.css);
5156
+ for (const name of preview.runtimeNames) runtimeNames.add(name);
5157
+ }
5158
+ const css = [...new Set(parts)].join("\n");
5159
+ if (!css) return;
5160
+ return {
5161
+ preview: {
5162
+ css,
5163
+ runtimeNames: [...runtimeNames]
5164
+ },
5165
+ range
5166
+ };
5167
+ }
5168
+ /**
5169
+ * Formats a resolved expression preview into an editor hover payload.
5170
+ *
5171
+ * @param preview - Assembled CSS or lowered JavaScript preview.
5172
+ * @param range - Inclusive start and exclusive end in original UTF-16 coordinates.
5173
+ * @returns Hover payload for CSS or JavaScript output.
5174
+ * @throws If the native formatter rejects the CSS preview.
5175
+ */
5176
+ #formatExpressionPreview(preview, range) {
5177
+ if (preview.js) return {
5178
+ start: range[0],
5179
+ end: range[1],
5180
+ css: "",
5181
+ documentation: `\`\`\`js\n${preview.js}\n\`\`\``
5182
+ };
5183
+ if (preview.documentation) return {
5184
+ start: range[0],
5185
+ end: range[1],
5186
+ css: "",
5187
+ documentation: preview.documentation
5188
+ };
5189
+ return {
5190
+ start: range[0],
5191
+ end: range[1],
5192
+ css: this.#query.formatCss(preview.css, this.#annotations),
5193
+ ...preview.runtimeNames.length ? { runtimeNames: preview.runtimeNames } : {}
5194
+ };
4720
5195
  }
4721
5196
  /**
4722
5197
  * Renders candidate text in a captured input plan or the standalone input registry.
@@ -4739,16 +5214,41 @@ var SourceQueries = class {
4739
5214
  *
4740
5215
  * @param text - Decoded partial candidate, including enclosing and written variants.
4741
5216
  * @param context - Input role of the literal. Only utility roles complete catalog names.
4742
- * @returns Candidates with the written variants, for names that start with the partial
4743
- * utility, at most {@link CATALOG_COMPLETIONS} of them in catalog order.
5217
+ * @returns `names`: candidates with the written variants, for names that start with the
5218
+ * partial utility, at most {@link CATALOG_COMPLETIONS} of them in catalog order. `incomplete`:
5219
+ * whether more names matched than `names` lists.
4744
5220
  */
4745
5221
  #catalogCompletions(text, context) {
4746
- if (!this.#catalogContext(context)) return [];
5222
+ if (!this.#catalogContext(context)) return {
5223
+ names: [],
5224
+ incomplete: false
5225
+ };
4747
5226
  const parts = segments(text, ":");
4748
5227
  const partial = parts.pop();
4749
- if (!partial) return [];
5228
+ if (!partial) return {
5229
+ names: [],
5230
+ incomplete: false
5231
+ };
4750
5232
  const variants = parts.map((part) => `${part}:`).join("");
4751
- return [.../* @__PURE__ */ new Set([...this.#catalog, ...this.#inputCatalogs.get(partial) ?? []])].filter((name) => name.startsWith(partial)).slice(0, CATALOG_COMPLETIONS).map((name) => variants + name);
5233
+ const matches = [.../* @__PURE__ */ new Set([...this.#catalog, ...this.#inputCatalogs.get(partial) ?? []])].filter((name) => name.startsWith(partial));
5234
+ return {
5235
+ names: matches.slice(0, CATALOG_COMPLETIONS).map((name) => variants + name),
5236
+ incomplete: matches.length > CATALOG_COMPLETIONS
5237
+ };
5238
+ }
5239
+ /**
5240
+ * Formats the concrete color of a color utility for a completion swatch.
5241
+ *
5242
+ * @param candidate - Full decoded candidate, including enclosing and written variants.
5243
+ * @returns `#rrggbb`, or `#rrggbbaa` below full opacity. Undefined for other candidates and for
5244
+ * colors that depend on the color scheme.
5245
+ * @throws If a matching utility definition has a malformed requirement.
5246
+ */
5247
+ #color(candidate) {
5248
+ const components = this.#candidates.color(candidate);
5249
+ if (!components) return;
5250
+ const [red, green, blue, alpha] = components.map((value) => Math.round(Math.min(1, Math.max(0, value)) * 255).toString(16).padStart(2, "0"));
5251
+ return `#${red}${green}${blue}${alpha === "ff" ? "" : alpha}`;
4752
5252
  }
4753
5253
  /**
4754
5254
  * Reports whether an input role completes plugin catalog names.
@@ -4854,7 +5354,7 @@ var SourceQueries = class {
4854
5354
  let reference = false;
4855
5355
  while (node && (ts.isIdentifier(node) || ts.isStringLiteralLike(node) || ts.isPropertyAccessExpression(node) || ts.isParenthesizedExpression(node) || ts.isTaggedTemplateExpression(node) || ts.isCallExpression(node) && !this.#index.styleCall(node))) {
4856
5356
  const callee = ts.isCallExpression(node) ? node.expression : ts.isTaggedTemplateExpression(node) ? node.tag : void 0;
4857
- if (callee && (this.#index.asset(source, callee)?.identity.kind === "ref" || ts.isPropertyAccessExpression(callee) && ["at", "in"].includes(callee.name.text))) reference = true;
5357
+ if (callee && this.#refCallee(source, callee)) reference = true;
4858
5358
  expression = node;
4859
5359
  node = node.parent;
4860
5360
  }
@@ -4868,6 +5368,25 @@ var SourceQueries = class {
4868
5368
  css: this.#query.formatCss(preview.css, this.#annotations)
4869
5369
  } : void 0;
4870
5370
  }
5371
+ /**
5372
+ * Reports whether `callee` calls a ref asset directly or through `.at()` / `.in()` chains.
5373
+ *
5374
+ * @param source - Prepared source stored in this snapshot's index.
5375
+ * @param callee - Call target or template tag to inspect.
5376
+ * @returns Whether the root receiver resolves to a `ref` asset.
5377
+ */
5378
+ #refCallee(source, callee) {
5379
+ while (ts.isParenthesizedExpression(callee)) callee = callee.expression;
5380
+ if (this.#index.asset(source, callee)?.identity.kind === "ref") return true;
5381
+ if (ts.isPropertyAccessExpression(callee) && ["at", "in"].includes(callee.name.text)) {
5382
+ let receiver = callee.expression;
5383
+ while (ts.isParenthesizedExpression(receiver)) receiver = receiver.expression;
5384
+ if (ts.isCallExpression(receiver)) return this.#refCallee(source, receiver.expression);
5385
+ if (ts.isTaggedTemplateExpression(receiver)) return this.#refCallee(source, receiver.tag);
5386
+ return this.#index.asset(source, receiver)?.identity.kind === "ref";
5387
+ }
5388
+ return false;
5389
+ }
4871
5390
  };
4872
5391
  // src/editor/snapshot.ts
4873
5392
  /**
@@ -5274,7 +5793,7 @@ var StylesheetEditor = class {
5274
5793
  async prepare(id, request) {
5275
5794
  if (id !== this.#id) return;
5276
5795
  if (this.#plugins && (request.kind === "completion" || request.kind === "resolve" && request.snapshot === this.#completionSnapshot(request.registryDirectives, request.snippets))) {
5277
- const input = catalogInput(this.#text.slice(0, request.kind === "completion" ? request.offset : request.input));
5796
+ const input = this.#catalogInput(request.kind === "completion" ? request.offset : request.input);
5278
5797
  if (input && !this.#inputCatalogs.has(input)) this.#inputCatalogs.set(input, await this.#plugins.catalog(input));
5279
5798
  }
5280
5799
  if (request.kind === "resolve" && request.snapshot === this.#completionSnapshot(request.registryDirectives, request.snippets) && this.#plugins && !this.#resolved.has(request.candidate)) {
@@ -5427,10 +5946,20 @@ var StylesheetEditor = class {
5427
5946
  * for the candidate's input, without duplicates.
5428
5947
  */
5429
5948
  #catalogAt(offset) {
5430
- const input = catalogInput(this.#text.slice(0, offset));
5949
+ const input = this.#catalogInput(offset);
5431
5950
  return [.../* @__PURE__ */ new Set([...this.#catalog, ...this.#inputCatalogs.get(input) ?? []])];
5432
5951
  }
5433
5952
  /**
5953
+ * Returns the text that a plugin catalog completes at a cursor.
5954
+ *
5955
+ * @param offset - UTF-16 character boundary within the captured text.
5956
+ * @returns The `@apply` candidate or applied `@variant` sequence before the cursor without its
5957
+ * variants, or an empty string at other positions.
5958
+ */
5959
+ #catalogInput(offset) {
5960
+ return stylesheetCatalogInput(this.#text, this.#byteOffset(offset)) ?? "";
5961
+ }
5962
+ /**
5434
5963
  * Converts a cursor in the original buffer to the native query's byte coordinates.
5435
5964
  *
5436
5965
  * @param offset - UTF-16 character boundary within the captured text.
@@ -5462,7 +5991,7 @@ var StylesheetEditor = class {
5462
5991
  const bytes = encoder.encode(text);
5463
5992
  const hover = query.hoverStylesheet(text, encoder.encode(text.slice(0, offset)).length);
5464
5993
  if (!hover) return;
5465
- const css = hover.css.startsWith("--") ? hover.css : hover.css ? this.#query.formatCss(hover.css, this.#preview) : "";
5994
+ const css = hover.css.startsWith("--") ? this.#query.annotatePreview(hover.css, this.#preview) : hover.css ? this.#query.formatCss(hover.css, this.#preview) : "";
5466
5995
  const decoder = new TextDecoder();
5467
5996
  return {
5468
5997
  start: decoder.decode(bytes.subarray(0, hover.start)).length,
@@ -5516,6 +6045,6 @@ function compilerOptions(config) {
5516
6045
  rootFontSize: resolved.rootFontSize
5517
6046
  };
5518
6047
  }
5519
- export { fileSourceKind as A, CompilationFailure as C, ResolutionMismatchError as D, CompilationProject as E, prepareSourcePlugins as F, attachPlugins as M, compileWithPlugins as N, sourceKey as O, pluginLoader as P, warnRejectedNames as S, tracePhase as T, defaultPluginExport as _, pluginDirectory as a, analyzeModule as b, CheckerSource as c, queryDesignSystem as d, isStylesheet as f, PluginRuntime as g, loadEditorCssGraph as h, completePluginPaths as i, TypeFactsError as j, cleanModuleId as k, checkerId as l, loadCssGraph as m, cssEntrypoint as n, queryPluginPaths as o, lintsStylesheet as p, StylesheetEditor as r, EditorSnapshot as s, compilerOptions as t, withRequestedProbes as u, cssBannerPrefix as v, startPhase as w, compileModule as x, finalizeCss as y };
6048
+ export { cleanModuleId as A, CompilationFailure as C, CompilationProject as D, tracePhase as E, pluginLoader as F, prepareSourcePlugins as I, TypeFactsError as M, attachPlugins as N, ResolutionMismatchError as O, compileWithPlugins as P, warnRejectedNames as S, startPhase as T, defaultPluginExport as _, pluginDirectory as a, analyzeModule as b, CheckerSource as c, queryDesignSystem as d, isStylesheet as f, PluginRuntime as g, loadEditorCssGraph as h, completePluginPaths as i, fileSourceKind as j, sourceKey as k, checkerId as l, loadCssGraph as m, cssEntrypoint as n, queryPluginPaths as o, lintsStylesheet as p, StylesheetEditor as r, EditorSnapshot as s, compilerOptions as t, withRequestedProbes as u, cssBannerPrefix as v, formatReport as w, compileModule as x, finalizeCss as y };
5520
6049
 
5521
- //# sourceMappingURL=options-CA4ymTHc.js.map
6050
+ //# sourceMappingURL=options-B0m3Ajj9.js.map