@stillwind/host 0.0.0-stage → 0.1.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,4770 @@
1
+ import { NativeDesignSystemLoader, completionDetail, editorCssSource, fingerprint, stylesheetPluginPaths } from "@stillwind/native";
2
+ import { PreparationError, checkerEnvironment, prepareSource } from "@stillwind/projection";
3
+ import { TraceMap, decodedMappings } from "@jridgewell/trace-mapping";
4
+ import ts from "typescript-6";
5
+ import * as path from "pathe";
6
+ import { dirname, isAbsolute, join, relative, resolve } from "pathe";
7
+ import { lintRules, normalizeCompilerConfig } from "@stillwind/config";
8
+ // src/css/plugins/session.ts
9
+ /** Runtimes of sessions whose design systems load plugins with dynamic families. */
10
+ const sessions = /* @__PURE__ */ new WeakMap();
11
+ /**
12
+ * Associates a session with the plugin runtime of the CSS graph that it was created or reloaded
13
+ * from, so that compilation can define dynamic candidates.
14
+ *
15
+ * @param session - Native session.
16
+ * @param runtime - Runtime returned with the graph, or undefined to detach.
17
+ * @param generation - Definition generation of the loader that the session uses. Defaults to
18
+ * zero, the generation of the graph's original loader.
19
+ */
20
+ function attachPlugins(session, runtime, generation = 0) {
21
+ if (runtime?.dynamic) sessions.set(session, {
22
+ runtime,
23
+ generation
24
+ });
25
+ else sessions.delete(session);
26
+ }
27
+ /**
28
+ * Compiles with the definitions of the attached plugins, and defines the dynamic candidates that
29
+ * the compilation reports.
30
+ *
31
+ * A session whose design system lacks definitions that the runtime added later is reloaded
32
+ * first. After each compilation, new candidates go to the plugins, and when they return CSS the
33
+ * session is reloaded and `compile` runs again, at most `rounds` more times. A session without
34
+ * plugins runs `compile` once.
35
+ *
36
+ * @param session - Native session whose output `compile` returns.
37
+ * @param compile - Compiles the graph into the session and returns its module outputs.
38
+ * @param rounds - Most reloads after the first compilation.
39
+ * @returns The output of the last compilation.
40
+ * @throws If a plugin, a reload, or `compile` fails.
41
+ */
42
+ async function compileWithPlugins(session, compile, rounds) {
43
+ const binding = sessions.get(session);
44
+ if (!binding) return compile();
45
+ /** Reloads the session with the runtime's current definitions. */
46
+ const sync = () => {
47
+ const loader = binding.runtime.replay(session, true);
48
+ session.reload(loader);
49
+ binding.generation = binding.runtime.generation;
50
+ binding.loader = loader;
51
+ };
52
+ if (binding.generation < binding.runtime.generation) sync();
53
+ let output = compile();
54
+ for (let round = 0; round < rounds; round++) {
55
+ const candidates = output.modules.flatMap((module) => module.dynamicCandidates);
56
+ if (!await binding.runtime.resolve(candidates)) break;
57
+ sync();
58
+ output = compile();
59
+ }
60
+ return output;
61
+ }
62
+ /**
63
+ * Returns the loader whose design system a session uses after plugin definitions were added.
64
+ *
65
+ * @param session - Native session.
66
+ * @returns The loader of the last reload with definitions, or undefined when the session still
67
+ * uses the loader that it was created or attached with.
68
+ */
69
+ function pluginLoader(session) {
70
+ return sessions.get(session)?.loader;
71
+ }
72
+ /**
73
+ * Finds plugin candidates across source texts before individual modules are compiled.
74
+ *
75
+ * @param session - Session attached to the project's plugin runtime.
76
+ * @param loader - Initial loader of the same session.
77
+ * @param texts - Original source documents, including templates and embedded scripts.
78
+ * @returns Completion of candidate resolution and any required CSS reload, without publishing modules.
79
+ * @throws If a plugin or CSS reload fails. Discard this runtime before retrying individual modules.
80
+ */
81
+ async function prepareSourcePlugins(session, loader, texts) {
82
+ if (!sessions.has(session)) return;
83
+ await compileWithPlugins(session, () => {
84
+ const query = (pluginLoader(session) ?? loader).editorQuery();
85
+ return { modules: [{ dynamicCandidates: [...new Set(texts.flatMap((text) => query.dynamicCandidates(text)))] }] };
86
+ }, 1);
87
+ }
88
+ // src/compilation/host.ts
89
+ /**
90
+ * Loads original or prepared source through the host, reading its descriptor once.
91
+ *
92
+ * @param host - Host whose current buffers supply this source.
93
+ * @param id - Full resolver identity. The host must preserve this identity in its answer.
94
+ * @returns Prepared source from load, or an original input assembled from describe and read.
95
+ * @throws If loading, describing, or reading the source fails.
96
+ */
97
+ async function loadSource(host, id) {
98
+ if (host.load) return host.load(id);
99
+ const descriptor = host.describe(id);
100
+ return {
101
+ resolverId: id,
102
+ ...descriptor,
103
+ document: {
104
+ ...descriptor.document,
105
+ code: await host.read(id)
106
+ }
107
+ };
108
+ }
109
+ // src/semantics/backend.ts
110
+ /**
111
+ * Failure to map, validate, or recover declaration identities for one source. The compiler turns
112
+ * this error into a source report using its original-coordinate range.
113
+ */
114
+ var TypeFactsError = class extends Error {
115
+ /** Compiler module identity used to locate the original prepared source. */
116
+ moduleId;
117
+ /**
118
+ * Inclusive original UTF-8 byte offset when the checker can identify it. Omission permits a
119
+ * document-scoped report.
120
+ */
121
+ start;
122
+ /**
123
+ * Exclusive original UTF-8 byte offset when known. The compiler uses a source range only when
124
+ * both endpoints are present.
125
+ */
126
+ end;
127
+ /** Issue category and detail passed to native source-failure reporting. */
128
+ issue;
129
+ /**
130
+ * Records a checker contract failure in original source coordinates.
131
+ *
132
+ * @param moduleId - Compiler identity of the affected source.
133
+ * @param start - Optional inclusive original UTF-8 byte offset.
134
+ * @param end - Optional exclusive original UTF-8 byte offset.
135
+ * @param kind - Native issue category, such as checker mapping, assignment, or identity
136
+ * resolution.
137
+ * @param detail - Error message also stored as the issue detail.
138
+ */
139
+ constructor(moduleId, start, end, kind, detail) {
140
+ super(detail);
141
+ this.moduleId = moduleId;
142
+ this.start = start;
143
+ this.end = end;
144
+ this.issue = {
145
+ kind,
146
+ detail
147
+ };
148
+ }
149
+ };
150
+ // src/compilation/module-source.ts
151
+ const formatsByExtension = {
152
+ ".jsx": "jsx",
153
+ ".tsx": "jsx",
154
+ ".astro": "astro",
155
+ ".svelte": "svelte",
156
+ ".vue": "vue"
157
+ };
158
+ const languagesByExtension = {
159
+ ".ts": "ts",
160
+ ".cts": "ts",
161
+ ".mts": "ts",
162
+ ".tsx": "tsx",
163
+ ".jsx": "jsx"
164
+ };
165
+ /**
166
+ * Infers the source format and parser language from a module path.
167
+ *
168
+ * @param id - Source identity whose query or fragment is removed before case-insensitive extension
169
+ * matching.
170
+ * @returns Parser settings with unambiguous module kind and the inferred source format. TypeScript
171
+ * and JSX extensions choose their parser languages. Declaration files use `dts`, and SFC
172
+ * extensions select projected formats. Unrecognized extensions default to JavaScript script input.
173
+ */
174
+ function fileSourceKind(id) {
175
+ const name = cleanModuleId(id).toLowerCase();
176
+ const extension = /\.[^.]+$/.exec(name)?.[0];
177
+ const format = formatsByExtension[extension ?? ""] ?? "script";
178
+ return {
179
+ syntax: {
180
+ language: /\.d\.[cm]?ts$/.test(name) ? "dts" : languagesByExtension[extension ?? ""] ?? "js",
181
+ moduleKind: "unambiguous"
182
+ },
183
+ format
184
+ };
185
+ }
186
+ /**
187
+ * Removes a filesystem identity's query or fragment before a disk operation.
188
+ *
189
+ * @param id - Resolver identity, including any query or fragment suffix.
190
+ * @returns The identity up to its first `?` or `#`. IDs beginning with NUL or `virtual:` are
191
+ * returned unchanged.
192
+ */
193
+ function cleanModuleId(id) {
194
+ if (id.startsWith("\0") || id.startsWith("virtual:")) return id;
195
+ return id.split(/[?#]/, 1)[0];
196
+ }
197
+ /**
198
+ * Converts an original UTF-8 byte boundary to a UTF-16 offset for slicing JavaScript text.
199
+ *
200
+ * @param text - Original document text.
201
+ * @param offset - Integer byte offset from zero through the UTF-8 byte length, at a character
202
+ * boundary.
203
+ * @returns Length of the text before that boundary in UTF-16 code units.
204
+ * @throws If the offset is negative, exceeds the byte length, or points into a UTF-8 continuation
205
+ * byte.
206
+ */
207
+ function byteToUtf16(text, offset) {
208
+ const bytes = new TextEncoder().encode(text);
209
+ if (offset < 0 || offset > bytes.length || offset < bytes.length && (bytes[offset] & 192) === 128) throw new Error("Invalid original UTF-8 boundary");
210
+ return new TextDecoder().decode(bytes.subarray(0, offset)).length;
211
+ }
212
+ // src/compilation/module-graph.ts
213
+ /**
214
+ * Compilation failure carrying diagnostic batches for the same report format used by collect mode.
215
+ * Its message renders those reports with source locations.
216
+ */
217
+ var CompilationFailure = class extends Error {
218
+ /**
219
+ * Report batches grouped by compiler module identity. The supplied array is retained without
220
+ * copying.
221
+ */
222
+ batches;
223
+ /**
224
+ * Builds an error message from the supplied reports and preserves an optional cause.
225
+ *
226
+ * @param batches - Reports to retain, in message order.
227
+ * @param cause - Optional preparation or checker failure that produced these reports.
228
+ */
229
+ constructor(batches, cause) {
230
+ super(batches.flatMap((batch) => batch.reports).map(formatReport).join("\n"), { cause });
231
+ this.batches = batches;
232
+ }
233
+ };
234
+ /**
235
+ * Formats a compiler report for an Error message or terminal output.
236
+ *
237
+ * @param report - Structured report with a primary label, related labels, and notes.
238
+ * @returns Text with one-based line and column ranges for source labels, followed by related labels
239
+ * and notes. Document-scoped primary labels use only the URI.
240
+ */
241
+ function formatReport(report) {
242
+ const { location, scope } = report.primary;
243
+ const at = scope === "document" ? location.uri : `${location.uri}:${location.startLine + 1}:${location.startColumn + 1}-${location.endLine + 1}:${location.endColumn + 1}`;
244
+ const related = report.related.map((label) => {
245
+ const loc = label.location;
246
+ return ` ${label.scope === "document" ? loc.uri : `${loc.uri}:${loc.startLine + 1}:${loc.startColumn + 1}`}${label.message ? `: ${label.message}` : ""}`;
247
+ });
248
+ return [
249
+ `${at}: ${report.code}: ${report.message}`,
250
+ ...related,
251
+ ...report.notes.map((note) => ` ${note}`)
252
+ ].join("\n");
253
+ }
254
+ /** Collects prepared sources and semantic facts for one entry's demanded dependency graph. */
255
+ var ModuleGraph = class {
256
+ session;
257
+ factsService;
258
+ host;
259
+ options;
260
+ analysis;
261
+ project;
262
+ /** Prepared sources keyed by compiler identity, including sources that later fail scanning. */
263
+ #attempted = /* @__PURE__ */ new Map();
264
+ /** Successful scanner summaries keyed by compiler identity. */
265
+ #summaries = /* @__PURE__ */ new Map();
266
+ /** Sources retained for compilation, keyed by full host identity. */
267
+ #sources = /* @__PURE__ */ new Map();
268
+ /** Correspondence from compiler identities to full host resolver identities. */
269
+ #resolverIds = /* @__PURE__ */ new Map();
270
+ /** Observed import resolutions keyed by importing resolver identity and authored specifier. */
271
+ #resolutions = /* @__PURE__ */ new Map();
272
+ /** Whether entry probes require semantic traversal and checker collection. */
273
+ #needsTypeFacts = false;
274
+ /** Only this project revision may store scan results or install shared checker inputs. */
275
+ #projectRevision;
276
+ /**
277
+ * Uses a caller-owned session, host, and lazy semantic backend for one entry.
278
+ * Supplying `analysis` retains unavailable dependencies and partial facts in that result.
279
+ * Omitting it keeps checker and dependency failures strict.
280
+ *
281
+ * @param session - Initialized native session. The caller retains ownership.
282
+ * @param factsService - Lazy backend for checker queries, or undefined when unavailable.
283
+ * @param host - Stable source descriptors, loading, and resolver operations for this graph.
284
+ * @param options - Diagnostic policy and captured checker inputs for one compilation.
285
+ * @param analysis - Optional result object to populate with observed sources, dependencies,
286
+ * reports, and unavailable ranges.
287
+ * @param project - Optional prepared inputs shared across scoped graphs of the same project.
288
+ */
289
+ constructor(session, factsService, host, options, analysis, project) {
290
+ this.session = session;
291
+ this.factsService = factsService;
292
+ this.host = host;
293
+ this.options = options;
294
+ this.analysis = analysis;
295
+ this.project = project;
296
+ this.#projectRevision = project?.revision;
297
+ }
298
+ /**
299
+ * Prepares source and retains it for report mapping, even if a later scan fails.
300
+ *
301
+ * @param input - Original or already prepared source. Preparation must preserve resolverId.
302
+ * @returns Prepared source. onModule runs before preparation and does not imply success.
303
+ * @throws If preparation fails or changes the resolver identity. PreparationError becomes CompilationFailure.
304
+ */
305
+ async prepare(input) {
306
+ this.host.onModule?.(input.moduleId, input.resolverId);
307
+ try {
308
+ const source = this.project?.source(input.resolverId) ?? ("kind" in input ? input : await prepareSource(input));
309
+ if (source.resolverId !== input.resolverId) throw new Error(`Host changed resolver identity for ${input.resolverId}`);
310
+ this.#attempted.set(source.moduleId, source);
311
+ this.analysis?.sources.push(source);
312
+ return source;
313
+ } catch (error) {
314
+ if (error instanceof PreparationError) throw this.#preparationFailure(input, error);
315
+ throw error;
316
+ }
317
+ }
318
+ /**
319
+ * Scans a prepared source without registering it in dependency traversal.
320
+ *
321
+ * @param source - Source with validated original document and projection correspondences.
322
+ * @returns Native summary of imports, declarations, and semantic probes.
323
+ * @throws CompilationFailure when scanning returns source diagnostics.
324
+ */
325
+ scan(source) {
326
+ const cached = this.project?.summary(source);
327
+ if (cached) return cached;
328
+ const result = this.session.scanSource(source);
329
+ if (result.kind === "failed") throw new CompilationFailure([result.batch]);
330
+ this.project?.retain(source, result.summary, this.#projectRevision);
331
+ return result.summary;
332
+ }
333
+ /**
334
+ * Looks up a summary retained during dependency traversal.
335
+ *
336
+ * @param moduleId - Compiler identity of the source.
337
+ * @returns Its cached summary, or undefined when traversal did not retain one.
338
+ */
339
+ summary(moduleId) {
340
+ return this.#summaries.get(moduleId);
341
+ }
342
+ /**
343
+ * Finds the host identity registered for a compiler module.
344
+ *
345
+ * @param moduleId - Compiler identity registered by dependency collection.
346
+ * @returns Full resolver identity, including any query suffix.
347
+ * @throws If the compiler refers to an unregistered module.
348
+ */
349
+ resolverId(moduleId) {
350
+ const id = this.#resolverIds.get(moduleId);
351
+ if (id === void 0) throw new Error(`Stillwind returned an unknown module: ${moduleId}`);
352
+ return id;
353
+ }
354
+ /**
355
+ * Registers the entry and loads dependencies demanded by its semantic probes.
356
+ *
357
+ * @param entry - Prepared entry source.
358
+ * @param entrySummary - Successful scan of that entry, with the same module identity.
359
+ * @returns A promise that resolves after traversal. Analysis mode retains unresolved and
360
+ * unsupported dependencies rather than failing the whole graph.
361
+ * @throws If strict traversal fails or source identities conflict.
362
+ */
363
+ async collectDependencies(entry, entrySummary) {
364
+ this.#needsTypeFacts = entrySummary.typeProbes.length > 0;
365
+ this.#register(entry);
366
+ const visited = /* @__PURE__ */ new Map();
367
+ const pending = [{
368
+ source: entry,
369
+ requested: null
370
+ }];
371
+ while (pending.length > 0) {
372
+ const { source, requested } = pending.pop();
373
+ const demands = visited.get(source.resolverId) ?? /* @__PURE__ */ new Set();
374
+ if (demands.has(requested)) continue;
375
+ demands.add(requested);
376
+ visited.set(source.resolverId, demands);
377
+ const summary = this.#dependencySummary(source, entry, entrySummary);
378
+ if (!summary || !this.#needsTypeFacts) continue;
379
+ const semanticResolutions = await this.#semanticResolutions(source);
380
+ for (const dependency of semanticDependencies(summary, requested)) {
381
+ const next = await this.#followDependency(source, dependency.source, semanticResolutions?.get(dependency.source));
382
+ if (next) pending.push({
383
+ source: next,
384
+ requested: dependency.imported
385
+ });
386
+ }
387
+ }
388
+ }
389
+ /**
390
+ * Attaches semantic facts and CSS value imports to the retained graph sources.
391
+ *
392
+ * @param entry - Registered entry whose transport imports remain unchanged.
393
+ * @returns Copies of retained sources with native type facts. Analysis mode records unavailable
394
+ * queries, while strict compilation requires a backend when facts are needed.
395
+ * @throws If strict checker collection or a checker source contract fails.
396
+ */
397
+ async collectTypedSources(entry) {
398
+ const facts = await this.#collectFacts();
399
+ return [...this.#sources.values()].map((source) => ({
400
+ ...source,
401
+ moduleCssImport: source.resolverId === entry.resolverId ? source.moduleCssImport : "stillwind/module-css",
402
+ typeFacts: facts.get(source.moduleId) ?? []
403
+ }));
404
+ }
405
+ /**
406
+ * Converts a known checker failure to a report in original source coordinates.
407
+ *
408
+ * @param error - Failure caught during compilation.
409
+ * @returns CompilationFailure for TypeFactsError whose source was prepared, otherwise the input.
410
+ */
411
+ failure(error) {
412
+ if (!(error instanceof TypeFactsError)) return error;
413
+ const source = this.#attempted.get(error.moduleId);
414
+ if (!source) return error;
415
+ const range = error.start !== void 0 && error.end !== void 0 ? {
416
+ start: byteToUtf16(source.document.code, error.start),
417
+ end: byteToUtf16(source.document.code, error.end)
418
+ } : void 0;
419
+ return new CompilationFailure([this.session.reportSourceFailure({
420
+ moduleId: source.moduleId,
421
+ document: source.document,
422
+ issue: error.issue,
423
+ range,
424
+ converter: source.kind === "projected" ? source.projection.converter : void 0
425
+ })], error);
426
+ }
427
+ /**
428
+ * Registers the source and enforces one-to-one host and compiler identities within the graph.
429
+ *
430
+ * @param source - Prepared source to retain for traversal and compilation.
431
+ * @throws If a compiler identity is shared or a host identity changes its compiler identity.
432
+ */
433
+ #register(source) {
434
+ const previous = this.#resolverIds.get(source.moduleId);
435
+ if (previous !== void 0 && previous !== source.resolverId) throw new Error(`Module identity ${source.moduleId} is shared by ${previous} and ${source.resolverId}`);
436
+ const existing = this.#sources.get(source.resolverId);
437
+ if (existing !== void 0 && existing.moduleId !== source.moduleId) throw new Error(`Resolver identity ${source.resolverId} changed module identity`);
438
+ this.#resolverIds.set(source.moduleId, source.resolverId);
439
+ this.#sources.set(source.resolverId, source);
440
+ }
441
+ /**
442
+ * Converts a preparation error into an original-document diagnostic batch.
443
+ *
444
+ * @param input - Source whose document metadata identifies the failing preparation.
445
+ * @param error - Preparation issue with optional original UTF-16 range and converter identity.
446
+ * @returns A compilation failure retaining the preparation error as its cause.
447
+ */
448
+ #preparationFailure(input, error) {
449
+ return new CompilationFailure([this.session.reportSourceFailure({
450
+ moduleId: input.moduleId,
451
+ document: input.document,
452
+ issue: error.issue,
453
+ converter: error.converter,
454
+ range: error.range
455
+ })], error);
456
+ }
457
+ /**
458
+ * Reuses or scans a source summary and records dependency syntax failures in analysis mode.
459
+ *
460
+ * @param source - Registered dependency or entry source.
461
+ * @param entry - Entry source whose initial scan is already available.
462
+ * @param entrySummary - Summary with the entry's compiler identity.
463
+ * @returns A retained summary, or undefined after an analysis-mode scan failure removes the source.
464
+ * @throws If scanning fails in strict mode or a summary changes the source's compiler identity.
465
+ */
466
+ #dependencySummary(source, entry, entrySummary) {
467
+ let summary;
468
+ try {
469
+ summary = this.#summaries.get(source.moduleId) ?? (source.resolverId === entry.resolverId ? entrySummary : this.scan(source));
470
+ } catch (error) {
471
+ if (!this.analysis || !(error instanceof CompilationFailure)) throw error;
472
+ this.analysis.batches.push(...error.batches);
473
+ this.#sources.delete(source.resolverId);
474
+ for (const dependency of this.analysis.dependencies) if (dependency.id === source.resolverId) dependency.status = "unsupported";
475
+ return;
476
+ }
477
+ if (summary.moduleId !== source.moduleId) throw new Error(`Scanner changed module identity for ${source.resolverId}`);
478
+ this.#summaries.set(source.moduleId, summary);
479
+ return summary;
480
+ }
481
+ /**
482
+ * Attaches checker environments, scanner probes, and observed resolutions to retained sources.
483
+ *
484
+ * @returns Checker inputs in source registration order. Missing summaries are scanned and cached.
485
+ * @throws If scanning or checker preparation fails.
486
+ */
487
+ #checkerSources() {
488
+ return [...this.#sources.values()].map((source) => {
489
+ const summary = this.#summaries.get(source.moduleId) ?? this.scan(source);
490
+ this.#summaries.set(source.moduleId, summary);
491
+ let environment;
492
+ try {
493
+ environment = checkerEnvironment(source);
494
+ } catch (error) {
495
+ if (error instanceof PreparationError) throw this.#preparationFailure(source, error);
496
+ throw error;
497
+ }
498
+ return {
499
+ ...source,
500
+ ...environment,
501
+ checkerSpans: summary.checkerSpans,
502
+ checkerBindings: summary.checkerBindings,
503
+ probes: summary.typeProbes,
504
+ resolutions: summary.moduleSpecifiers.flatMap((specifier) => {
505
+ const id = this.#resolutions.get(source.resolverId)?.get(specifier.source);
506
+ return id ? [{
507
+ id,
508
+ start: specifier.start,
509
+ end: specifier.end
510
+ }] : [];
511
+ })
512
+ };
513
+ });
514
+ }
515
+ /**
516
+ * Collects declared assets for checker interpretation.
517
+ *
518
+ * @returns A new map from compiler identity to the corresponding scanner asset array.
519
+ */
520
+ #assets() {
521
+ return new Map([...this.#summaries].map(([id, summary]) => [id, summary.assets]));
522
+ }
523
+ /**
524
+ * Adds an unverified range for each retained probe when analysis mode has no usable facts.
525
+ *
526
+ * @param source - Source whose scanner probes use original UTF-8 byte coordinates.
527
+ * @param reason - Explanation included in every added range. Strict mode has no analysis to update.
528
+ */
529
+ #unavailable(source, reason) {
530
+ this.analysis?.unverified.push(...(this.#summaries.get(source.moduleId)?.typeProbes ?? []).map((probe) => ({
531
+ moduleId: source.moduleId,
532
+ start: probe.start,
533
+ end: probe.end,
534
+ reason
535
+ })));
536
+ }
537
+ /**
538
+ * Requests checker resolutions when the host enables them, recording failures as unverified probes.
539
+ *
540
+ * @param source - Importing source whose resolver identity selects the returned map.
541
+ * @returns Authored specifiers mapped to host identities, or undefined when disabled or unavailable.
542
+ * @throws If resolution fails outside analysis mode.
543
+ */
544
+ async #semanticResolutions(source) {
545
+ if (!this.host.typeFactsResolution) return;
546
+ try {
547
+ const backend = this.factsService();
548
+ if (backend && this.project && this.project.revision === this.#projectRevision) return (await this.project.resolve(backend, this.#checkerSources(), this.options.typeFactsInputs)).get(source.resolverId);
549
+ return (await backend?.resolveModules(this.#checkerSources(), this.#assets(), this.options.typeFactsInputs))?.get(source.resolverId);
550
+ } catch (error) {
551
+ if (!this.analysis) throw error;
552
+ this.#unavailable(source, String(error));
553
+ }
554
+ }
555
+ /**
556
+ * Resolves a demanded dependency, records its status, and loads supported source for traversal.
557
+ *
558
+ * @param source - Registered importing source.
559
+ * @param specifier - Authored module request.
560
+ * @param semanticId - Optional checker fallback used when the host returns no resolution.
561
+ * @returns Registered dependency source, or undefined for external, unresolved, or unsupported requests.
562
+ * @throws If strict loading fails. Analysis mode records loading failures and available diagnostics.
563
+ */
564
+ async #followDependency(source, specifier, semanticId) {
565
+ const resolved = await this.#resolveDependency(source, specifier, semanticId);
566
+ const observed = {
567
+ importer: source.resolverId,
568
+ specifier,
569
+ id: resolved?.id,
570
+ status: !resolved ? "unresolved" : resolved.external ? "external" : "resolved"
571
+ };
572
+ this.analysis?.dependencies.push(observed);
573
+ if (!resolved || resolved.external) return;
574
+ const id = this.project?.source(resolved.id)?.resolverId ?? resolved.id;
575
+ observed.id = id;
576
+ if (!this.#canLoadDependency(id, observed)) return;
577
+ let resolutions = this.#resolutions.get(source.resolverId);
578
+ if (!resolutions) this.#resolutions.set(source.resolverId, resolutions = /* @__PURE__ */ new Map());
579
+ resolutions.set(specifier, id);
580
+ this.host.watch(id);
581
+ try {
582
+ let dependency = this.#sources.get(id);
583
+ if (!dependency) {
584
+ dependency = await this.prepare(await this.#load(id));
585
+ this.#register(dependency);
586
+ }
587
+ return dependency;
588
+ } catch (error) {
589
+ if (!this.analysis) throw error;
590
+ observed.status = "unsupported";
591
+ this.analysis.unverified.push({
592
+ moduleId: source.moduleId,
593
+ reason: String(error)
594
+ });
595
+ if (error instanceof CompilationFailure) this.analysis.batches.push(...error.batches);
596
+ }
597
+ }
598
+ /**
599
+ * Uses host resolution first and a checker identity only when the host returns null.
600
+ *
601
+ * @param source - Importer whose full resolver identity is passed to the host.
602
+ * @param specifier - Authored module request.
603
+ * @param semanticId - Optional identity supplied by checker resolution.
604
+ * @returns A resolution, or null when unavailable. Analysis mode converts host exceptions to null.
605
+ * @throws If host resolution fails in strict mode.
606
+ */
607
+ async #resolveDependency(source, specifier, semanticId) {
608
+ try {
609
+ return await this.host.resolve(specifier, source.resolverId, { skipSelf: true }) ?? (semanticId ? { id: semanticId } : null);
610
+ } catch (error) {
611
+ if (!this.analysis) throw error;
612
+ return null;
613
+ }
614
+ }
615
+ /**
616
+ * Distinguishes traversable sources from checker declarations and unsupported dependencies.
617
+ *
618
+ * @param id - Full resolved host identity.
619
+ * @param observed - Mutable dependency record whose status becomes types or unsupported when skipped.
620
+ * @returns Whether the dependency should be loaded as source.
621
+ */
622
+ #canLoadDependency(id, observed) {
623
+ const name = cleanModuleId(id);
624
+ if (/\.d\.[cm]?ts$/.test(name) || !this.host.typeFactsResolution && /(?:^|[\\/])node_modules[\\/]/.test(name)) {
625
+ observed.status = "types";
626
+ return false;
627
+ }
628
+ if (!(this.host.supports?.(id) ?? /\.(?:[cm]?[jt]sx?|astro|svelte|vue)$/.test(name))) {
629
+ observed.status = "unsupported";
630
+ return false;
631
+ }
632
+ return true;
633
+ }
634
+ /**
635
+ * Reuses a prepared project source or loads new input through the host.
636
+ *
637
+ * @param id - Full resolved dependency identity.
638
+ * @returns A shared prepared source or new input from the host. Do not mutate cached sources.
639
+ * @throws If host loading, description, or reading fails.
640
+ */
641
+ async #load(id) {
642
+ const cached = this.project?.source(id);
643
+ if (cached) return cached;
644
+ return loadSource(this.host, id);
645
+ }
646
+ /**
647
+ * Collects available facts for retained sources when entry probes require semantic information.
648
+ *
649
+ * @returns Facts keyed by compiler identity. Analysis mode records unavailable queries and may return partial facts.
650
+ * @throws If strict checker collection fails or a compilation failure occurs while preparing checker sources.
651
+ */
652
+ async #collectFacts() {
653
+ if (!this.#needsTypeFacts) return /* @__PURE__ */ new Map();
654
+ try {
655
+ const backend = this.factsService();
656
+ if (!backend) {
657
+ if (!this.analysis) throw new Error("Type facts required for this compilation are unavailable");
658
+ for (const source of this.#sources.values()) this.#unavailable(source, "Semantic queries are disabled");
659
+ return /* @__PURE__ */ new Map();
660
+ }
661
+ if (this.analysis) {
662
+ const sources = (this.project?.revision === this.#projectRevision ? this.project?.install(backend, this.#checkerSources(), this.options.typeFactsInputs) : void 0) ?? this.#checkerSources();
663
+ const available = await backend.collectAvailable(sources, this.#assets(), this.options.typeFactsInputs);
664
+ this.analysis.unverified.push(...available.unverified);
665
+ return available.facts;
666
+ }
667
+ return await backend.collect(this.#checkerSources(), this.#assets(), this.options.typeFactsInputs);
668
+ } catch (error) {
669
+ if (!this.analysis || error instanceof CompilationFailure) throw error;
670
+ for (const source of this.#sources.values()) this.#unavailable(source, String(error));
671
+ return /* @__PURE__ */ new Map();
672
+ }
673
+ }
674
+ };
675
+ /**
676
+ * Selects imports needed to answer the current semantic demand.
677
+ *
678
+ * @param summary - Scanner summary for the source being traversed.
679
+ * @param requested - Null for entry probes, `*` for a namespace demand, or a specific exported
680
+ * name.
681
+ * @returns Probe imports, imports for a matched export, or matching re-export demands. Unmatched
682
+ * and namespace demands conservatively retain all imports and re-exports.
683
+ */
684
+ function semanticDependencies(summary, requested) {
685
+ if (requested === null) return summary.probeImports;
686
+ const selected = summary.exportImports.find((entry) => entry.name === requested);
687
+ if (requested !== "*" && selected) return selected.imports;
688
+ const reExports = summary.reExports.filter((entry) => requested === "*" || entry.exported === requested || entry.exported === "*");
689
+ if (requested !== "*" && reExports.length > 0) return reExports.map((entry) => ({
690
+ source: entry.source,
691
+ imported: entry.exported === "*" ? requested : entry.imported
692
+ }));
693
+ return [...summary.imports, ...summary.reExports];
694
+ }
695
+ // src/compilation/request.ts
696
+ /**
697
+ * Creates an empty observed graph before loading its semantic dependencies.
698
+ *
699
+ * @param entry - Compiler module ID of the loaded entry source.
700
+ * @returns A mutable graph with no reports or dependencies and generation initially allowed.
701
+ */
702
+ function createModuleAnalysis(entry) {
703
+ return {
704
+ entry,
705
+ coverage: "observed",
706
+ modules: [],
707
+ batches: [],
708
+ fixes: [],
709
+ sources: [],
710
+ dependencies: [],
711
+ unverified: [],
712
+ generation: "complete"
713
+ };
714
+ }
715
+ // src/compilation/compiler.ts
716
+ /** Most reloads with new plugin definitions during one compilation of a graph. */
717
+ const PLUGIN_ROUNDS = 3;
718
+ /**
719
+ * Analyzes an entry and its semantic dependencies without requiring stylesheet delivery IDs.
720
+ * Source failures return diagnostic batches. Unavailable semantic information records unverified
721
+ * ranges. Entry I/O and native transport failures reject.
722
+ * The caller owns the initialized session and the lazy checker service.
723
+ *
724
+ * @param session - Native project session with an initialized design system.
725
+ * @param factsService - Supplies a checker configured for the host's TypeScript environment,
726
+ * or undefined when semantic facts are unavailable.
727
+ * @param id - Full resolver identity of the entry, including query suffixes.
728
+ * @param host - Source loading, resolution, metadata, and dependency tracking operations.
729
+ * @param typeFactsInputs - Captured overlays and ambient declarations for this analysis.
730
+ * @param project - Optional sources prepared by earlier analyses of this project.
731
+ * The caller must invalidate changed sources before analysis starts.
732
+ * @returns Reports and sources for the semantic dependencies demanded by the entry.
733
+ * @throws If entry I/O fails, a host changes resolver identity, or native transport operations fail.
734
+ */
735
+ async function analyzeModule(session, factsService, id, host, typeFactsInputs, project) {
736
+ const revision = project?.revision;
737
+ const captured = project?.source(id);
738
+ const input = captured ?? await loadSource(host, id);
739
+ if (project?.revision !== revision) project = void 0;
740
+ const analysis = createModuleAnalysis(input.moduleId);
741
+ if (!captured && input.resolverId !== id) throw new Error(`Host changed resolver identity for ${id}`);
742
+ await compileGraph(session, factsService, input.document.code, input.resolverId, host, {
743
+ diagnostics: "collect",
744
+ moduleCssImport: "stillwind/module-css",
745
+ typeFactsInputs
746
+ }, analysis, input, project);
747
+ for (const batch of analysis.batches) for (const report of batch.reports) {
748
+ const edits = report.actions[0]?.edits;
749
+ if (edits?.length && report.code !== "prefer-sorted-utilities") analysis.fixes.push(edits);
750
+ }
751
+ return analysis;
752
+ }
753
+ /**
754
+ * Compiles an entry buffer and its demanded semantic dependencies into a project session.
755
+ * The host descriptor supplies the module identity and parser metadata for each source.
756
+ * Type facts are requested lazily for original-coordinate probes in JS/TS or SFC inputs.
757
+ *
758
+ * Collect mode retains compiler and checker reports, including known syntax and projection
759
+ * failures. The default throw mode rejects compiler diagnostics. Lint findings only produce warnings.
760
+ * Host I/O, checker process, and malformed native transport failures propagate in both modes.
761
+ * Failed compilation can still update the session, register watches, and send warnings.
762
+ *
763
+ * @param session - Native project session with an initialized design system.
764
+ * @param factsService - Supplies the type-facts service when the source graph needs semantic facts.
765
+ * @param code - Entry source before Stillwind transformation.
766
+ * @param id - Full resolver identity of the entry source, including its query suffix.
767
+ * @param host - Source metadata, resolution, reading, dependency tracking, and warning operations.
768
+ * @param options - Diagnostic behavior, captured checker inputs, and generated imports for the entry.
769
+ * @returns A promise for the entry output and composition metadata, or undefined when normal mode
770
+ * produces no entry code.
771
+ * @throws If compilation rejects diagnostics, source preparation fails, or host or checker operations fail.
772
+ */
773
+ async function compileModule(session, factsService, code, id, host, options = {}) {
774
+ return compileGraph(session, factsService, code, id, host, options);
775
+ }
776
+ /**
777
+ * Prepares the demanded graph, compiles it into the session, and derives the entry output.
778
+ *
779
+ * @param session - Initialized native session that retains successful module artifacts.
780
+ * @param factsService - Lazy checker backend for semantic probes.
781
+ * @param code - Original entry text used when entryInput is absent.
782
+ * @param id - Full host identity of the entry.
783
+ * @param host - Stable source metadata, resolution, and notification operations.
784
+ * @param options - Diagnostic policy, captured checker inputs, and entry transport imports.
785
+ * @param analysis - Optional object populated with sources, dependencies, reports, and generation status.
786
+ * @param entryInput - Optional loaded entry, which takes precedence over code and host.describe.
787
+ * @param project - Optional prepared sources shared with other analyses of this project.
788
+ * @returns Entry output, a diagnostic-only output after a collected failure, or undefined when no code is emitted.
789
+ * @throws If strict compilation fails or a host or transport failure cannot be collected.
790
+ */
791
+ async function compileGraph(session, factsService, code, id, host, options, analysis, entryInput, project) {
792
+ const graph = new ModuleGraph(session, factsService, host, options, analysis, project);
793
+ let hasModuleCssImport = false;
794
+ try {
795
+ const descriptor = entryInput ?? {
796
+ resolverId: id,
797
+ ...host.describe(id),
798
+ document: {
799
+ ...host.describe(id).document,
800
+ code
801
+ }
802
+ };
803
+ const entrySource = await graph.prepare(descriptor);
804
+ const entrySummary = graph.scan(entrySource);
805
+ hasModuleCssImport = entrySummary.moduleCssImports > 0;
806
+ if (entrySummary.macroImports > 0) entrySource.stylesheetImports = options.stylesheetImports;
807
+ if (hasModuleCssImport) entrySource.moduleCssImport = options.moduleCssImport;
808
+ await graph.collectDependencies(entrySource, entrySummary);
809
+ const typedSources = await graph.collectTypedSources(entrySource);
810
+ const producer = analysis ? void 0 : entrySource.moduleId;
811
+ const projectOutput = await compileWithPlugins(session, () => session.compile(typedSources, producer), PLUGIN_ROUNDS);
812
+ if (analysis) recordAnalysis(analysis, projectOutput.modules, session, typedSources, graph);
813
+ reportOutputDiagnostics(projectOutput.modules, graph, host, options);
814
+ return entryOutput(projectOutput.modules, entrySource.moduleId, hasModuleCssImport, options);
815
+ } catch (error) {
816
+ const failure = graph.failure(error);
817
+ if (failure instanceof CompilationFailure && options.diagnostics === "collect") {
818
+ if (analysis) {
819
+ analysis.batches = [...failure.batches];
820
+ analysis.generation = "blocked";
821
+ }
822
+ return failedOutput(entryInput?.moduleId ?? host.describe(id).moduleId, failure.batches, hasModuleCssImport);
823
+ }
824
+ throw failure;
825
+ }
826
+ }
827
+ /**
828
+ * Selects the entry and computes its composition dependency identities and topology fingerprint.
829
+ *
830
+ * @param modules - Native outputs in compiler order.
831
+ * @param entryModuleId - Compiler identity of the requested entry.
832
+ * @param hasModuleCssImport - Whether the entry requested an explicit CSS value.
833
+ * @param options - Diagnostic policy controlling whether reports from all modules are attached.
834
+ * @returns Enriched entry output. Throw mode omits entries without nonempty code, and collect mode retains them.
835
+ */
836
+ function entryOutput(modules, entryModuleId, hasModuleCssImport, options) {
837
+ const output = modules.find((candidate) => candidate.moduleId === entryModuleId);
838
+ const composition = output?.composition ?? [];
839
+ const compositionModules = [...new Set(composition.map(({ base }) => base.moduleId))].filter((module) => module !== entryModuleId);
840
+ const compositionTopology = JSON.stringify(composition.map(({ derived, base }) => [`${derived.moduleId}:${derived.start}`, `${base.moduleId}:${base.start}`]).sort((a, b) => a[0].localeCompare(b[0]) || a[1].localeCompare(b[1])));
841
+ if (options.diagnostics === "collect" && output) return {
842
+ ...output,
843
+ hasModuleCssImport,
844
+ compositionModules,
845
+ compositionTopology,
846
+ diagnostics: modules.flatMap((module) => module.diagnostics),
847
+ reports: modules.flatMap((module) => module.reports)
848
+ };
849
+ if (!output?.code) return;
850
+ return {
851
+ ...output,
852
+ hasModuleCssImport,
853
+ compositionModules,
854
+ compositionTopology
855
+ };
856
+ }
857
+ /**
858
+ * Populates analysis batches and removes artifacts when missing semantic facts block lowering.
859
+ *
860
+ * @param analysis - Mutable result whose unverified ranges are deduplicated and generation status updated.
861
+ * @param modules - Mutable native outputs whose reports are filtered and artifacts may be cleared.
862
+ * @param session - Session used to diagnose sources independently when facts are unavailable.
863
+ * @param typedSources - Prepared sources from the same compilation, with available type facts attached.
864
+ * @param graph - Graph retaining scanner summaries for the compiled modules.
865
+ */
866
+ function recordAnalysis(analysis, modules, session, typedSources, graph) {
867
+ analysis.modules = modules;
868
+ analysis.unverified = [...new Map(analysis.unverified.map((range) => [JSON.stringify(range), range])).values()];
869
+ const localReports = analysis.unverified.length ? session.diagnose(typedSources) : [];
870
+ for (const module of modules) {
871
+ module.reports = localReports.find((batch) => batch.module === module.moduleId)?.reports ?? module.reports;
872
+ const ranges = analysis.unverified.filter((range) => range.moduleId === module.moduleId);
873
+ const generationUnverified = generationNeedsFacts(graph.summary(module.moduleId), ranges);
874
+ module.reports = verifiedReports(module.reports, ranges);
875
+ if (generationUnverified || module.diagnostics.length) analysis.generation = "blocked";
876
+ if (generationUnverified) clearArtifacts(module);
877
+ analysis.batches.push({
878
+ module: module.moduleId,
879
+ reports: module.reports
880
+ });
881
+ }
882
+ }
883
+ /**
884
+ * Checks whether unavailable semantic information affects a probe required for lowering.
885
+ *
886
+ * @param summary - Scanner summary for the module, or undefined if unavailable.
887
+ * @param ranges - Unverified ranges in original UTF-8 bytes. Missing bounds cover the whole module.
888
+ * @returns Whether an unbounded range exists or a bounded range overlaps a probe beyond recognition.
889
+ */
890
+ function generationNeedsFacts(summary, ranges) {
891
+ return ranges.some((range) => {
892
+ if (range.start === void 0 || range.end === void 0) return true;
893
+ return summary?.typeProbes.some((probe) => !probe.recognitionOnly && overlaps(range, probe.start, probe.end));
894
+ });
895
+ }
896
+ /**
897
+ * Keeps source failures while omitting missing checker facts errors in unverified ranges.
898
+ *
899
+ * @param reports - Reports with original UTF-8 locations.
900
+ * @param ranges - Unverified original UTF-8 ranges for the same module.
901
+ * @returns A filtered array in report order. Other diagnostic codes remain unchanged.
902
+ */
903
+ function verifiedReports(reports, ranges) {
904
+ return reports.filter((report) => {
905
+ if (report.code !== checkerFactsRequiredCode) return true;
906
+ const { start, end } = report.primary.location;
907
+ return !ranges.some((range) => overlaps(range, start, end));
908
+ });
909
+ }
910
+ /** `CompileDiagnostic::CheckerFactsRequired`, which unverified semantic ranges can cause. */
911
+ const checkerFactsRequiredCode = "SW30001";
912
+ /**
913
+ * Tests whether a diagnostic or probe overlaps an unavailable semantic range.
914
+ *
915
+ * @param range - Half-open original UTF-8 range. Missing bounds cover the entire module.
916
+ * @param start - Inclusive original UTF-8 byte offset.
917
+ * @param end - Exclusive original UTF-8 byte offset.
918
+ * @returns Whether the ranges intersect, treating an unbounded range as intersecting everything.
919
+ */
920
+ function overlaps(range, start, end) {
921
+ if (range.start === void 0 || range.end === void 0) return true;
922
+ return start < range.end && end > range.start;
923
+ }
924
+ /**
925
+ * Removes generated artifacts while keeping reports and composition metadata for analysis.
926
+ *
927
+ * @param module - Mutable output whose missing facts make its generated artifacts unreliable.
928
+ */
929
+ function clearArtifacts(module) {
930
+ module.code = null;
931
+ module.css = "";
932
+ module.resources = [];
933
+ module.classes = [];
934
+ module.symbols = [];
935
+ module.mappings = [];
936
+ }
937
+ /**
938
+ * Checks output identities, reports lint and rejected-name warnings, and enforces diagnostic policy.
939
+ *
940
+ * @param modules - Native outputs with identities registered in graph.
941
+ * @param graph - Source graph used to verify each output's host identity.
942
+ * @param host - Warning receiver, which may receive messages before a later failure.
943
+ * @param options - Collect mode retains compiler reports instead of throwing.
944
+ * @throws If an output identity is unknown or throw mode encounters compiler errors.
945
+ */
946
+ function reportOutputDiagnostics(modules, graph, host, options) {
947
+ for (const output of modules) {
948
+ graph.resolverId(output.moduleId);
949
+ if (output.diagnostics.length > 0 && options.diagnostics !== "collect") throw new CompilationFailure(modules.filter((module) => module.diagnostics.length > 0).map((module) => ({
950
+ module: module.moduleId,
951
+ reports: module.reports
952
+ })));
953
+ reportLintWarnings(output, host);
954
+ warnRejectedNames(output.rejectedNames ?? [], (message) => host.warn(message));
955
+ }
956
+ }
957
+ /**
958
+ * Reports naming fallbacks through the host warning channel without a source location.
959
+ *
960
+ * @param rejected - Generator rejections in request order.
961
+ * @param warn - Receives the family, input hash, and rejection reason for each fallback.
962
+ */
963
+ function warnRejectedNames(rejected, warn) {
964
+ for (const entry of rejected) warn(`stillwind: the ${entry.kind} name for ${entry.hash} was rejected: ${entry.reason}`);
965
+ }
966
+ /**
967
+ * Sends enabled lint findings through the host without changing their report severity.
968
+ *
969
+ * @param output - Findings and per-rule lint levels. Missing settings default to off.
970
+ * @param host - Receiver for warning text with original source positions.
971
+ */
972
+ function reportLintWarnings(output, host) {
973
+ for (const finding of output.lintFindings ?? []) {
974
+ if ((output.lintSettings?.[finding.rule] ?? "off") === "off") continue;
975
+ host.warn(`${finding.rule}: ${finding.message} (${finding.uri}:${finding.start})`);
976
+ }
977
+ }
978
+ /**
979
+ * Projects a report's primary label into the diagnostic shape returned by compilation.
980
+ *
981
+ * @param report - Structured compiler report.
982
+ * @returns Primary location and scope, diagnostic code and class, message, and notes. Related
983
+ * labels and severity remain in the report.
984
+ */
985
+ function reportDiagnostic(report) {
986
+ return {
987
+ ...report.primary.location,
988
+ scope: report.primary.scope,
989
+ code: report.code,
990
+ ...report.class && { class: report.class },
991
+ message: report.message,
992
+ notes: report.notes
993
+ };
994
+ }
995
+ /**
996
+ * Builds a collect-mode entry output when preparation, scanning, or checking failed.
997
+ *
998
+ * @param moduleId - Compiler identity of the entry module.
999
+ * @param batches - Failure reports from the attempted compilation.
1000
+ * @param hasModuleCssImport - Whether scanning found an explicit CSS value import in the entry.
1001
+ * @returns An output with null code, empty generated artifacts, all reports, and diagnostics
1002
+ * derived only from error reports.
1003
+ */
1004
+ function failedOutput(moduleId, batches, hasModuleCssImport) {
1005
+ const reports = batches.flatMap((batch) => batch.reports);
1006
+ return {
1007
+ moduleId,
1008
+ code: null,
1009
+ css: "",
1010
+ resources: [],
1011
+ mappings: [],
1012
+ classes: [],
1013
+ symbols: [],
1014
+ diagnostics: reports.filter((report) => report.severity === "error").map(reportDiagnostic),
1015
+ reports,
1016
+ rejectedNames: [],
1017
+ dynamicCandidates: [],
1018
+ lintFindings: [],
1019
+ lintSettings: {},
1020
+ composition: [],
1021
+ hasModuleCssImport,
1022
+ compositionModules: [],
1023
+ compositionTopology: "[]"
1024
+ };
1025
+ }
1026
+ // src/css/banners.ts
1027
+ /**
1028
+ * Formats notices as the prefix of a published stylesheet.
1029
+ *
1030
+ * @param banners - Notices in published order without duplicates, as a native plan or part lists
1031
+ * them. Callers that combine lists must order them again with `cssBanners` from `stillwind/css`.
1032
+ * @returns The notices in the given order, each followed by a newline.
1033
+ */
1034
+ function cssBannerPrefix(banners) {
1035
+ return banners.map((banner) => `${banner}\n`).join("");
1036
+ }
1037
+ /**
1038
+ * Adds notices before a CSS body without changing the body.
1039
+ *
1040
+ * @param output - CSS body and the notices that it requires, in the form that
1041
+ * {@link cssBannerPrefix} accepts.
1042
+ * @returns The published stylesheet text, or an empty string when the body is blank.
1043
+ */
1044
+ function finalizeCss(output) {
1045
+ return output.css.trim() ? cssBannerPrefix(output.banners ?? []) + output.css : "";
1046
+ }
1047
+ // src/css/plugins/host.ts
1048
+ /**
1049
+ * Matches an import or `@plugin` specifier that names a file by a relative or absolute path or
1050
+ * a `file:` URL, rather than a package.
1051
+ */
1052
+ const PATH_SPECIFIER = /^(?:\.{1,2}[\\/]|[\\/]|[a-z]:[\\/]|file:)/i;
1053
+ /**
1054
+ * Recognizes Tailwind's plugin export forms without executing a factory.
1055
+ *
1056
+ * @param value - Default export of a plugin module.
1057
+ * @returns Whether `value` is a function or an object with a `handler` function.
1058
+ */
1059
+ function isTailwindPlugin(value) {
1060
+ return typeof value === "function" || typeof value === "object" && value !== null && typeof value.handler === "function";
1061
+ }
1062
+ /**
1063
+ * Whether a loaded plugin uses the Stillwind plugin contract.
1064
+ *
1065
+ * @param plugin - Configured or loaded plugin.
1066
+ * @returns Whether `plugin` has a `css` function, which Tailwind plugins lack.
1067
+ */
1068
+ function nativePlugin(plugin) {
1069
+ return typeof plugin === "object" && plugin !== null && "css" in plugin && typeof plugin.css === "function";
1070
+ }
1071
+ /**
1072
+ * Selects the plugin that a module exports by default.
1073
+ *
1074
+ * @param module - Evaluated module namespace.
1075
+ * @param specifier - Request that loaded the module, used in the error message.
1076
+ * @returns The default export.
1077
+ * @throws If the default export is neither a Stillwind plugin object nor a Tailwind v4 plugin.
1078
+ */
1079
+ function defaultPluginExport(module, specifier) {
1080
+ const plugin = module?.default;
1081
+ if (isTailwindPlugin(plugin)) return plugin;
1082
+ if (typeof plugin !== "object" || plugin === null || typeof plugin.name !== "string" || typeof plugin.css !== "function") throw new Error(`Stillwind plugin ${specifier} must export a plugin object by default, or a Tailwind v4 handler`);
1083
+ return plugin;
1084
+ }
1085
+ /**
1086
+ * Returns the utility text before the cursor for plugin catalog lookup.
1087
+ *
1088
+ * @param text - Text before the cursor. The candidate ends at the cursor and starts after the
1089
+ * last whitespace, quote, backtick, `;`, `{`, or `}`.
1090
+ * @returns The candidate without its variants, such as `icon-mdi--cl` for `hover:icon-mdi--cl`.
1091
+ */
1092
+ function catalogInput(text) {
1093
+ const candidate = /[^\s"'`;{}]*$/.exec(text)[0];
1094
+ let depth = 0;
1095
+ for (let index = candidate.length - 1; index >= 0; index--) {
1096
+ const character = candidate[index];
1097
+ if (character === "]" || character === ")") depth++;
1098
+ else if ((character === "[" || character === "(") && depth > 0) depth--;
1099
+ else if (character === ":" && depth === 0) return candidate.slice(index + 1);
1100
+ }
1101
+ return candidate;
1102
+ }
1103
+ /**
1104
+ * Identifies one `@plugin` statement independently of its request ID.
1105
+ *
1106
+ * @param request - Plugin request.
1107
+ * @returns Importer, specifier, and JSON options joined by NUL characters.
1108
+ */
1109
+ function instanceKey(request) {
1110
+ return `${request.importer}\0${request.specifier}\0${JSON.stringify(request.pluginOptions ?? [])}`;
1111
+ }
1112
+ /**
1113
+ * Identifies one request independently of its ID, which changes between loads.
1114
+ *
1115
+ * @param request - Loader request.
1116
+ * @returns Importer, specifier, and JSON plugin options joined by NUL characters. An `@import`
1117
+ * has no options part.
1118
+ */
1119
+ function answerKey(request) {
1120
+ return `${request.importer}\0${request.specifier}\0${JSON.stringify(request.pluginOptions) ?? ""}`;
1121
+ }
1122
+ // src/css/plugins/runtime.ts
1123
+ /**
1124
+ * Specifier of the `@plugin` request that the native loader adds after the root stylesheet for
1125
+ * the Tailwind settings. Decoded CSS never contains NUL, so no authored statement has it.
1126
+ */
1127
+ const SETTINGS = "\0stillwind-tailwind-settings";
1128
+ /**
1129
+ * Matches `@stillwind-dynamic <prefix>*;` or `<prefix>[*];` and captures the prefix.
1130
+ */
1131
+ const DYNAMIC = /@stillwind-dynamic\s+([^\s;*[\]]+)(?:\[\*\]|\*)\s*;/g;
1132
+ /**
1133
+ * Runs the plugins of one CSS graph and defines candidates of their dynamic families on demand.
1134
+ *
1135
+ * The runtime records every answer of the graph's load, so {@link PluginRuntime.replay} loads the
1136
+ * same graph again without host I/O, with the definitions that plugins have added since. A
1137
+ * candidate that a plugin leaves undefined is not requested again for the runtime's lifetime.
1138
+ *
1139
+ * Tailwind plugins of the graph share one adapter runtime, which {@link PluginRuntime.initialize}
1140
+ * creates after the first load because their handlers read the complete CSS theme.
1141
+ */
1142
+ var PluginRuntime = class {
1143
+ options;
1144
+ plugins;
1145
+ root;
1146
+ host;
1147
+ watch;
1148
+ previous;
1149
+ settings;
1150
+ /** Plugin statements keyed by importer, specifier, and options text. */
1151
+ #instances = /* @__PURE__ */ new Map();
1152
+ /** Recorded answers keyed by {@link answerKey}. */
1153
+ #answers = /* @__PURE__ */ new Map();
1154
+ /** Requests of the load by importer and request ID, which order the plugin statements. */
1155
+ #requests = /* @__PURE__ */ new Map();
1156
+ /** Root answer, recorded by {@link PluginRuntime.recordRoot}. */
1157
+ #root;
1158
+ /** Candidates already passed to a plugin, including ones it left undefined. */
1159
+ #requested = /* @__PURE__ */ new Set();
1160
+ /** Editor catalogs keyed by input, oldest first. The empty input is never evicted. */
1161
+ #catalogs = /* @__PURE__ */ new Map();
1162
+ /**
1163
+ * Number of {@link PluginRuntime.resolve} calls that added CSS. The loader of the original
1164
+ * load contains the definitions of generation zero.
1165
+ */
1166
+ #generation = 0;
1167
+ /** Runtime of every Tailwind plugin of the graph, which share one config and theme. */
1168
+ #tailwind;
1169
+ /** Loader of the original load, whose source IDs replays share without a session. */
1170
+ #loader;
1171
+ /** Loader for the last queried definition generation. Source usage remains in separate sessions. */
1172
+ #snapshot;
1173
+ /** Tailwind statements in stylesheet order; an index is the statement's owner index. */
1174
+ #tailwindInstances = [];
1175
+ /** Answer to the {@link SETTINGS} request, which the Tailwind runtime generates. */
1176
+ #settingsCss = "";
1177
+ /**
1178
+ * Creates a runtime for one load.
1179
+ *
1180
+ * @param options - Compiler options of the load, reused by {@link PluginRuntime.replay}.
1181
+ * @param plugins - Plugins configured for the project, which take precedence over packages.
1182
+ * @param root - Absolute project directory passed to plugins.
1183
+ * @param host - Loads plugin packages and plugin files, or undefined when the host can only use
1184
+ * configured plugins.
1185
+ * @param watch - Registers files and directories that plugins read.
1186
+ * @param previous - Runtime of an earlier load of the same project. A statement with the same
1187
+ * specifier, options, and plugin resolves the earlier load's candidates of its families again.
1188
+ * @param settings - Project's Tailwind settings. Either field makes the graph use the Tailwind
1189
+ * plugin adapter, as a Tailwind `@plugin` statement does.
1190
+ */
1191
+ constructor(options, plugins, root, host, watch, previous, settings) {
1192
+ this.options = options;
1193
+ this.plugins = plugins;
1194
+ this.root = root;
1195
+ this.host = host;
1196
+ this.watch = watch;
1197
+ this.previous = previous;
1198
+ this.settings = settings;
1199
+ }
1200
+ /** Number of definition batches added after the original load. */
1201
+ get generation() {
1202
+ return this.#generation;
1203
+ }
1204
+ /** Whether project settings or a loaded plugin require the Tailwind adapter. */
1205
+ get tailwind() {
1206
+ return this.settings?.tailwind !== void 0 || this.settings?.important !== void 0 || [...this.#instances.values()].some((instance) => instance.tailwind);
1207
+ }
1208
+ /** Whether any loaded plugin declares a dynamic family. */
1209
+ get dynamic() {
1210
+ return !!this.#tailwind || [...this.#instances.values()].some((instance) => instance.prefixes.length > 0);
1211
+ }
1212
+ /**
1213
+ * Records the root answer of the load.
1214
+ *
1215
+ * @param answer - Root input without its request ID.
1216
+ */
1217
+ recordRoot(answer) {
1218
+ this.#root = answer;
1219
+ }
1220
+ /**
1221
+ * Records the answer to an `@import` request so that a replay can repeat it.
1222
+ *
1223
+ * @param request - Loader request.
1224
+ * @param answer - File input supplied for it, without its request ID.
1225
+ */
1226
+ recordImport(request, answer) {
1227
+ this.#recordRequest(request);
1228
+ this.#answers.set(answerKey(request), answer);
1229
+ }
1230
+ /**
1231
+ * Runs the plugin of an `@plugin` request and returns the answer for it.
1232
+ *
1233
+ * The answer's definitions are the user's own when the host loads the plugin from a
1234
+ * relative or absolute path and `own` is true. Otherwise, they belong to the plugin that the
1235
+ * specifier names, including a plugin configured for the project.
1236
+ *
1237
+ * @param request - Loader request whose `pluginOptions` is set.
1238
+ * @param own - Whether the stylesheet that contains the statement is the user's own CSS.
1239
+ * @returns File input without its request ID. Its name identifies the specifier and options.
1240
+ * @throws If no plugin has the specifier's name and the host cannot load it, or the plugin fails.
1241
+ */
1242
+ async answerPlugin(request, own = false) {
1243
+ this.#recordRequest(request);
1244
+ const key = instanceKey(request);
1245
+ let instance = this.#instances.get(key);
1246
+ if (!instance) {
1247
+ const configured = this.plugins.find((candidate) => candidate.name === request.specifier);
1248
+ const plugin = configured ?? await this.host?.load(request.specifier, request.importer, this.watch);
1249
+ if (!plugin) throw new Error(`Stillwind plugin ${request.specifier} is not configured, and this host cannot load packages`);
1250
+ const context = {
1251
+ options: Object.fromEntries((request.pluginOptions ?? []).map((option) => [option.name, option.value])),
1252
+ root: this.root,
1253
+ watch: this.watch,
1254
+ resolve: async (specifier) => this.host?.resolve(specifier, request.importer),
1255
+ read: async (path) => {
1256
+ if (!this.host) throw new Error(`This host cannot read plugin files: ${path}`);
1257
+ return this.host.read(path);
1258
+ },
1259
+ list: async (path) => {
1260
+ if (!this.host?.list) throw new Error(`This host cannot list plugin directories: ${path}`);
1261
+ return this.host.list(path);
1262
+ }
1263
+ };
1264
+ const css = nativePlugin(plugin) ? await plugin.css(context) : "";
1265
+ const prefixes = [...css.matchAll(DYNAMIC)].map((match) => match[1]);
1266
+ const previous = this.previous ? this.previous.#instances.get(key) : void 0;
1267
+ const candidates = previous?.plugin === plugin && nativePlugin(plugin) && plugin.resolve ? previous.candidates.filter((candidate) => prefixes.some((prefix) => candidate.startsWith(prefix))) : [];
1268
+ const resolved = candidates.length && nativePlugin(plugin) ? await plugin.resolve(candidates, context) : "";
1269
+ for (const candidate of candidates) this.#requested.add(candidate);
1270
+ instance = {
1271
+ plugin,
1272
+ context,
1273
+ css,
1274
+ prefixes,
1275
+ candidates,
1276
+ definitions: resolved.trim() ? [resolved] : [],
1277
+ origin: !configured && own && PATH_SPECIFIER.test(request.specifier) ? { kind: "own" } : {
1278
+ kind: "plugin",
1279
+ name: request.specifier
1280
+ },
1281
+ tailwind: nativePlugin(plugin) ? void 0 : (await import("./configuration-CnrzO-F3.js")).configurePlugin(plugin, request.pluginOptions ?? [])
1282
+ };
1283
+ this.#instances.set(key, instance);
1284
+ }
1285
+ const answer = this.#pluginAnswer(key, instance);
1286
+ this.#answers.set(answerKey(request), answer);
1287
+ return answer;
1288
+ }
1289
+ /**
1290
+ * Evaluates Tailwind handlers with the complete CSS theme, then resolves the candidates of
1291
+ * dynamic families that the graph's CSS applies with `@apply` and `@variant`.
1292
+ *
1293
+ * Tailwind handlers run after the first load because their `theme()` calls read the complete
1294
+ * CSS theme. Their output then needs one more load of the recorded graph. Dynamic candidates in
1295
+ * the graph's CSS need one more load when a plugin defines any of them, with or without
1296
+ * Tailwind. Canonical queries prepare spelling indexes on demand.
1297
+ *
1298
+ * Each later load requests the Tailwind settings after the root stylesheet, as
1299
+ * {@link TailwindRuntime.settingsCss} describes.
1300
+ *
1301
+ * @param loader - Loader of the completed original load. With Tailwind plugins or settings, it
1302
+ * can skip its canonical spelling index, as {@link PluginRuntime.tailwind} allows.
1303
+ * @returns `loader` when no plugin adds CSS, and otherwise a loader with the added CSS.
1304
+ * @throws If the Tailwind configuration is rejected or invalid, a plugin, a handler, or a
1305
+ * callback fails, or the native loader rejects the generated CSS.
1306
+ */
1307
+ async initialize(loader) {
1308
+ this.#loader = loader;
1309
+ const instances = this.#orderedInstances().filter((instance) => instance.tailwind);
1310
+ const project = await this.#projectConfig();
1311
+ let current = loader;
1312
+ if (instances.length || project) {
1313
+ this.#tailwindInstances = instances;
1314
+ const { TailwindRuntime } = await import("./plugin-DvCyhK1k.js");
1315
+ const editor = loader.editorQuery();
1316
+ this.#tailwind = new TailwindRuntime(instances.map((instance) => instance.tailwind), editor.themeTokens(), editor.legacyThemeKeys(), project);
1317
+ if (this.previous) await this.resolve(this.previous.#requested);
1318
+ this.#updateTailwindCss();
1319
+ current = this.replay(void 0, true);
1320
+ }
1321
+ if (!this.dynamic) {
1322
+ this.#snapshot = {
1323
+ generation: this.#generation,
1324
+ loader: current
1325
+ };
1326
+ return current;
1327
+ }
1328
+ const query = current.editorQuery();
1329
+ const sources = [this.#root?.content ?? "", ...[...this.#answers.values()].map((a) => a.content)];
1330
+ if (await this.resolve(sources.flatMap((css) => query.stylesheetDynamicCandidates(css)))) current = this.replay(void 0, true);
1331
+ this.#snapshot = {
1332
+ generation: this.#generation,
1333
+ loader: current
1334
+ };
1335
+ return current;
1336
+ }
1337
+ /**
1338
+ * Loads the runtime's current CSS definitions once per definition generation.
1339
+ *
1340
+ * @returns The shared loader for editor queries. Do not add CSS or session usage to it.
1341
+ * @throws If the native loader rejects the plugin definitions.
1342
+ */
1343
+ snapshot() {
1344
+ if (this.#snapshot?.generation !== this.#generation) this.#snapshot = {
1345
+ generation: this.#generation,
1346
+ loader: this.replay(void 0, true)
1347
+ };
1348
+ return this.#snapshot.loader;
1349
+ }
1350
+ /**
1351
+ * Resolves one editor candidate in a separate loader without changing a session's used CSS.
1352
+ *
1353
+ * @param candidate - Candidate as an editor offers it, such as `probe-4` or `state-open:`.
1354
+ * @returns Queries over the shared loader containing the candidate's definitions.
1355
+ * @throws If a plugin fails or the native loader rejects the generated CSS.
1356
+ */
1357
+ async query(candidate) {
1358
+ const query = this.snapshot().editorQuery();
1359
+ return await this.resolve(query.dynamicCandidates(candidate)) ? this.snapshot().editorQuery() : query;
1360
+ }
1361
+ /**
1362
+ * Passes new candidates to the plugins that declare their families.
1363
+ *
1364
+ * @param candidates - Compiler requests for native utility names, complete Tailwind utility
1365
+ * keys, or variant names with an `@variant ` prefix. Previously requested keys are skipped.
1366
+ * @returns Whether any plugin returned CSS, so that the design system must be loaded again.
1367
+ * @throws If a plugin fails.
1368
+ */
1369
+ async resolve(candidates) {
1370
+ const pending = /* @__PURE__ */ new Map();
1371
+ const tailwind = [];
1372
+ for (const candidate of candidates) {
1373
+ if (this.#requested.has(candidate)) continue;
1374
+ this.#requested.add(candidate);
1375
+ if (this.#tailwind?.accepts(candidate)) tailwind.push(candidate);
1376
+ for (const instance of this.#instances.values()) if (nativePlugin(instance.plugin) && instance.plugin.resolve && instance.prefixes.some((prefix) => candidate.startsWith(prefix))) {
1377
+ pending.set(instance, [...pending.get(instance) ?? [], candidate]);
1378
+ break;
1379
+ }
1380
+ }
1381
+ let changed = this.#tailwind?.resolve(tailwind) ?? false;
1382
+ if (changed) this.#updateTailwindCss();
1383
+ for (const [instance, names] of pending) {
1384
+ instance.candidates.push(...names);
1385
+ const css = nativePlugin(instance.plugin) ? await instance.plugin.resolve(names, instance.context) : "";
1386
+ if (css.trim()) {
1387
+ instance.definitions.push(css);
1388
+ changed = true;
1389
+ }
1390
+ }
1391
+ if (changed) this.#generation++;
1392
+ return changed;
1393
+ }
1394
+ /**
1395
+ * Lists the candidates that editors complete for the loaded dynamic families.
1396
+ *
1397
+ * @param input - Utility text before an editor's cursor, without variants, or an empty string
1398
+ * for the candidates that editors always offer.
1399
+ * @returns Candidate names that start with `input`, from every plugin with a catalog, sorted
1400
+ * and deduplicated. Names that end with `-` are incomplete. The runtime keeps the answers for
1401
+ * the empty input and for the {@link CATALOG_INPUTS} most recent other inputs.
1402
+ */
1403
+ catalog(input = "") {
1404
+ let names = this.#catalogs.get(input);
1405
+ if (names) this.#catalogs.delete(input);
1406
+ else names = Promise.all([...this.#instances.values()].map(async (instance) => nativePlugin(instance.plugin) && instance.plugin.catalog ? await instance.plugin.catalog(instance.context, input) : [])).then((lists) => [.../* @__PURE__ */ new Set([...lists.flat(), ...this.#tailwind?.catalog() ?? []])].filter((name) => name.startsWith(input)).sort());
1407
+ this.#catalogs.set(input, names);
1408
+ for (const key of this.#catalogs.keys()) {
1409
+ if (this.#catalogs.size <= 17) break;
1410
+ if (key) this.#catalogs.delete(key);
1411
+ }
1412
+ return names;
1413
+ }
1414
+ /**
1415
+ * Loads the recorded graph again into a loader of `session`, with the current definitions.
1416
+ *
1417
+ * @param session - Session whose source IDs the new loader shares. Omission shares the
1418
+ * original loader's source IDs.
1419
+ * @param intermediate - Skips preparing the canonical spelling index for a loader that only
1420
+ * serves a later load or a short query. Canonical queries still prepare it on first use.
1421
+ * @returns A complete loader with the load's compiler options, for
1422
+ * {@link NativeProjectSession.reload}.
1423
+ * @throws If the recorded graph is incomplete or the native loader rejects it.
1424
+ */
1425
+ replay(session, intermediate = false) {
1426
+ if (!this.#root) throw new Error("Stillwind plugin runtime has no recorded CSS graph");
1427
+ const loader = session ? session.newLoader(this.options) : this.#loader?.newLoader(this.options) ?? new NativeDesignSystemLoader(this.options);
1428
+ if (intermediate) loader.deferCanonicalIndex();
1429
+ if (this.#tailwind) loader.requestTrailingPlugin(SETTINGS);
1430
+ let step = loader.provide(0, this.#root.name, this.#root.content, this.#root.uri, this.#root.sourceMapSource, this.#root.lint);
1431
+ while (step.kind !== "complete") step = loader.provideMany(step.requests.map((request) => {
1432
+ if (this.#tailwind && request.specifier === SETTINGS && request.pluginOptions !== void 0) return {
1433
+ id: request.id,
1434
+ name: `stillwind-plugin:${SETTINGS.slice(1)}#${this.#generation}`,
1435
+ content: this.#settingsCss
1436
+ };
1437
+ const instance = request.pluginOptions !== void 0 ? this.#instances.get(instanceKey(request)) : void 0;
1438
+ const answer = instance ? this.#pluginAnswer(instanceKey(request), instance) : this.#answers.get(answerKey(request));
1439
+ if (!answer) throw new Error(`Stillwind plugin runtime has no answer for ${request.specifier}`);
1440
+ return {
1441
+ id: request.id,
1442
+ ...answer
1443
+ };
1444
+ }));
1445
+ return loader;
1446
+ }
1447
+ /**
1448
+ * Returns the answer to a plugin request with the instance's current definitions.
1449
+ *
1450
+ * @param key - Importer, specifier, and options text of the instance.
1451
+ * @param instance - Loaded plugin statement.
1452
+ * @returns An internal buffer whose name changes with its content.
1453
+ */
1454
+ #pluginAnswer(key, instance) {
1455
+ return {
1456
+ name: `stillwind-plugin:${key.replaceAll("\0", "#")}#${this.#generation}#${instance.definitions.length}`,
1457
+ content: [instance.css, ...instance.definitions].join("\n"),
1458
+ origin: instance.origin
1459
+ };
1460
+ }
1461
+ /**
1462
+ * Stores the generated CSS of each Tailwind statement and of the settings as their answers.
1463
+ */
1464
+ #updateTailwindCss() {
1465
+ for (const [owner, instance] of this.#tailwindInstances.entries()) instance.css = this.#tailwind.css(owner);
1466
+ this.#settingsCss = this.#tailwind.settingsCss();
1467
+ }
1468
+ /**
1469
+ * Awaits the project's Tailwind configuration and applies its `important` field.
1470
+ *
1471
+ * @returns The configuration with `important` applied, or undefined without settings.
1472
+ * @throws If the configuration promise rejects, its value is not an object, or both the field
1473
+ * and the configuration set `important`.
1474
+ */
1475
+ async #projectConfig() {
1476
+ const { important } = this.settings ?? {};
1477
+ const tailwind = await this.settings?.tailwind;
1478
+ if (tailwind === void 0) return important === void 0 ? void 0 : { important };
1479
+ if (typeof tailwind !== "object" || tailwind === null || Array.isArray(tailwind)) throw new Error("Stillwind config tailwind must resolve to a Tailwind configuration object");
1480
+ const config = tailwind;
1481
+ if (important === void 0) return config;
1482
+ if (config.important !== void 0) throw new Error("Stillwind config important must not be set together with tailwind.important");
1483
+ return {
1484
+ ...config,
1485
+ important
1486
+ };
1487
+ }
1488
+ /**
1489
+ * Records a request of the load, which orders the plugin statements.
1490
+ *
1491
+ * @param request - Import or plugin request.
1492
+ */
1493
+ #recordRequest(request) {
1494
+ let requests = this.#requests.get(request.importer);
1495
+ if (!requests) this.#requests.set(request.importer, requests = /* @__PURE__ */ new Map());
1496
+ requests.set(request.id, request);
1497
+ }
1498
+ /**
1499
+ * Orders the plugin statements as the import-expanded stylesheet does.
1500
+ *
1501
+ * @returns Each statement once, depth first from the root in request order.
1502
+ */
1503
+ #orderedInstances() {
1504
+ const result = /* @__PURE__ */ new Set();
1505
+ const visited = /* @__PURE__ */ new Set();
1506
+ /**
1507
+ * Adds the statements of one stylesheet and of the stylesheets it imports.
1508
+ *
1509
+ * @param name - Recorded identity of the stylesheet.
1510
+ */
1511
+ const visit = (name) => {
1512
+ if (visited.has(name)) return;
1513
+ visited.add(name);
1514
+ for (const request of [...this.#requests.get(name)?.values() ?? []].sort((a, b) => a.id - b.id)) {
1515
+ const instance = this.#instances.get(instanceKey(request));
1516
+ if (request.pluginOptions !== void 0 && instance) result.add(instance);
1517
+ else {
1518
+ const answer = this.#answers.get(answerKey(request));
1519
+ if (answer) visit(answer.name);
1520
+ }
1521
+ }
1522
+ };
1523
+ if (this.#root) visit(this.#root.name);
1524
+ return [...result];
1525
+ }
1526
+ };
1527
+ // src/css/css.ts
1528
+ /**
1529
+ * Checks whether an identity names a stylesheet.
1530
+ *
1531
+ * @param id - Resolver identity or file path.
1532
+ * @returns Whether the complete identity ends in `.css`, ignoring case. The check includes any
1533
+ * query suffix.
1534
+ */
1535
+ function isStylesheet(id) {
1536
+ return /\.css$/i.test(id);
1537
+ }
1538
+ /**
1539
+ * Loads original CSS, then retries with recovered definitions if that load fails.
1540
+ *
1541
+ * @param root - Resolved CSS entrypoint.
1542
+ * @param options - Compiler policies used by semantic queries.
1543
+ * @param host - Resolver and reads of the captured original buffers.
1544
+ * @param pluginInputs - Plugins for `@plugin` statements, as {@link loadCssGraph} describes.
1545
+ * @returns A query graph and whether its sources were recovered. Original buffers remain unchanged.
1546
+ * The recovered graph must only supply editor queries, because its text omits authored rules.
1547
+ * @throws If both loads fail, including unresolved imports or unreadable files.
1548
+ */
1549
+ async function loadEditorCssGraph(root, options, host, pluginInputs) {
1550
+ try {
1551
+ return {
1552
+ ...await loadCssGraph(root, options, host, void 0, void 0, pluginInputs),
1553
+ recovered: false
1554
+ };
1555
+ } catch {
1556
+ return {
1557
+ ...await loadCssGraph(root, options, {
1558
+ ...host,
1559
+ read: async (id) => editorCssSource(await host.read(id))
1560
+ }, void 0, void 0, pluginInputs),
1561
+ recovered: true
1562
+ };
1563
+ }
1564
+ }
1565
+ /**
1566
+ * Selects the user's own CSS for stylesheet lint. The root is linted unless it lies under
1567
+ * `node_modules`. An import is linted when lint checks its importer, its specifier is a relative
1568
+ * or absolute path, and its file does not lie under `node_modules`. A package specifier such as
1569
+ * `stillwind` or `tailwindcss` therefore excludes the package and everything it imports, even when
1570
+ * the package resolves outside `node_modules`.
1571
+ *
1572
+ * @param id - Resolved CSS file identity.
1573
+ * @param importer - Importing file and its lint mark, or undefined for the root.
1574
+ * @param specifier - Import request text, or undefined for the root.
1575
+ * @returns Whether stylesheet lint checks the file.
1576
+ */
1577
+ function lintsStylesheet(id, importer, specifier) {
1578
+ if (/[\\/]node_modules[\\/]/.test(id)) return false;
1579
+ return !importer || importer.lint && specifier !== void 0 && PATH_SPECIFIER.test(specifier);
1580
+ }
1581
+ /**
1582
+ * Names the package that supplies an imported stylesheet that is not the user's own CSS.
1583
+ *
1584
+ * A package specifier, such as `stillwind` or `@scope/name/theme.css`, names its package. A path
1585
+ * specifier keeps the package of its importer, so a package's relative imports stay in the
1586
+ * package. Otherwise, the last `node_modules` directory in `id` names the package.
1587
+ *
1588
+ * @param id - Resolved CSS file identity.
1589
+ * @param specifier - Import request text.
1590
+ * @param importerPackage - Package of the importing file, or undefined when it has none.
1591
+ * @returns The package name, or undefined when none of these rules names one.
1592
+ */
1593
+ function stylesheetPackage(id, specifier, importerPackage) {
1594
+ if (!PATH_SPECIFIER.test(specifier)) {
1595
+ const [first, second] = specifier.split("/");
1596
+ return first.startsWith("@") && second !== void 0 ? `${first}/${second}` : first;
1597
+ }
1598
+ if (importerPackage !== void 0) return importerPackage;
1599
+ return [...id.matchAll(/[\\/]node_modules[\\/]((?:@[^\\/]+[\\/])?[^\\/]+)/g)].at(-1)?.[1].replace("\\", "/");
1600
+ }
1601
+ /**
1602
+ * Loads a CSS graph and returns the completed native loader and its resource references.
1603
+ * `root` must already be resolved and accepted by the host's read and watch methods.
1604
+ * `options` configures a new loader. If `suppliedLoader` is given, it must not have
1605
+ * received any input yet, and this function uses its existing configuration.
1606
+ * `rootContent` skips reading the root file. The function still watches that file
1607
+ * and all resolved dependencies. Each file is marked for stylesheet lint as `host.lint` decides,
1608
+ * or as {@link lintsStylesheet} decides when the host omits it.
1609
+ * Canonical queries build their indexes on first use.
1610
+ *
1611
+ * Reads run concurrently, and each request ID is read only once. Responses ready
1612
+ * in the same event-loop turn are sent together to reduce native calls. Faster reads
1613
+ * can reveal more imports without waiting for slower reads.
1614
+ * Resolution, read, and native loading errors reject the promise. Reads already
1615
+ * started continue, and files already registered with the watcher stay registered.
1616
+ *
1617
+ * @param root - Resolved CSS entrypoint accepted by the host's read and watch operations.
1618
+ * @param options - Compiler settings used when creating a new loader.
1619
+ * @param host - CSS resolver, reader, source identity operations, and dependency watcher.
1620
+ * @param rootContent - Optional entrypoint text that replaces the initial filesystem read.
1621
+ * @param suppliedLoader - Optional configured loader that has not received any CSS input.
1622
+ * @param pluginInputs - Plugins for `@plugin` statements. Omission uses no configured plugins,
1623
+ * the root's directory as the project directory, and the host's plugin operations.
1624
+ * @returns A promise for the completed native loader and its authored resource references.
1625
+ * @throws If resolving, reading, or loading the CSS graph fails.
1626
+ */
1627
+ async function loadCssGraph(root, options, host, rootContent, suppliedLoader, pluginInputs) {
1628
+ const loader = suppliedLoader ?? new NativeDesignSystemLoader(options);
1629
+ loader.deferCanonicalIndex();
1630
+ const plugins = new PluginRuntime(options, pluginInputs?.plugins ?? [], pluginInputs?.root ?? root.replace(/[\\/][^\\/]*$/, ""), host.plugins, (path, kind) => {
1631
+ if (kind === "directory") host.watchDirectory?.(path);
1632
+ else host.watch(path);
1633
+ }, pluginInputs?.previous, pluginInputs && {
1634
+ tailwind: pluginInputs.tailwind,
1635
+ important: pluginInputs.important
1636
+ });
1637
+ host.watch(root);
1638
+ const lints = /* @__PURE__ */ new Map();
1639
+ const packages = /* @__PURE__ */ new Map();
1640
+ const lint = (id, importer, specifier) => host.lint ? host.lint(id, importer, specifier) : lintsStylesheet(id, importer, specifier);
1641
+ lints.set(root, lint(root));
1642
+ const rootAnswer = {
1643
+ name: root,
1644
+ content: rootContent ?? await host.read(root),
1645
+ uri: host.documentUri(root),
1646
+ sourceMapSource: host.sourceMapSource(root),
1647
+ lint: lints.get(root)
1648
+ };
1649
+ plugins.recordRoot(rootAnswer);
1650
+ const initial = loader.provide(0, rootAnswer.name, rootAnswer.content, rootAnswer.uri, rootAnswer.sourceMapSource, rootAnswer.lint);
1651
+ let completion;
1652
+ await new Promise((resolveLoad, rejectLoad) => {
1653
+ const started = /* @__PURE__ */ new Set();
1654
+ let stopped = false;
1655
+ let queued = false;
1656
+ let ready = [];
1657
+ /**
1658
+ * Stops graph advancement and rejects the pending load.
1659
+ * @param error - Resolution, reading, or native loading failure passed to the caller.
1660
+ */
1661
+ const fail = (error) => {
1662
+ stopped = true;
1663
+ rejectLoad(error);
1664
+ };
1665
+ /**
1666
+ * Completes the graph or starts reads for requests that have not already started.
1667
+ * @param step - Native loading step. Completion stores resources and resolves the load.
1668
+ */
1669
+ const advance = (step) => {
1670
+ if (step.kind === "complete") {
1671
+ completion = step;
1672
+ stopped = true;
1673
+ resolveLoad();
1674
+ return;
1675
+ }
1676
+ for (const request of step.requests) {
1677
+ if (started.has(request.id)) continue;
1678
+ started.add(request.id);
1679
+ /**
1680
+ * Resolves, watches, and reads this request, then schedules a batch of ready responses.
1681
+ * An import that the host cannot resolve or read is answered as unresolved.
1682
+ * @returns A promise that resolves after queuing the response, or after observing a stopped load.
1683
+ * @throws If a plugin fails to load. The attached rejection handler stops the load.
1684
+ */
1685
+ const read = async () => {
1686
+ if (request.pluginOptions !== void 0) {
1687
+ const answer = await plugins.answerPlugin(request, lints.get(request.importer) ?? false);
1688
+ if (plugins.tailwind) loader.deferCanonicalIndex();
1689
+ if (!stopped) {
1690
+ ready.push({
1691
+ id: request.id,
1692
+ ...answer
1693
+ });
1694
+ schedule();
1695
+ }
1696
+ return;
1697
+ }
1698
+ /**
1699
+ * Answers the request as unresolved, so the loader skips the import and stylesheet lint
1700
+ * reports it.
1701
+ */
1702
+ const unresolved = () => {
1703
+ if (stopped) return;
1704
+ const answer = {
1705
+ name: request.specifier,
1706
+ content: "",
1707
+ lint: false,
1708
+ unresolved: true
1709
+ };
1710
+ plugins.recordImport(request, answer);
1711
+ ready.push({
1712
+ id: request.id,
1713
+ ...answer
1714
+ });
1715
+ schedule();
1716
+ };
1717
+ let name;
1718
+ try {
1719
+ name = await host.resolve(request.specifier, request.importer);
1720
+ } catch {
1721
+ unresolved();
1722
+ return;
1723
+ }
1724
+ if (stopped) return;
1725
+ host.watch(name);
1726
+ let content;
1727
+ try {
1728
+ content = await host.read(name);
1729
+ } catch {
1730
+ unresolved();
1731
+ return;
1732
+ }
1733
+ if (stopped) return;
1734
+ const marked = lint(name, {
1735
+ id: request.importer,
1736
+ lint: lints.get(request.importer) ?? false
1737
+ }, request.specifier);
1738
+ lints.set(name, (lints.get(name) ?? false) || marked);
1739
+ const library = marked ? void 0 : stylesheetPackage(name, request.specifier, packages.get(request.importer));
1740
+ if (!marked && !packages.has(name)) packages.set(name, library);
1741
+ const answer = {
1742
+ name,
1743
+ content,
1744
+ uri: host.documentUri(name),
1745
+ sourceMapSource: host.sourceMapSource(name),
1746
+ lint: marked,
1747
+ ...marked ? {} : { origin: {
1748
+ kind: "library",
1749
+ name: library
1750
+ } }
1751
+ };
1752
+ plugins.recordImport(request, answer);
1753
+ ready.push({
1754
+ id: request.id,
1755
+ ...answer
1756
+ });
1757
+ schedule();
1758
+ };
1759
+ read().catch(fail);
1760
+ }
1761
+ };
1762
+ /** Sends the responses that are ready in the current event-loop turn together. */
1763
+ const schedule = () => {
1764
+ if (!queued) {
1765
+ queued = true;
1766
+ setTimeout(() => {
1767
+ queued = false;
1768
+ const responses = ready;
1769
+ ready = [];
1770
+ if (stopped) return;
1771
+ try {
1772
+ advance(loader.provideMany(responses));
1773
+ } catch (error) {
1774
+ fail(error);
1775
+ }
1776
+ });
1777
+ }
1778
+ };
1779
+ advance(initial);
1780
+ });
1781
+ return {
1782
+ loader: await plugins.initialize(loader),
1783
+ resources: completion?.resources ?? [],
1784
+ lintSources: completion?.lintSources ?? [],
1785
+ skipped: completion?.skipped ?? [],
1786
+ plugins
1787
+ };
1788
+ }
1789
+ // src/editor/candidates.ts
1790
+ /**
1791
+ * Shares previews, batch ordering, completion catalogs, and summaries for one captured design system.
1792
+ */
1793
+ var CandidateQueries = class {
1794
+ /** Native query pinned to the design system used for candidate validation and previews. */
1795
+ #query;
1796
+ /** Successful and failed CSS previews keyed by preview kind, input role, and decoded candidate. */
1797
+ #previews = /* @__PURE__ */ new Map();
1798
+ /** Shared completion arrays keyed by input role, decoded prefix, and snippet support. */
1799
+ #completions = /* @__PURE__ */ new Map();
1800
+ /** Added marker classes and null results keyed by input role and decoded candidate. */
1801
+ #markers = /* @__PURE__ */ new Map();
1802
+ /** Summaries and empty results keyed by the full generated CSS, including preview annotations. */
1803
+ #details = /* @__PURE__ */ new Map();
1804
+ /**
1805
+ * Creates empty caches for one captured design system.
1806
+ *
1807
+ * @param query - Native query whose theme, utility definitions, and compiler settings supply
1808
+ * all results. A different design system requires a new instance.
1809
+ */
1810
+ constructor(query) {
1811
+ this.#query = query;
1812
+ }
1813
+ /**
1814
+ * Caches standalone CSS for one candidate and its input role, including failed resolution.
1815
+ * Ordinary utilities use `&` as their subject. Previews omit enclosing source conditions.
1816
+ *
1817
+ * @param candidate - Decoded candidate text, including any variants supplied by the caller.
1818
+ * Option roles also accept the option text supported by their registry.
1819
+ * @param context - Input role used for validation and emission. Defaults to ordinary utilities.
1820
+ * @returns CSS for valid input, or null when the native query cannot emit it.
1821
+ * @throws If a matching ordinary utility definition has a malformed requirement.
1822
+ */
1823
+ preview(candidate, context = "utility") {
1824
+ const key = `${context}\0${candidate}`;
1825
+ if (!this.#previews.has(key)) this.#previews.set(key, this.#query.previewCandidate(candidate, context));
1826
+ return this.#previews.get(key);
1827
+ }
1828
+ /**
1829
+ * Caches the marker class that one candidate adds to the element as written.
1830
+ *
1831
+ * @param candidate - Decoded candidate text, including enclosing variants.
1832
+ * @param context - Input role of the candidate. Only ordinary utilities add marker classes.
1833
+ * @returns The class and its origins, or null when the candidate adds no marker class.
1834
+ * Ref conditions of an enclosing style object are not checked.
1835
+ */
1836
+ marker(candidate, context = "utility") {
1837
+ const key = `${context}\0${candidate}`;
1838
+ if (!this.#markers.has(key)) this.#markers.set(key, this.#query.addedMarker(candidate, context));
1839
+ return this.#markers.get(key);
1840
+ }
1841
+ /**
1842
+ * Caches the selectors, at-rule conditions, and declarations of a variant chain.
1843
+ *
1844
+ * @param candidate - Decoded variant chain, with or without a trailing colon.
1845
+ * @param context - Original input role whose constraints must allow the entire chain.
1846
+ * @returns CSS introduced by the variants, or null when the chain or role is unsupported.
1847
+ * Utility output and surrounding source conditions are omitted.
1848
+ */
1849
+ variant(candidate, context) {
1850
+ const key = `variant\0${context}\0${candidate}`;
1851
+ if (!this.#previews.has(key)) this.#previews.set(key, this.#query.previewVariant(candidate, context));
1852
+ return this.#previews.get(key);
1853
+ }
1854
+ /**
1855
+ * Compares two ordinary utility candidates using the compiler's variant and utility order.
1856
+ *
1857
+ * @param left - Full decoded candidate spelling, including its variants.
1858
+ * @param right - Full decoded candidate spelling, including its variants.
1859
+ * @returns -1, 0, or 1, or null when either candidate cannot resolve.
1860
+ * @throws If a matching utility definition has a malformed requirement.
1861
+ */
1862
+ compare(left, right) {
1863
+ return this.#query.compareCandidates(left, right);
1864
+ }
1865
+ /**
1866
+ * Prepares all spellings in `values` with one native request.
1867
+ * Repeated spellings are resolved once. The input array remains unchanged.
1868
+ *
1869
+ * @param values - Full decoded ordinary utility candidates, including their variants.
1870
+ * @returns A comparator whose numeric rank differences belong only to this batch.
1871
+ * It returns null for unresolved candidates or spellings absent from `values`.
1872
+ * An empty batch returns a comparator that always returns null.
1873
+ * @throws If a matching utility requirement is malformed or a native rank exceeds uint32.
1874
+ */
1875
+ order(values) {
1876
+ const unique = [...new Set(values)];
1877
+ if (unique.length === 0) return () => null;
1878
+ const ranks = this.#query.candidateRanks(unique);
1879
+ const positions = new Map(unique.map((value, index) => [value, ranks[index]]));
1880
+ return (left, right) => {
1881
+ const a = positions.get(left);
1882
+ const b = positions.get(right);
1883
+ return a == null || b == null ? null : a - b;
1884
+ };
1885
+ }
1886
+ /**
1887
+ * Caches unique labels in lexical order for one decoded partial candidate and its role.
1888
+ * Existing variant prefixes remain present, and variant labels end in `:`.
1889
+ * Suggestions do not append a variant already present in the prefix. An ordinary utility
1890
+ * prefix without variants, `!`, or `-` also receives marker class names, which may have no
1891
+ * preview.
1892
+ *
1893
+ * @param prefix - Decoded partial candidate, including any enclosing variants.
1894
+ * @param context - Input role that selects the candidate registry and permitted variants.
1895
+ * Defaults to ordinary utilities.
1896
+ * @param snippets - Whether to include empty brackets for arbitrary variant values and `name/`
1897
+ * labels for modifiable markers. Defaults to false.
1898
+ * @returns A shared readonly array of matching labels.
1899
+ * @throws If a matching ordinary utility definition has a malformed requirement.
1900
+ */
1901
+ complete(prefix, context = "utility", snippets = false) {
1902
+ const key = `${context}\0${prefix}\0${snippets}`;
1903
+ if (!this.#completions.has(key)) this.#completions.set(key, this.#query.completeCandidate(prefix, context, snippets));
1904
+ return this.#completions.get(key);
1905
+ }
1906
+ /**
1907
+ * Caches a short declaration or rule summary for selected completion CSS.
1908
+ *
1909
+ * @param css - Generated CSS to summarize, including optional preview annotations.
1910
+ * @returns A summary of at most 160 Unicode code points, or undefined when the CSS has
1911
+ * no declarations or descriptive rule wrappers.
1912
+ */
1913
+ detail(css) {
1914
+ if (!this.#details.has(css)) this.#details.set(css, completionDetail(css) ?? void 0);
1915
+ return this.#details.get(css);
1916
+ }
1917
+ /**
1918
+ * Resolves a color utility's concrete color against this query's theme.
1919
+ *
1920
+ * @param candidate - Full decoded ordinary utility candidate, including variants and modifiers.
1921
+ * @returns sRGB red, green, blue, and effective alpha components in 0..1, or undefined when
1922
+ * the candidate is not a color utility or has no unambiguous concrete color.
1923
+ * @throws If a matching utility definition has a malformed requirement.
1924
+ */
1925
+ color(candidate) {
1926
+ return this.#query.candidateColor(candidate) ?? void 0;
1927
+ }
1928
+ };
1929
+ /**
1930
+ * Splits at delimiters outside brackets, parentheses, single or double quotes, and escapes.
1931
+ * The operation preserves source spelling and does not validate nesting syntax.
1932
+ *
1933
+ * @param text - Candidate text whose backslashes escape the following UTF-16 code unit.
1934
+ * @param delimiter - One UTF-16 code unit, such as `:` or `/`, that is not a bracket,
1935
+ * parenthesis, quote, or backslash.
1936
+ * @returns Segments in their original order, including empty segments. Nothing is trimmed
1937
+ * or unescaped, and an empty input returns one empty segment.
1938
+ */
1939
+ function segments(text, delimiter) {
1940
+ const result = [];
1941
+ let start = 0;
1942
+ let depth = 0;
1943
+ let quote = "";
1944
+ let escaped = false;
1945
+ for (let index = 0; index < text.length; index++) {
1946
+ const character = text[index];
1947
+ if (escaped) {
1948
+ escaped = false;
1949
+ continue;
1950
+ }
1951
+ if (character === "\\") {
1952
+ escaped = true;
1953
+ continue;
1954
+ }
1955
+ if (quote) {
1956
+ if (character === quote) quote = "";
1957
+ continue;
1958
+ }
1959
+ if (character === "'" || character === "\"") quote = character;
1960
+ else if (character === "[" || character === "(") depth++;
1961
+ else if (character === "]" || character === ")") depth--;
1962
+ else if (character === delimiter && depth === 0) {
1963
+ result.push(text.slice(start, index));
1964
+ start = index + 1;
1965
+ }
1966
+ }
1967
+ result.push(text.slice(start));
1968
+ return result;
1969
+ }
1970
+ /**
1971
+ * Describes an added marker class and the definitions that make it a marker.
1972
+ *
1973
+ * @param marker - Marker class returned by {@link CandidateQueries.marker}.
1974
+ * @returns Markdown with the class name first, followed by one line for each kind of origin.
1975
+ */
1976
+ function markerDocumentation(marker) {
1977
+ const code = (text) => {
1978
+ const ticks = "`".repeat(Math.max(0, ...[...text.matchAll(/`+/g)].map((match) => match[0].length)) + 1);
1979
+ return `${ticks}${text.startsWith("`") || text.endsWith("`") ? ` ${text} ` : text}${ticks}`;
1980
+ };
1981
+ const definitions = marker.origins.flatMap((origin) => origin.kind === "utility" || origin.kind === "variant" ? [`the ${code(origin.name)} ${origin.kind}`] : []);
1982
+ const kinds = new Set(marker.origins.map((origin) => origin.kind));
1983
+ return [
1984
+ `Adds the marker class ${code(marker.class)} to the element as written.`,
1985
+ kinds.has("declared") ? "A `@stillwind-marker` statement declares this class." : void 0,
1986
+ definitions.length ? `Selectors in ${list(definitions)} select this class.` : void 0,
1987
+ kinds.has("source") ? "Selectors in plugin CSS select this class." : void 0
1988
+ ].filter(Boolean).join("\n\n");
1989
+ }
1990
+ /**
1991
+ * Joins phrases into an English list.
1992
+ *
1993
+ * @param items - At least one phrase, in display order.
1994
+ * @returns The phrases separated by commas, with "and" before the last one.
1995
+ */
1996
+ function list(items) {
1997
+ return items.length < 3 ? items.join(" and ") : `${items.slice(0, -1).join(", ")}, and ${items.at(-1)}`;
1998
+ }
1999
+ // src/editor/request.ts
2000
+ /**
2001
+ * Starts an editor answer tied to the original source text.
2002
+ *
2003
+ * @param source - Complete original document text.
2004
+ * @returns An empty answer with the fingerprint required for its ranges and edits.
2005
+ */
2006
+ function editorResult(source) {
2007
+ return { revision: fingerprint(source) };
2008
+ }
2009
+ // src/editor/source/order.ts
2010
+ /**
2011
+ * Groups `items` by syntax category without crossing barriers.
2012
+ *
2013
+ * Ref groups retain their first appearance order, and each marker precedes its
2014
+ * projections. Bases, utilities, and custom properties follow in that order. Each
2015
+ * category retains its input order.
2016
+ *
2017
+ * @param items - Inputs in their current order, with a distinct object for each occurrence.
2018
+ * @param allows - Optional predicate that approves the original range covering each adjacent
2019
+ * exchange. Rejected exchanges can prevent the result from reaching the full category order.
2020
+ * @returns A new array of the original objects. The input array and its objects remain unchanged.
2021
+ */
2022
+ function orderInputs(items, allows) {
2023
+ const sorted = [];
2024
+ let start = 0;
2025
+ for (let end = 0; end <= items.length; end++) if (end === items.length || items[end].order.kind === "barrier") {
2026
+ sorted.push(...orderRun(items.slice(start, end), allows));
2027
+ if (end < items.length) sorted.push(items[end]);
2028
+ start = end + 1;
2029
+ }
2030
+ return sorted;
2031
+ }
2032
+ /**
2033
+ * Computes the category order for one run and applies any permitted adjacent exchanges.
2034
+ *
2035
+ * @param items - A run without barriers, with a distinct object for each occurrence.
2036
+ * @param allows - Optional predicate over the original range covering two adjacent inputs.
2037
+ * @returns The same input objects in a new array. Neither the input array nor its objects change.
2038
+ */
2039
+ function orderRun(items, allows) {
2040
+ const refs = /* @__PURE__ */ new Map();
2041
+ const groups = {
2042
+ bases: [],
2043
+ utilities: [],
2044
+ customProperties: []
2045
+ };
2046
+ for (const item of items) if (item.order.kind === "ref") {
2047
+ let group = refs.get(item.order.identity);
2048
+ if (!group) {
2049
+ group = {
2050
+ markers: [],
2051
+ projections: []
2052
+ };
2053
+ refs.set(item.order.identity, group);
2054
+ }
2055
+ group[item.order.projection ? "projections" : "markers"].push(item);
2056
+ } else if (item.order.kind !== "barrier") groups[item.order.kind].push(item);
2057
+ const ordered = [
2058
+ ...[...refs.values()].flatMap(({ markers, projections }) => [...markers, ...projections]),
2059
+ ...groups.bases,
2060
+ ...groups.utilities,
2061
+ ...groups.customProperties
2062
+ ];
2063
+ if (!allows) return ordered;
2064
+ const positions = new Map(ordered.map((item, index) => [item, index]));
2065
+ const sorted = [...items];
2066
+ for (let position = 1; position < sorted.length; position++) for (let cursor = position; cursor > 0; cursor--) {
2067
+ const left = sorted[cursor - 1];
2068
+ const right = sorted[cursor];
2069
+ if (positions.get(left) <= positions.get(right) || !allows(Math.min(left.start, right.start), Math.max(left.end, right.end))) break;
2070
+ [sorted[cursor - 1], sorted[cursor]] = [right, left];
2071
+ }
2072
+ return sorted;
2073
+ }
2074
+ /**
2075
+ * Classifies direct style input syntax and resolved declarations for grouping.
2076
+ *
2077
+ * @param source - Fixed source whose AST contains node.
2078
+ * @param node - Input or property to classify.
2079
+ * @param resolveAsset - Resolves native declaration identities and stable aliases for this source graph.
2080
+ * @returns An input category, or a barrier when the input cannot move safely.
2081
+ */
2082
+ function classifyInput(source, node, resolveAsset) {
2083
+ if (ts.isPropertyAssignment(node) || ts.isShorthandPropertyAssignment(node)) {
2084
+ if (ts.isComputedPropertyName(node.name)) return { kind: "barrier" };
2085
+ const name = ts.isStringLiteralLike(node.name) ? node.name.text : node.name.getText();
2086
+ if (name.startsWith("--")) return { kind: "customProperties" };
2087
+ return name === "" || name.endsWith(":") || name === "class" ? { kind: "utilities" } : { kind: "barrier" };
2088
+ }
2089
+ if (ts.isStringLiteralLike(node) || ts.isTemplateExpression(node)) return { kind: "utilities" };
2090
+ const asset = resolveAsset(source, node);
2091
+ if (asset?.identity.kind === "style") return { kind: "bases" };
2092
+ if (asset?.identity.kind === "ref") return {
2093
+ kind: "ref",
2094
+ identity: JSON.stringify(asset.identity),
2095
+ projection: false
2096
+ };
2097
+ if (ts.isCallExpression(node) && ts.isPropertyAccessExpression(node.expression) && [
2098
+ "asAnchor",
2099
+ "asContainer",
2100
+ "positionAnchor"
2101
+ ].includes(node.expression.name.text)) {
2102
+ const ref = resolveAsset(source, node.expression.expression);
2103
+ if (ref?.identity.kind === "ref") return {
2104
+ kind: "ref",
2105
+ identity: JSON.stringify(ref.identity),
2106
+ projection: true
2107
+ };
2108
+ }
2109
+ if (ts.isParenthesizedExpression(node) || ts.isAsExpression(node) || ts.isSatisfiesExpression(node) || ts.isNonNullExpression(node)) return classifyInput(source, node.expression, resolveAsset);
2110
+ if (ts.isArrayLiteralExpression(node) || ts.isObjectLiteralExpression(node)) {
2111
+ const orders = (ts.isArrayLiteralExpression(node) ? node.elements : node.properties).map((element) => classifyInput(source, element, resolveAsset));
2112
+ const first = orders[0];
2113
+ if (first && first.kind !== "barrier" && first.kind !== "ref" && orders.every((order) => order.kind === first.kind)) return first;
2114
+ }
2115
+ return { kind: "barrier" };
2116
+ }
2117
+ // src/editor/sort.ts
2118
+ /**
2119
+ * Composes existing edits with utility sorting and grouping of direct style inputs.
2120
+ * Literal sorting applies only to ordinary utilities. Containers are processed from the
2121
+ * smallest to the largest so an outer replacement includes edits to nested inputs.
2122
+ * Unknown syntax, ambiguous comments, and text that cannot map exactly delimit grouping.
2123
+ *
2124
+ * @param source - The same prepared source object stored in `index`, with an unchanged buffer.
2125
+ * @param index - Index built from that source graph before any edits are applied.
2126
+ * @param candidates - Candidate query for the design system that compiled the source.
2127
+ * @param options - Sorting targets. False returns only the seed edits in source order.
2128
+ * @param seed - Nonoverlapping replacements in original UTF-16 coordinates. Inside a sortable
2129
+ * literal, each edit must replace a complete utility token. Edits inside grouped containers must
2130
+ * stay within one input. Replacement text must contain any JS escapes needed at its range.
2131
+ * @param allows - Optional predicate that approves a whole literal's content range or the
2132
+ * range covering an adjacent input exchange. Every range uses original UTF-16 coordinates.
2133
+ * @returns Edits in ascending original offset order. The source and seed array remain unchanged.
2134
+ * @throws If a matching utility definition has a malformed requirement or native ranking fails.
2135
+ */
2136
+ function sortSource(source, index, candidates, options, seed = [], allows) {
2137
+ if (options === false) return seed.toSorted((a, b) => a.start - b.start);
2138
+ let edits = [...seed];
2139
+ const permits = allows ?? (() => true);
2140
+ if (options.stringLiterals !== false) {
2141
+ const literals = index.literals.filter((literal) => literal.source === source && literal.context === "utility" && permits(literal.boundaries[0], literal.boundaries.at(-1))).map((literal) => {
2142
+ const matches = [...literal.text.matchAll(/\S+/gu)];
2143
+ const original = matches.map((match) => match[0]);
2144
+ const spellings = matches.map((match) => {
2145
+ const start = literal.boundaries[match.index];
2146
+ const end = literal.boundaries[match.index + match[0].length];
2147
+ const edit = seed.find((edit) => edit.start === start && edit.end === end);
2148
+ return {
2149
+ token: edit ? decodeReplacement(edit.newText, literal) : match[0],
2150
+ text: edit?.newText ?? source.document.code.slice(start, end)
2151
+ };
2152
+ });
2153
+ return {
2154
+ literal,
2155
+ original,
2156
+ tokens: spellings.map((spelling) => spelling.token),
2157
+ matches,
2158
+ spellings
2159
+ };
2160
+ });
2161
+ const compare = candidates.order(literals.flatMap(({ literal, tokens }) => tokens.map((token) => literal.prefix + token)));
2162
+ for (const { literal, original, tokens, matches, spellings } of literals) {
2163
+ const start = literal.boundaries[0];
2164
+ const end = literal.boundaries.at(-1);
2165
+ const sorted = sortRuns(tokens, (a, b) => compare(literal.prefix + a, literal.prefix + b));
2166
+ if (sorted.every((token, position) => token === original[position])) continue;
2167
+ let cursor = start;
2168
+ let newText = "";
2169
+ const queues = /* @__PURE__ */ new Map();
2170
+ for (const spelling of spellings) {
2171
+ let queue = queues.get(spelling.token);
2172
+ if (!queue) {
2173
+ queue = {
2174
+ texts: [],
2175
+ position: 0
2176
+ };
2177
+ queues.set(spelling.token, queue);
2178
+ }
2179
+ queue.texts.push(spelling.text);
2180
+ }
2181
+ for (const [position, match] of matches.entries()) {
2182
+ const tokenStart = literal.boundaries[match.index];
2183
+ const tokenEnd = literal.boundaries[match.index + match[0].length];
2184
+ const queue = queues.get(sorted[position]);
2185
+ newText += source.document.code.slice(cursor, tokenStart) + queue.texts[queue.position++];
2186
+ cursor = tokenEnd;
2187
+ }
2188
+ newText += source.document.code.slice(cursor, end);
2189
+ edits = absorb(edits, {
2190
+ start,
2191
+ end,
2192
+ newText
2193
+ });
2194
+ }
2195
+ }
2196
+ if (options.arrays !== false) {
2197
+ const containers = index.containers.filter((container) => container.source === source).sort((a, b) => a.node.end - a.node.pos - (b.node.end - b.node.pos));
2198
+ for (const container of containers) {
2199
+ const elements = ts.isArrayLiteralExpression(container.node) ? container.node.elements : ts.isCallExpression(container.node) ? container.node.arguments : container.node.properties;
2200
+ const items = [...elements].map((node) => {
2201
+ const range = index.range(source, node);
2202
+ const offset = range ? range[0] - node.getStart() : 0;
2203
+ const start = node.getFullStart() + offset;
2204
+ const end = range?.[1] ?? 0;
2205
+ const text = range ? applyEdits(source.document.code.slice(start, end), edits.filter((edit) => edit.start >= start && edit.end <= end).map((edit) => ({
2206
+ ...edit,
2207
+ start: edit.start - start,
2208
+ end: edit.end - start
2209
+ }))) : "";
2210
+ const order = index.inputOrder(source, node);
2211
+ const ambiguousComment = /^[^\r\n]*(?:\/\/|\/\*)/.test(text) && node.pos > elements.pos;
2212
+ return {
2213
+ node,
2214
+ start,
2215
+ end,
2216
+ text,
2217
+ order: range && !ambiguousComment && source.document.code.slice(start, end) === node.getSourceFile().text.slice(node.getFullStart(), node.end) ? order : { kind: "barrier" }
2218
+ };
2219
+ });
2220
+ for (let position = 0; position < items.length; position++) {
2221
+ const item = items[position];
2222
+ const next = items[position + 1];
2223
+ const tail = source.document.code.slice(item.end, next?.start ?? index.range(source, container.node)?.[1] ?? item.end);
2224
+ if (/^[^\r\n]*(?:\/\/|\/\*)/.test(tail) || next && /^[^\r\n]*(?:\/\/|\/\*)/.test(next.text.slice(0, next.text.length - (next.node.end - next.node.getStart())))) item.order = { kind: "barrier" };
2225
+ }
2226
+ const sorted = orderInputs(items, allows);
2227
+ if (sorted.every((item, position) => item === items[position])) continue;
2228
+ for (let position = 0; position < items.length;) {
2229
+ if (items[position] === sorted[position]) {
2230
+ position++;
2231
+ continue;
2232
+ }
2233
+ const start = position++;
2234
+ while (position < items.length && items[position] !== sorted[position]) position++;
2235
+ if (items.slice(start, position).some((item) => item.order.kind === "barrier")) continue;
2236
+ const edit = {
2237
+ start: items[start].start,
2238
+ end: items[position - 1].end,
2239
+ newText: sorted.slice(start, position).map((item) => item.text).join(",")
2240
+ };
2241
+ edits = absorb(edits, edit);
2242
+ }
2243
+ }
2244
+ }
2245
+ return edits.sort((a, b) => a.start - b.start);
2246
+ }
2247
+ /**
2248
+ * Applies replacements from the end of a document so all ranges keep their original meaning.
2249
+ *
2250
+ * @param source - Original document text, or a slice whose coordinates match `edits`.
2251
+ * @param edits - Nonoverlapping half-open UTF-16 ranges within `source`, in any order.
2252
+ * The caller must provide valid boundaries because this function does not validate them.
2253
+ * @returns The replaced text. The edit array and its objects remain unchanged.
2254
+ */
2255
+ function applyEdits(source, edits) {
2256
+ for (const edit of [...edits].sort((a, b) => b.start - a.start)) source = source.slice(0, edit.start) + edit.newText + source.slice(edit.end);
2257
+ return source;
2258
+ }
2259
+ /**
2260
+ * Escapes replacement content for an existing JS string or template token.
2261
+ *
2262
+ * @param text - Decoded replacement text without surrounding delimiters.
2263
+ * @param literal - Indexed literal whose AST token supplies the quote or backtick delimiter.
2264
+ * @returns Content without delimiters, with backslashes, the delimiter, tabs, CR, and LF escaped.
2265
+ * Template content also escapes `${` so it cannot introduce an interpolation.
2266
+ */
2267
+ function escapeContent(text, literal) {
2268
+ const quote = ts.isTemplateLiteralToken(literal.node) ? "`" : literal.node.getText()[0];
2269
+ let escaped = text.replaceAll("\\", "\\\\").replaceAll(quote, `\\${quote}`).replaceAll(" ", "\\t").replaceAll("\r", "\\r").replaceAll("\n", "\\n");
2270
+ if (quote === "`") escaped = escaped.replaceAll("${", "\\${");
2271
+ return escaped;
2272
+ }
2273
+ /**
2274
+ * Decodes a seeded replacement using the original literal's delimiter.
2275
+ *
2276
+ * @param text - Source spelling of replacement content that can be wrapped in that delimiter.
2277
+ * @param literal - Indexed literal that supplies the quote or backtick delimiter.
2278
+ * @returns TypeScript's decoded string value, or the supplied text when parsing produces a
2279
+ * different initializer kind. Parser diagnostics are not checked.
2280
+ */
2281
+ function decodeReplacement(text, literal) {
2282
+ const quote = ts.isTemplateLiteralToken(literal.node) ? "`" : literal.node.getText()[0];
2283
+ const node = ts.createSourceFile("literal.ts", `const value=${quote}${text}${quote};`, ts.ScriptTarget.Latest, true).statements[0].declarationList.declarations[0].initializer;
2284
+ return node && ts.isStringLiteralLike(node) ? node.text : text;
2285
+ }
2286
+ /**
2287
+ * Replaces edits covered by a larger, already composed replacement.
2288
+ *
2289
+ * @param edits - Existing edits in original coordinates. Every overlapping edit must be fully
2290
+ * contained in `replacement` and already reflected in its text.
2291
+ * @param replacement - Replacement whose text includes all contained edits.
2292
+ * @returns A new array with overlapping edits removed and the replacement appended.
2293
+ * The result is not sorted, and the input edit objects remain unchanged.
2294
+ */
2295
+ function absorb(edits, replacement) {
2296
+ return [...edits.filter((edit) => edit.end <= replacement.start || edit.start >= replacement.end), replacement];
2297
+ }
2298
+ /**
2299
+ * Sorts contiguous runs of resolved utilities while keeping unresolved spellings in place.
2300
+ *
2301
+ * @param values - Decoded candidates in their original order.
2302
+ * @param compare - Compiler comparator prepared for these spellings. A null self-comparison
2303
+ * marks a boundary, and a null comparison within a run treats that pair as equal.
2304
+ * @returns A new array with stable ordering inside each run. `values` remains unchanged.
2305
+ */
2306
+ function sortRuns(values, compare) {
2307
+ const result = [...values];
2308
+ let start = 0;
2309
+ for (let position = 0; position <= values.length; position++) if (position === values.length || compare(values[position], values[position]) === null) {
2310
+ result.splice(start, position - start, ...values.slice(start, position).sort((a, b) => compare(a, b) ?? 0));
2311
+ start = position + 1;
2312
+ }
2313
+ return result;
2314
+ }
2315
+ // src/semantics/checker-source.ts
2316
+ /**
2317
+ * Serializes a declaration identity as a stable checker string-literal key.
2318
+ *
2319
+ * @param identity - Native declaration identity with original UTF-8 offsets.
2320
+ * @returns `stillwind-identity/v1:` followed by base64url JSON of kind, module ID, range, and
2321
+ * binding name in a fixed field order.
2322
+ */
2323
+ function identityKey(identity) {
2324
+ return `stillwind-identity/v1:${base64url(JSON.stringify({
2325
+ kind: identity.kind,
2326
+ moduleId: identity.moduleId,
2327
+ start: identity.start,
2328
+ end: identity.end,
2329
+ bindingName: identity.bindingName
2330
+ }))}`;
2331
+ }
2332
+ /**
2333
+ * Selects the checker filename for a prepared source.
2334
+ *
2335
+ * @param source - Source with its host checker filename and any projection syntax.
2336
+ * @returns The host filename for direct input, or that filename followed by the projection language
2337
+ * extension for projected input.
2338
+ */
2339
+ function checkerId(source) {
2340
+ return source.kind === "direct" ? source.checkerFileName : `${source.checkerFileName}.${source.projection.syntax.language}`;
2341
+ }
2342
+ /**
2343
+ * Applies the current query's probes to the project's sources without changing other inputs.
2344
+ *
2345
+ * @param inventory - Sources currently installed in the checker.
2346
+ * @param requested - Sources whose probe ranges or recognitionOnly settings may have changed.
2347
+ * Sources outside inventory are ignored.
2348
+ * @returns The original array when probes match, or a new array with changed source records.
2349
+ * Neither input is mutated. Unchanged source records are shared.
2350
+ */
2351
+ function withRequestedProbes(inventory, requested) {
2352
+ const probesById = new Map(requested.map((source) => [source.resolverId, source.probes]));
2353
+ let changed = false;
2354
+ const sources = inventory.map((source) => {
2355
+ const probes = probesById.get(source.resolverId);
2356
+ if (!probes || probes.length === source.probes.length && probes.every((probe, index) => probe.start === source.probes[index].start && probe.end === source.probes[index].end && probe.recognitionOnly === source.probes[index].recognitionOnly)) return source;
2357
+ changed = true;
2358
+ return {
2359
+ ...source,
2360
+ probes
2361
+ };
2362
+ });
2363
+ return changed ? sources : inventory;
2364
+ }
2365
+ /**
2366
+ * Checker buffer with declaration identities, resolved import paths, and helper aliases inserted
2367
+ * for type queries. Its range maps relate checker AST expressions to original document bytes.
2368
+ */
2369
+ var CheckerSource = class {
2370
+ /** Prepared source and original-coordinate requests that own this checker buffer. */
2371
+ source;
2372
+ /** Unedited input buffer, optionally restricted to one original script region. */
2373
+ buffer;
2374
+ /**
2375
+ * Final checker text after identity arguments, module paths, and helper bindings have been
2376
+ * rewritten.
2377
+ */
2378
+ text;
2379
+ /**
2380
+ * Checker filename, with a distinct client-script suffix when the buffer has an original region.
2381
+ */
2382
+ id;
2383
+ /** Serialized identity keys mapped to the native declarations supplied during construction. */
2384
+ identities = /* @__PURE__ */ new Map();
2385
+ /** Independent module that supplies helper declarations in the virtual project. */
2386
+ helperModule;
2387
+ /** Shadow UTF-16 AST ranges keyed to original UTF-8 probe ranges. */
2388
+ probes = /* @__PURE__ */ new Map();
2389
+ /** Producer call ranges after identity insertion, keyed to their asset families. */
2390
+ producers = /* @__PURE__ */ new Map();
2391
+ /** Authored module specifiers keyed by their rewritten checker UTF-16 ranges. */
2392
+ moduleSpecifiers = /* @__PURE__ */ new Map();
2393
+ /**
2394
+ * Ordered, nonoverlapping edits in the input buffer. Their cumulative lengths translate between
2395
+ * input and checker offsets.
2396
+ */
2397
+ #edits = [];
2398
+ /** Original document text used to convert byte ranges and recover diagnostic byte offsets. */
2399
+ #original;
2400
+ /**
2401
+ * Projected UTF-16 positions mapped to original UTF-16 positions. Null marks conflicting
2402
+ * correspondences. Missing keys have no known mapping.
2403
+ */
2404
+ #points;
2405
+ /**
2406
+ * Constructs checker text and range indexes without modifying the source or input buffer.
2407
+ *
2408
+ * @param source - Prepared source with validated frontend correspondences, probes, resolutions,
2409
+ * and helper references.
2410
+ * @param buffer - Direct or projected checker text, optionally scoped to an original script
2411
+ * region.
2412
+ * @param index - Buffer index used to give independent client scripts distinct filenames.
2413
+ * @param assets - Native declaration records with original-byte producer call ranges. Repeated
2414
+ * records for the same generated call are inserted once.
2415
+ * @param ids - Resolved source identities mapped to their main checker filenames for import
2416
+ * rewriting.
2417
+ * @throws If a byte boundary is invalid, producer identities conflict, a mapped producer does not
2418
+ * end with a closing parenthesis, edits overlap, or projection decoding fails.
2419
+ */
2420
+ constructor(source, buffer, index, assets, ids) {
2421
+ this.source = source;
2422
+ this.buffer = buffer;
2423
+ this.id = buffer.region ? `${source.checkerFileName}.stillwind-client-${index}.ts` : checkerId(source);
2424
+ this.#original = source.document.code;
2425
+ this.#points = projectionPoints(source);
2426
+ const producers = /* @__PURE__ */ new Map();
2427
+ const producerRanges = [];
2428
+ for (const asset of assets) {
2429
+ const targets = this.targets(asset.callStart, asset.callEnd, "producer");
2430
+ const key = identityKey(asset.identity);
2431
+ this.identities.set(key, asset.identity);
2432
+ for (const [start, end] of targets) {
2433
+ const previous = producers.get(end);
2434
+ if (previous) {
2435
+ if (previous !== key) throw new Error(`Conflicting producer identities in ${source.moduleId}`);
2436
+ continue;
2437
+ }
2438
+ producers.set(end, key);
2439
+ producerRanges.push({
2440
+ start,
2441
+ end,
2442
+ kind: asset.identity.kind
2443
+ });
2444
+ const call = buffer.source.slice(start, end);
2445
+ if (!call.endsWith(")")) throw new Error(`Cannot locate producer in ${source.moduleId}`);
2446
+ const separator = [...call.matchAll(/[,(]/g)].some((match) => skipTrivia(call, match.index + 1) === call.length - 1) ? "" : ",";
2447
+ const identity = `{readonly __stillwindDeclarationIdentity:${JSON.stringify(key)}}`;
2448
+ const syntax = source.kind === "direct" ? source.syntax : source.projection.syntax;
2449
+ const argument = syntax.language === "js" || syntax.language === "jsx" ? `/** @type {${identity}} */ (/** @type {unknown} */ (undefined))` : `undefined as unknown as ${identity}`;
2450
+ this.#edits.push({
2451
+ at: end - 1,
2452
+ end: end - 1,
2453
+ original: {
2454
+ start: asset.callStart,
2455
+ end: asset.callEnd
2456
+ },
2457
+ text: `${separator}${argument}`
2458
+ });
2459
+ }
2460
+ }
2461
+ const specifiers = [];
2462
+ for (const resolution of source.resolutions ?? []) for (const [at, end] of this.targets(resolution.start, resolution.end, "moduleSpecifier")) {
2463
+ const scanner = ts.createScanner(ts.ScriptTarget.Latest, true);
2464
+ scanner.setText(buffer.source.slice(at, end));
2465
+ scanner.scan();
2466
+ specifiers.push({
2467
+ start: at,
2468
+ end,
2469
+ text: scanner.getTokenValue()
2470
+ });
2471
+ this.#edits.push({
2472
+ at,
2473
+ end,
2474
+ original: {
2475
+ start: resolution.start,
2476
+ end: resolution.end
2477
+ },
2478
+ text: JSON.stringify(path.resolve(ids.get(resolution.id) ?? resolution.id).replaceAll("\\", "/"))
2479
+ });
2480
+ }
2481
+ const bindings = buffer.region ? [] : source.checkerBindings ?? [];
2482
+ if (bindings.length > 0) {
2483
+ const names = new Set(buffer.source.replaceAll(/\\u(?:\{([\da-fA-F]{1,6})\}|([\da-fA-F]{4}))/g, (escape, braced, fixed) => {
2484
+ const value = Number.parseInt(braced ?? fixed, 16);
2485
+ return value <= 1114111 ? String.fromCodePoint(value) : escape;
2486
+ }).match(/[$_\p{ID_Start}][$\u200c\u200d\p{ID_Continue}]*/gu));
2487
+ const aliases = /* @__PURE__ */ new Map();
2488
+ let next = 0;
2489
+ for (const binding of bindings) {
2490
+ let alias = aliases.get(binding.name);
2491
+ if (!alias) {
2492
+ do
2493
+ alias = `__stillwindCheckerHelper${next++}`;
2494
+ while (names.has(alias));
2495
+ aliases.set(binding.name, alias);
2496
+ }
2497
+ this.#edits.push({
2498
+ at: binding.projectedStart,
2499
+ end: binding.projectedEnd,
2500
+ text: alias,
2501
+ original: {
2502
+ start: 0,
2503
+ end: 0
2504
+ }
2505
+ });
2506
+ }
2507
+ const id = `${this.id}.stillwind-helpers.ts`;
2508
+ this.helperModule = {
2509
+ id,
2510
+ text: [...aliases.keys()].map((name) => `export declare const ${name}: typeof globalThis.${name};`).join("\n")
2511
+ };
2512
+ this.#edits.push({
2513
+ at: buffer.source.length,
2514
+ end: buffer.source.length,
2515
+ text: `\nimport {${[...aliases].map(([name, alias]) => `${name} as ${alias}`).join(",")}} from ${JSON.stringify(path.resolve(id).replaceAll("\\", "/"))};\n`,
2516
+ original: {
2517
+ start: 0,
2518
+ end: 0
2519
+ }
2520
+ });
2521
+ }
2522
+ this.#edits.sort((a, b) => a.at - b.at || a.end - b.end);
2523
+ for (let i = 1; i < this.#edits.length; i++) if (this.#edits[i].at < this.#edits[i - 1].end || this.#edits[i].at === this.#edits[i - 1].at) throw new Error(`Overlapping checker edits in ${source.moduleId}`);
2524
+ for (const probe of source.probes) for (const [start, end] of this.targets(probe.start, probe.end, "expression")) this.probes.set(`${this.toShadow(start)}:${this.toShadow(end, true)}`, probe);
2525
+ for (const specifier of specifiers) this.moduleSpecifiers.set(`${this.toShadow(specifier.start)}:${this.toShadow(specifier.end, true)}`, specifier.text);
2526
+ for (const producer of producerRanges) this.producers.set(`${this.toShadow(producer.start)}:${this.toShadow(producer.end, true)}`, producer.kind);
2527
+ let text = buffer.source;
2528
+ for (const edit of [...this.#edits].reverse()) text = text.slice(0, edit.at) + edit.text + text.slice(edit.end);
2529
+ this.text = text;
2530
+ }
2531
+ /**
2532
+ * Finds input-buffer intervals corresponding to one original range and role.
2533
+ *
2534
+ * @param start - Inclusive original UTF-8 byte boundary.
2535
+ * @param end - Exclusive original UTF-8 byte boundary.
2536
+ * @param role - Frontend correspondence role, matched exactly for projected input.
2537
+ * @returns Deduplicated UTF-16 intervals. Independent scripts receive only contained ranges.
2538
+ * Their ranges are excluded from the main buffer. Unmapped projected ranges produce an empty
2539
+ * list.
2540
+ * @throws If either original byte boundary is invalid.
2541
+ */
2542
+ targets(start, end, role) {
2543
+ const a = byteToUtf16(this.#original, start);
2544
+ const b = byteToUtf16(this.#original, end);
2545
+ if (this.buffer.region) return a >= this.buffer.region.start && b <= this.buffer.region.end ? [[a - this.buffer.region.start, b - this.buffer.region.start]] : [];
2546
+ if (this.source.checkerBuffers?.some((buffer) => buffer.region && a >= buffer.region.start && b <= buffer.region.end)) return [];
2547
+ if (this.source.kind === "direct") return [[a, b]];
2548
+ return [...new Map((this.source.checkerSpans ?? []).filter((span) => span.start === start && span.end === end && span.role === role).map((span) => [`${span.projectedStart}:${span.projectedEnd}`, [span.projectedStart, span.projectedEnd]])).values()];
2549
+ }
2550
+ /**
2551
+ * Translates an input-buffer boundary after checker edits are applied.
2552
+ *
2553
+ * @param position - UTF-16 boundary in the unedited checker buffer.
2554
+ * @param end - True for an interval end, which stays before an insertion at the same position.
2555
+ * False includes such an insertion.
2556
+ * @returns The UTF-16 boundary in final checker text. Positions should delimit preserved input
2557
+ * intervals rather than lie inside replaced text.
2558
+ */
2559
+ toShadow(position, end = false) {
2560
+ let delta = 0;
2561
+ for (const edit of this.#edits) {
2562
+ if (edit.at > position || edit.at === position && (end || edit.end > edit.at)) break;
2563
+ delta += edit.text.length - (edit.end - edit.at);
2564
+ }
2565
+ return position + delta;
2566
+ }
2567
+ /**
2568
+ * Maps a checker position back to an original document byte boundary.
2569
+ *
2570
+ * @param position - UTF-16 position in final checker text.
2571
+ * @param end - True selects the owning original range's end for positions inside generated edits.
2572
+ * False selects its start.
2573
+ * @returns An original UTF-8 byte offset, or null when a projected position has no unique known
2574
+ * correspondence.
2575
+ */
2576
+ originalOffset(position, end = false) {
2577
+ let delta = 0;
2578
+ for (const edit of this.#edits) {
2579
+ const start = edit.at + delta;
2580
+ if (position < start) break;
2581
+ if (position < start + edit.text.length) return end ? edit.original.end : edit.original.start;
2582
+ delta += edit.text.length - (edit.end - edit.at);
2583
+ }
2584
+ const generated = position - delta;
2585
+ const original = this.buffer.region ? generated + this.buffer.region.start : this.source.kind === "direct" ? generated : this.#points.get(generated);
2586
+ return original === void 0 || original === null ? null : new TextEncoder().encode(this.#original.slice(0, original)).length;
2587
+ }
2588
+ };
2589
+ /**
2590
+ * Collects exact projection points for mapping checker diagnostics back to a document.
2591
+ *
2592
+ * @param source - Prepared source with its original text and any Volar or version 3 projection map.
2593
+ * @returns Generated UTF-16 positions mapped to original UTF-16 positions. Conflicting points map
2594
+ * to null. Direct sources produce an empty map because their offsets are translated directly.
2595
+ * @throws If a version 3 projection map cannot be decoded.
2596
+ */
2597
+ function projectionPoints(source) {
2598
+ const points = /* @__PURE__ */ new Map();
2599
+ /**
2600
+ * Records a projection point and keeps conflicting mappings ambiguous.
2601
+ * @param generated - UTF-16 offset in the generated checker source.
2602
+ * @param original - Corresponding UTF-16 offset in the original document.
2603
+ */
2604
+ const add = (generated, original) => {
2605
+ if (points.has(generated) && points.get(generated) !== original) points.set(generated, null);
2606
+ else points.set(generated, original);
2607
+ };
2608
+ if (source.kind === "direct") return points;
2609
+ const map = source.projection.map;
2610
+ if (map.kind === "volar") for (const entry of map.mappings) for (let i = 0; i < entry.sourceOffsets.length; i++) {
2611
+ const length = entry.generatedLengths?.[i] ?? entry.lengths[i];
2612
+ add(entry.generatedOffsets[i], entry.sourceOffsets[i]);
2613
+ if (length === entry.lengths[i]) for (let j = 1; j < length; j++) add(entry.generatedOffsets[i] + j, entry.sourceOffsets[i] + j);
2614
+ }
2615
+ else {
2616
+ /**
2617
+ * Builds line starts for converting source-map columns to offsets.
2618
+ * @param text - Original or generated text whose LF characters delimit lines.
2619
+ * @returns Ordered UTF-16 offsets, beginning with zero and including the position after every LF.
2620
+ */
2621
+ const lines = (text) => [0, ...[...text.matchAll(/\n/g)].map((match) => match.index + 1)];
2622
+ const generated = lines(source.projection.code);
2623
+ const original = lines(source.document.code);
2624
+ const trace = new TraceMap(map.json);
2625
+ const selected = trace.sources.indexOf(map.source);
2626
+ for (const [line, segments] of decodedMappings(trace).entries()) for (const segment of segments) if (segment.length >= 4 && segment[1] === selected) add(generated[line] + segment[0], original[segment[2]] + segment[3]);
2627
+ }
2628
+ return points;
2629
+ }
2630
+ /**
2631
+ * Encodes identity JSON as an unpadded base64url key.
2632
+ * @param text - Serialized identity text encoded as UTF-8 before base64 conversion.
2633
+ * @returns Base64 with URL-safe characters and no trailing padding.
2634
+ */
2635
+ function base64url(text) {
2636
+ return btoa(String.fromCharCode(...new TextEncoder().encode(text))).replaceAll("+", "-").replaceAll("/", "_").replace(/=+/, "");
2637
+ }
2638
+ /**
2639
+ * Finds the next token start after whitespace and comments.
2640
+ * @param text - Checker call text to scan.
2641
+ * @param offset - UTF-16 position at which scanning starts.
2642
+ * @returns UTF-16 start of the next token, or text.length at end of input.
2643
+ */
2644
+ function skipTrivia(text, offset) {
2645
+ const scanner = ts.createScanner(ts.ScriptTarget.Latest, true);
2646
+ scanner.setText(text);
2647
+ scanner.resetTokenState(offset);
2648
+ scanner.scan();
2649
+ return scanner.getTokenStart();
2650
+ }
2651
+ // src/editor/previews.ts
2652
+ /** Captures compiler input plans and assembles their required declaration previews. */
2653
+ var GeneratedPreviews = class {
2654
+ /** Fingerprint of original buffers, capture revisions, and resolved graph dependencies. */
2655
+ revision;
2656
+ /** Captures and original UTF-16 sites, keyed by full compiler module identity. */
2657
+ #modules = /* @__PURE__ */ new Map();
2658
+ /** Declaration and style-call sites keyed by semantic identity, including imported values. */
2659
+ #declarations = /* @__PURE__ */ new Map();
2660
+ /**
2661
+ * Captures the graph's known modules together so their display names share one table.
2662
+ * Unknown modules are skipped.
2663
+ * Dependency previews require their declaration modules to be present in the graph.
2664
+ *
2665
+ * @param graph - Original buffers and dependencies for the source revisions to capture.
2666
+ * @param session - Session whose analyses for modules match the supplied buffers. Captures remain
2667
+ * usable after later session updates. Published sites are readonly.
2668
+ * @param modules - Module IDs successfully compiled from these buffers. Other retained analyses are skipped.
2669
+ * @throws If a captured UTF-8 range is invalid for its original buffer.
2670
+ */
2671
+ constructor(graph, session, modules) {
2672
+ const revisions = [];
2673
+ const captures = new Map(session.editorModules([...modules]).map((editor) => [editor.moduleId(), editor]));
2674
+ for (const source of graph.sources) {
2675
+ const editor = captures.get(source.moduleId);
2676
+ revisions.push(source.moduleId, fingerprint(source.document.code), editor?.revision() ?? "");
2677
+ if (!editor) continue;
2678
+ const sites = editor.sites().map((native) => ({
2679
+ native,
2680
+ start: byteToUtf16(source.document.code, native.start),
2681
+ end: byteToUtf16(source.document.code, native.end)
2682
+ }));
2683
+ this.#modules.set(source.moduleId, {
2684
+ editor,
2685
+ sites
2686
+ });
2687
+ for (const { native } of sites) if (native.identity) this.#declarations.set(identityKey(native.identity), native);
2688
+ }
2689
+ this.revision = fingerprint(JSON.stringify([revisions, graph.dependencies]));
2690
+ }
2691
+ /**
2692
+ * Finds the occurrences captured for one compiler module.
2693
+ *
2694
+ * @param source - Prepared source whose full module identity selects the capture.
2695
+ * @returns Occurrences in compiler traversal order, or an empty list for an unknown module.
2696
+ * The array and its entries are readonly and shared with this capture.
2697
+ */
2698
+ sites(source) {
2699
+ return this.#modules.get(source.moduleId)?.sites ?? [];
2700
+ }
2701
+ /**
2702
+ * Finds a literal at the half-open original UTF-16 range `[start, end)`.
2703
+ * The range may address the literal content or include its one-character delimiters.
2704
+ *
2705
+ * @param source - Prepared source whose full module identity selects the capture.
2706
+ * @param start - Inclusive original UTF-16 offset of the content or opening delimiter.
2707
+ * @param end - Exclusive original UTF-16 offset of the content or closing delimiter.
2708
+ * @returns A shared occurrence with an input context, or undefined when no range matches exactly.
2709
+ */
2710
+ input(source, start, end) {
2711
+ for (const site of this.sites(source)) if (site.native.context && (site.start === start && site.end === end || site.start === start + 1 && site.end === end - 1)) return site;
2712
+ }
2713
+ /**
2714
+ * Renders a replacement for the whole captured input while retaining its compiler conditions.
2715
+ * The result contains only that plan's CSS. Dependency assembly is handled by `preview`.
2716
+ *
2717
+ * @param source - Prepared source whose full module identity selects the capture.
2718
+ * @param start - Inclusive original UTF-8 byte offset of the captured input, taken from
2719
+ * `PreviewSite.native.start`.
2720
+ * @param candidate - Decoded replacement text without enclosing group variants.
2721
+ * @returns CSS for that plan, or undefined for an unknown module or input, failed emission,
2722
+ * or output with no CSS. Captured plans and shared generated names remain unchanged.
2723
+ */
2724
+ previewInput(source, start, candidate) {
2725
+ return this.#modules.get(source.moduleId)?.editor.previewInput(start, candidate) ?? void 0;
2726
+ }
2727
+ /**
2728
+ * Assembles a captured declaration or style call addressed by its semantic identity.
2729
+ * Imported aliases reuse that identity.
2730
+ *
2731
+ * @param identity - Full native declaration identity, including original UTF-8 ranges.
2732
+ * @returns The preview assembled by `preview`, or undefined when the identity is absent
2733
+ * or its declaration and dependencies cannot supply valid, nonempty CSS.
2734
+ */
2735
+ previewIdentity(identity) {
2736
+ const site = this.#declarations.get(identityKey(identity));
2737
+ return site ? this.preview(site) : void 0;
2738
+ }
2739
+ /**
2740
+ * Assembles `site` and its dependencies from this capture batch. Composed styles precede
2741
+ * the site's CSS, and global definitions follow it. Each dependency identity is visited once.
2742
+ * Identical CSS parts and runtime expression text are deduplicated in traversal order.
2743
+ *
2744
+ * @param site - Occurrence from this instance's capture batch. Its generated names must share
2745
+ * the declaration captures' name table.
2746
+ * @returns CSS and runtime key expressions, or undefined if any required site is missing or
2747
+ * invalid, or if the assembled CSS is empty. The site and declaration captures remain unchanged.
2748
+ */
2749
+ preview(site) {
2750
+ const parts = [];
2751
+ const runtimeNames = /* @__PURE__ */ new Set();
2752
+ const seen = /* @__PURE__ */ new Set();
2753
+ /**
2754
+ * Appends valid output and dependency expressions to the shared accumulators.
2755
+ * A false result can leave partial entries, which the outer query discards on failure.
2756
+ *
2757
+ * @param site - Occurrence from the same capture batch as its dependency declarations.
2758
+ * @returns Whether the occurrence and every newly visited dependency are valid and present.
2759
+ */
2760
+ const collect = (site) => {
2761
+ if (!site.valid) return false;
2762
+ const dependencies = site.dependencies.flatMap((identity) => {
2763
+ const key = identityKey(identity);
2764
+ if (seen.has(key)) return [];
2765
+ seen.add(key);
2766
+ return [{
2767
+ identity,
2768
+ site: this.#declarations.get(key)
2769
+ }];
2770
+ });
2771
+ for (const dependency of dependencies.filter((item) => item.identity.kind === "style")) if (!dependency.site || !collect(dependency.site)) return false;
2772
+ if (site.css) parts.push(site.css);
2773
+ for (const name of site.runtimeNames) runtimeNames.add(name);
2774
+ for (const dependency of dependencies.filter((item) => item.identity.kind !== "style")) if (!dependency.site || !collect(dependency.site)) return false;
2775
+ return true;
2776
+ };
2777
+ if (!collect(site)) return;
2778
+ const css = [...new Set(parts)].join("\n");
2779
+ return css ? {
2780
+ css,
2781
+ runtimeNames: [...runtimeNames]
2782
+ } : void 0;
2783
+ }
2784
+ };
2785
+ // src/editor/source/bindings.ts
2786
+ /**
2787
+ * Resolves declaration identities and original ranges in a fixed source graph.
2788
+ */
2789
+ var SourceBindings = class {
2790
+ /** In-memory files keyed by checker filename with slash separators and preserved casing. */
2791
+ files = /* @__PURE__ */ new Map();
2792
+ /** Producers keyed first by module identity, then by `start:end` in original UTF-16 coordinates. */
2793
+ #assets = /* @__PURE__ */ new Map();
2794
+ /** Comments with `swlint-*` directives keyed by module identity, from each source's scan. */
2795
+ #lintComments = /* @__PURE__ */ new Map();
2796
+ /** Resolved producers and cached misses for nodes in the captured checker ASTs. */
2797
+ #nodeAssets = /* @__PURE__ */ new WeakMap();
2798
+ /** Generated UTF-16 positions mapped to original positions. Null marks conflicting origins. */
2799
+ #points = /* @__PURE__ */ new Map();
2800
+ /** Binder over the in-memory files and the graph's resolved import dependencies. */
2801
+ #checker;
2802
+ /** Symbols found in assignment or increment/decrement targets, excluded from stable aliases. */
2803
+ #mutated = /* @__PURE__ */ new Set();
2804
+ /**
2805
+ * Parses sources, scans declaration records, and binds imports without reading disk.
2806
+ *
2807
+ * @param graph - Fixed sources and resolved dependencies from one analysis. Do not mutate its sources.
2808
+ * @param session - Session used to scan those sources. Capture previews before constructing this binder.
2809
+ * @throws If source scanning or projection mapping fails.
2810
+ */
2811
+ constructor(graph, session) {
2812
+ for (const source of graph.sources) {
2813
+ const text = source.kind === "direct" ? source.document.code : source.projection.code;
2814
+ const fileName = checkerName(source.checkerFileName);
2815
+ const ast = ts.createSourceFile(fileName, text, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);
2816
+ this.files.set(fileName, {
2817
+ source,
2818
+ ast
2819
+ });
2820
+ this.#points.set(source.moduleId, projectionPoints(source));
2821
+ const scan = session.scanSource(source);
2822
+ this.#assets.set(source.moduleId, assetRanges(source.document.code, scan.kind === "ready" ? scan.summary.assets : []));
2823
+ this.#lintComments.set(source.moduleId, scan.kind === "ready" ? scan.summary.lintComments : []);
2824
+ }
2825
+ const host = {
2826
+ getSourceFile: (name) => this.files.get(checkerName(name))?.ast,
2827
+ getDefaultLibFileName: () => "lib.d.ts",
2828
+ writeFile: () => {},
2829
+ getCurrentDirectory: () => "/",
2830
+ getDirectories: () => [],
2831
+ fileExists: (name) => this.files.has(checkerName(name)),
2832
+ readFile: (name) => this.files.get(checkerName(name))?.ast.text,
2833
+ getCanonicalFileName: checkerName,
2834
+ useCaseSensitiveFileNames: () => true,
2835
+ getNewLine: () => "\n",
2836
+ resolveModuleNames: (names, containingFile) => names.map((name) => {
2837
+ const source = this.files.get(checkerName(containingFile))?.source;
2838
+ const dependency = graph.dependencies.find((item) => item.importer === source?.resolverId && item.specifier === name);
2839
+ const target = graph.sources.find((item) => item.resolverId === dependency?.id);
2840
+ return target ? {
2841
+ resolvedFileName: checkerName(target.checkerFileName),
2842
+ extension: ts.Extension.Tsx
2843
+ } : void 0;
2844
+ })
2845
+ };
2846
+ const program = ts.createProgram([...this.files.keys()], {
2847
+ noLib: true,
2848
+ allowJs: true
2849
+ }, host);
2850
+ this.#checker = program.getTypeChecker();
2851
+ for (const { ast } of this.files.values()) walk(ast, (node) => {
2852
+ const target = ts.isBinaryExpression(node) && node.operatorToken.kind >= ts.SyntaxKind.FirstAssignment && node.operatorToken.kind <= ts.SyntaxKind.LastAssignment ? node.left : (ts.isPrefixUnaryExpression(node) || ts.isPostfixUnaryExpression(node)) && [ts.SyntaxKind.PlusPlusToken, ts.SyntaxKind.MinusMinusToken].includes(node.operator) ? node.operand : void 0;
2853
+ if (target) {
2854
+ /**
2855
+ * Records symbols in assignment targets that can contain identifier bindings.
2856
+ * Property accesses do not mark their receiver as a reassigned binding.
2857
+ *
2858
+ * @param node - Identifier or supported destructuring subtree of the target.
2859
+ * Recognized symbols are added to `#mutated`, including nested pattern members.
2860
+ */
2861
+ const mark = (node) => {
2862
+ if (ts.isIdentifier(node)) {
2863
+ const symbol = this.#checker.getSymbolAtLocation(node);
2864
+ if (symbol) this.#mutated.add(symbol);
2865
+ } else if (ts.isArrayLiteralExpression(node) || ts.isObjectLiteralExpression(node) || ts.isPropertyAssignment(node) || ts.isShorthandPropertyAssignment(node) || ts.isSpreadAssignment(node) || ts.isSpreadElement(node) || ts.isParenthesizedExpression(node)) ts.forEachChild(node, mark);
2866
+ };
2867
+ mark(target);
2868
+ }
2869
+ });
2870
+ }
2871
+ /**
2872
+ * Recognizes a direct method of an imported Stillwind style producer.
2873
+ * Other property accesses with the same spelling do not establish producer authority.
2874
+ *
2875
+ * @param node - Expression in one of this index's checker ASTs.
2876
+ * @param name - Exact method spelling, such as `keyframes` or `viewTransition`.
2877
+ * @returns Whether the receiver is a supported value import of `style` and the method matches.
2878
+ */
2879
+ producer(node, name) {
2880
+ return ts.isPropertyAccessExpression(node) && node.name.text === name && this.styleImport(node.expression);
2881
+ }
2882
+ /**
2883
+ * Checks direct named imports of `style` and namespace accesses to that export.
2884
+ *
2885
+ * @param node - Expression in this index's checker ASTs. Supported imports come from
2886
+ * Stillwind's framework and vanilla entrypoints.
2887
+ * @returns Whether a value import establishes that producer. Type-only imports and symbols
2888
+ * marked as mutated fail this check.
2889
+ */
2890
+ styleImport(node) {
2891
+ const namespace = ts.isPropertyAccessExpression(node) && node.name.text === "style";
2892
+ if (!ts.isIdentifier(node) && !(namespace && ts.isIdentifier(node.expression))) return false;
2893
+ const symbol = this.#checker.getSymbolAtLocation(namespace ? node.expression : node);
2894
+ if (!symbol || this.#mutated.has(symbol)) return false;
2895
+ return !!symbol.declarations?.some((declaration) => {
2896
+ if (namespace ? !ts.isNamespaceImport(declaration) : !ts.isImportSpecifier(declaration) || (declaration.propertyName ?? declaration.name).text !== "style" || declaration.isTypeOnly) return false;
2897
+ const owner = ts.isNamespaceImport(declaration) ? declaration.parent.parent : declaration.parent.parent.parent;
2898
+ return ts.isImportDeclaration(owner) && owner.importClause?.phaseModifier !== ts.SyntaxKind.TypeKeyword && ts.isStringLiteral(owner.moduleSpecifier) && /^stillwind\/(?:alpine|astro|lit|preact|qwik|react|solid|svelte|vanilla|vue)$/.test(owner.moduleSpecifier.text);
2899
+ });
2900
+ }
2901
+ /**
2902
+ * Maps a checker node to an exact range in its original document.
2903
+ * For projections, an anchor is accepted only when the intervening and selected text match
2904
+ * the original buffer. A conflicting mapping at the node's start prevents fallback to an anchor.
2905
+ *
2906
+ * @param source - Prepared source whose checker AST contains `node`.
2907
+ * @param node - Node from this index, with leading trivia excluded from its selected range.
2908
+ * @returns Inclusive start and exclusive end in original UTF-16 coordinates, or undefined
2909
+ * when a projection cannot map the text exactly.
2910
+ */
2911
+ range(source, node) {
2912
+ const ast = node.getSourceFile();
2913
+ const start = node.getStart(ast);
2914
+ const end = node.end;
2915
+ if (source.kind === "direct") return [start, end];
2916
+ const points = this.#points.get(source.moduleId);
2917
+ const exact = points.get(start);
2918
+ const anchors = exact === void 0 ? [...points].filter(([position, original]) => position <= start && original !== null).sort((a, b) => b[0] - a[0]) : [[start, exact]];
2919
+ for (const [position, original] of anchors) {
2920
+ if (original === null || original === void 0) continue;
2921
+ const offset = original + start - position;
2922
+ if (source.document.code.slice(original, offset + end - start) === ast.text.slice(position, end)) return [offset, offset + end - start];
2923
+ }
2924
+ }
2925
+ /**
2926
+ * Resolves a native producer or an alias through stable variable initializers and imports.
2927
+ * Both successful resolutions and misses are cached for the AST node.
2928
+ *
2929
+ * @param source - Prepared source whose checker AST contains `node`.
2930
+ * @param node - Node from this index. Alias chains may reach another source in the same graph.
2931
+ * @returns A shared native record that callers must keep unchanged, or undefined when no
2932
+ * producer is found. Mutated bindings and cyclic aliases stop alias resolution.
2933
+ */
2934
+ asset(source, node) {
2935
+ if (!this.#nodeAssets.has(node)) this.#nodeAssets.set(node, this.#resolveAsset(source, node, /* @__PURE__ */ new Set()));
2936
+ return this.#nodeAssets.get(node);
2937
+ }
2938
+ /**
2939
+ * Returns the comments that contain `swlint-*` directives in `source`'s original buffer.
2940
+ *
2941
+ * @param source - Prepared source of this index.
2942
+ * @returns Comment bodies in original UTF-8 byte offsets, or an empty list when the scan
2943
+ * failed. Callers must keep the returned list unchanged.
2944
+ */
2945
+ lintComments(source) {
2946
+ return this.#lintComments.get(source.moduleId) ?? [];
2947
+ }
2948
+ /**
2949
+ * Follows a producer range or a stable alias chain without caching intermediate nodes.
2950
+ * Exact native producer records take precedence over checks on alias bindings.
2951
+ *
2952
+ * @param source - Prepared source whose checker AST contains `node`.
2953
+ * @param node - Expression to resolve, including supported TypeScript wrappers.
2954
+ * @param seen - Symbols already visited in the current chain. Visited symbols are added
2955
+ * even when resolution fails, so a separate chain needs a fresh set.
2956
+ * @returns The native record reached by the chain, or undefined for mutated, cyclic,
2957
+ * missing, or unsupported bindings.
2958
+ */
2959
+ #resolveAsset(source, node, seen) {
2960
+ const range = this.range(source, node);
2961
+ if (range) {
2962
+ const found = this.#assets.get(source.moduleId)?.get(`${range[0]}:${range[1]}`);
2963
+ if (found) return found;
2964
+ }
2965
+ if (ts.isParenthesizedExpression(node) || ts.isAsExpression(node) || ts.isSatisfiesExpression(node) || ts.isNonNullExpression(node)) return this.#resolveAsset(source, node.expression, seen);
2966
+ if (ts.isPropertyAccessExpression(node) && ts.isIdentifier(node.expression)) {
2967
+ if (!this.#checker.getSymbolAtLocation(node.expression)?.declarations?.some(ts.isNamespaceImport)) return;
2968
+ } else if (!ts.isIdentifier(node)) return;
2969
+ let symbol = this.#checker.getSymbolAtLocation(node);
2970
+ if (!symbol || this.#mutated.has(symbol) || seen.has(symbol)) return;
2971
+ seen.add(symbol);
2972
+ if (symbol.flags & ts.SymbolFlags.Alias) {
2973
+ symbol = this.#checker.getAliasedSymbol(symbol);
2974
+ if (this.#mutated.has(symbol) || seen.has(symbol)) return;
2975
+ seen.add(symbol);
2976
+ }
2977
+ const declaration = symbol.valueDeclaration;
2978
+ if (declaration && ts.isVariableDeclaration(declaration) && declaration.initializer) {
2979
+ const owner = this.files.get(declaration.getSourceFile().fileName)?.source;
2980
+ return owner ? this.#resolveAsset(owner, declaration.initializer, seen) : void 0;
2981
+ }
2982
+ }
2983
+ /**
2984
+ * Finds the smallest mapped AST node that contains an original document position.
2985
+ *
2986
+ * @param source - Prepared source whose checker filename selects a file in this index.
2987
+ * @param offset - Original UTF-16 cursor offset. Containment uses half-open ranges.
2988
+ * @returns The containing node, or undefined when the file is absent or no mapped node
2989
+ * contains the position. A position at a node's exclusive end does not select that node.
2990
+ */
2991
+ nodeAt(source, offset) {
2992
+ const file = this.files.get(checkerName(source.checkerFileName));
2993
+ let best;
2994
+ if (file) walk(file.ast, (node) => {
2995
+ const range = this.range(source, node);
2996
+ if (range && range[0] <= offset && offset < range[1] && (!best || node.end - node.pos < best.end - best.pos)) best = node;
2997
+ });
2998
+ return best;
2999
+ }
3000
+ };
3001
+ /**
3002
+ * Converts native producer call ranges with one traversal of the original source.
3003
+ *
3004
+ * @param text - Original document text that owns every producer range.
3005
+ * @param assets - Native records whose call ranges use original UTF-8 byte offsets.
3006
+ * @returns Records keyed by `start:end`, where both offsets use original UTF-16 coordinates.
3007
+ * @throws If a call boundary falls inside a UTF-8 sequence or outside the source.
3008
+ */
3009
+ function assetRanges(text, assets) {
3010
+ const offsets = [...new Set(assets.flatMap((asset) => [asset.callStart, asset.callEnd]))].sort((a, b) => a - b);
3011
+ const positions = /* @__PURE__ */ new Map();
3012
+ let byte = 0;
3013
+ let utf16 = 0;
3014
+ for (const offset of offsets) {
3015
+ while (byte < offset && utf16 < text.length) {
3016
+ const point = text.codePointAt(utf16);
3017
+ byte += point <= 127 ? 1 : point <= 2047 ? 2 : point <= 65535 ? 3 : 4;
3018
+ utf16 += point > 65535 ? 2 : 1;
3019
+ }
3020
+ if (byte !== offset) throw new Error("Invalid original UTF-8 boundary");
3021
+ positions.set(offset, utf16);
3022
+ }
3023
+ return new Map(assets.map((asset) => [`${positions.get(asset.callStart)}:${positions.get(asset.callEnd)}`, asset]));
3024
+ }
3025
+ /**
3026
+ * Provides the separator spelling used by the in-memory checker file map.
3027
+ *
3028
+ * @param name - Checker filename with either slash or backslash separators.
3029
+ * @returns The filename with slash separators. Casing and path segments remain unchanged.
3030
+ */
3031
+ function checkerName(name) {
3032
+ return name.replaceAll("\\", "/");
3033
+ }
3034
+ /**
3035
+ * Visits an AST node before its descendants in TypeScript's child order.
3036
+ *
3037
+ * @param node - Root of the subtree to traverse.
3038
+ * @param visit - Callback for each node. It must preserve the tree during traversal.
3039
+ * Returning from the callback does not skip descendants.
3040
+ * @throws If the callback throws, traversal stops and propagates that error.
3041
+ */
3042
+ function walk(node, visit) {
3043
+ visit(node);
3044
+ ts.forEachChild(node, (child) => walk(child, visit));
3045
+ }
3046
+ // src/editor/source/literal.ts
3047
+ /**
3048
+ * Decodes JS literal content while mapping every decoded position to its source spelling.
3049
+ * CR and CRLF become LF. Escaped line continuations emit no text and move the preceding
3050
+ * boundary past the continuation. The caller must compare the result with the AST's decoded text.
3051
+ *
3052
+ * @param raw - Literal content without its opening delimiter or closing delimiter/interpolation.
3053
+ * @param start - Original UTF-16 offset of the first code unit in `raw`.
3054
+ * @returns Decoded text and `text.length + 1` source boundaries, or undefined for a trailing
3055
+ * backslash, invalid hex digits, a missing Unicode brace, or a code point above U+10FFFF.
3056
+ */
3057
+ function decodeLiteral(raw, start) {
3058
+ let text = "";
3059
+ const boundaries = [start];
3060
+ for (let index = 0; index < raw.length;) {
3061
+ const begin = index;
3062
+ let value = raw[index++];
3063
+ if (value === "\\") {
3064
+ const escape = raw[index++];
3065
+ if (escape === void 0) return;
3066
+ if (escape === "\n" || escape === "\r") {
3067
+ if (escape === "\r" && raw[index] === "\n") index++;
3068
+ boundaries[boundaries.length - 1] = start + index;
3069
+ continue;
3070
+ }
3071
+ if (escape === "x" || escape === "u") {
3072
+ const brace = escape === "u" && raw[index] === "{";
3073
+ const end = brace ? raw.indexOf("}", index + 1) : index + (escape === "x" ? 2 : 4);
3074
+ const digits = raw.slice(index + (brace ? 1 : 0), end);
3075
+ if (end < index || !/^[\da-f]+$/i.test(digits)) return;
3076
+ const point = Number.parseInt(digits, 16);
3077
+ if (point > 1114111) return;
3078
+ value = String.fromCodePoint(point);
3079
+ index = end + (brace ? 1 : 0);
3080
+ } else value = {
3081
+ n: "\n",
3082
+ r: "\r",
3083
+ t: " ",
3084
+ b: "\b",
3085
+ f: "\f",
3086
+ v: "\v",
3087
+ "0": "\0"
3088
+ }[escape] ?? escape;
3089
+ } else if (value === "\r") {
3090
+ if (raw[index] === "\n") index++;
3091
+ value = "\n";
3092
+ }
3093
+ text += value;
3094
+ for (let unit = 1; unit <= value.length; unit++) boundaries.push(start + (unit === value.length ? index : begin));
3095
+ }
3096
+ return {
3097
+ text,
3098
+ boundaries
3099
+ };
3100
+ }
3101
+ // src/editor/source/inputs.ts
3102
+ /**
3103
+ * Indexes utility literals and sortable inputs in a fixed source graph.
3104
+ */
3105
+ var SourceIndex = class {
3106
+ /** Generated occurrences and replacement plans captured from the same source graph. */
3107
+ previews;
3108
+ /** Indexed literals in discovery order, with fixed source boundaries. */
3109
+ literals;
3110
+ #literals = [];
3111
+ /** Fixed direct inputs eligible for grouping, including nested containers. */
3112
+ containers;
3113
+ #containers = [];
3114
+ /** Binder and source ranges shared by all indexed inputs. */
3115
+ #bindings;
3116
+ /**
3117
+ * Captures generated previews, rescans graph sources for producer records, and binds aliases.
3118
+ * Checker ASTs use projected text when present. Editor ranges address original buffers.
3119
+ * Source scanning updates the session's source registry and can replace reports for a failed scan.
3120
+ *
3121
+ * @param graph - Original buffers and resolved dependencies for the analyzed source revisions.
3122
+ * Its prepared sources must remain unchanged while the index is used.
3123
+ * @param session - Session whose analyses for modules match these revisions. Captures are taken
3124
+ * before rescanning, and later queries use the captured plans and the in-memory ASTs.
3125
+ * @param modules - Module IDs successfully compiled from these buffers. Failed scans have no capture.
3126
+ * @throws If source transport, a projection map, or an original UTF-8 boundary is invalid.
3127
+ */
3128
+ constructor(graph, session, modules) {
3129
+ this.previews = new GeneratedPreviews(graph, session, modules);
3130
+ this.#bindings = new SourceBindings(graph, session);
3131
+ for (const { source, ast } of this.#bindings.files.values()) {
3132
+ walk(ast, (node) => {
3133
+ if (!ts.isCallExpression(node)) return;
3134
+ const asset = this.asset(source, node);
3135
+ if (asset?.identity.kind === "style" || this.#bindings.styleImport(node.expression)) {
3136
+ if (node.arguments.length > 1) this.#containers.push({
3137
+ source,
3138
+ node
3139
+ });
3140
+ for (const argument of node.arguments) this.#input(source, argument);
3141
+ return;
3142
+ }
3143
+ if (asset?.identity.kind === "keyframes" || this.#bindings.producer(node.expression, "keyframes")) {
3144
+ this.#keyframes(source, node.arguments[0]);
3145
+ return;
3146
+ }
3147
+ if (asset?.identity.kind === "viewTransition" || this.#bindings.producer(node.expression, "viewTransition")) {
3148
+ const body = node.arguments[0];
3149
+ if (body && ts.isObjectLiteralExpression(body)) for (const property of body.properties) {
3150
+ if (!ts.isPropertyAssignment(property) || ts.isComputedPropertyName(property.name)) continue;
3151
+ const name = ts.isStringLiteralLike(property.name) ? property.name.text : property.name.getText();
3152
+ if ([
3153
+ "group",
3154
+ "old",
3155
+ "new",
3156
+ "imagePair"
3157
+ ].includes(name) && ts.isStringLiteralLike(property.initializer)) this.#literal(source, property.initializer, "", "viewTransitionUtilities");
3158
+ }
3159
+ return;
3160
+ }
3161
+ if (this.#bindings.producer(node.expression, "css")) {
3162
+ const inputs = [...node.arguments];
3163
+ const options = inputs.at(-1);
3164
+ const anchored = options !== void 0 && isCssOptions(options) && options.properties.some((property) => ts.isPropertyAssignment(property) && propertyName(property) === "selector");
3165
+ if (options !== void 0 && isCssOptions(options)) {
3166
+ inputs.pop();
3167
+ for (const property of options.properties) if (ts.isPropertyAssignment(property) && propertyName(property) === "template" && ts.isStringLiteralLike(property.initializer)) this.#literal(source, property.initializer, "", "cssTemplate");
3168
+ }
3169
+ for (const input of inputs) this.#cssInput(source, input, "", anchored ? "anchoredDocument" : "document");
3170
+ return;
3171
+ }
3172
+ if (this.#bindings.producer(node.expression, "media")) {
3173
+ for (const argument of node.arguments) if (ts.isStringLiteralLike(argument)) this.#literal(source, argument, "", "mediaVariants");
3174
+ return;
3175
+ }
3176
+ if (this.asset(source, node.expression)?.identity.kind === "keyframes") {
3177
+ const options = node.arguments[0];
3178
+ if (options && ts.isStringLiteralLike(options)) this.#literal(source, options, "", "animationOptions");
3179
+ }
3180
+ });
3181
+ walk(ast, (node) => {
3182
+ if (!ts.isStringLiteralLike(node) && !ts.isTemplateLiteralToken(node)) return;
3183
+ const range = this.range(source, node);
3184
+ const site = range && this.previews.input(source, ...range);
3185
+ if (site?.native.context) this.#literal(source, node, "", site.native.context, site);
3186
+ });
3187
+ }
3188
+ this.literals = this.#literals;
3189
+ this.containers = this.#containers;
3190
+ }
3191
+ /**
3192
+ * Indexes literal frame utilities and quoted condition keys in an authored keyframes body.
3193
+ * Nested object bodies retain definition contexts. Computed properties, nonliteral frame
3194
+ * values, and missing bodies add no literals.
3195
+ *
3196
+ * @param source - Prepared source stored in this index.
3197
+ * @param node - Body in that source's checker AST, or undefined for a missing argument.
3198
+ * Recognized quoted conditions and frame utilities are appended to `literals`.
3199
+ */
3200
+ #keyframes(source, node) {
3201
+ if (!node || !ts.isObjectLiteralExpression(node)) return;
3202
+ for (const property of node.properties) {
3203
+ if (!ts.isPropertyAssignment(property) || ts.isComputedPropertyName(property.name)) continue;
3204
+ const name = ts.isStringLiteralLike(property.name) ? property.name.text : property.name.getText();
3205
+ if (name.endsWith(":") || ts.isObjectLiteralExpression(property.initializer)) {
3206
+ if (ts.isStringLiteralLike(property.name)) this.#literal(source, property.name, "", "definitionVariants");
3207
+ this.#keyframes(source, property.initializer);
3208
+ } else if (/^(?:from|to|(?:\d+(?:\.\d+)?%)(?:\s*,\s*\d+(?:\.\d+)?%)*)$/.test(name) && ts.isStringLiteralLike(property.initializer)) this.#literal(source, property.initializer, "", "keyframesFrame");
3209
+ }
3210
+ }
3211
+ /**
3212
+ * Classifies direct input syntax and bound identities without reading base bodies or CSS.
3213
+ * Arrays and objects receive a category only when all children share one non-ref category.
3214
+ *
3215
+ * @param source - Prepared source stored in this index.
3216
+ * @param node - Input or property in that source's checker AST.
3217
+ * @returns The grouping category, or a barrier for unknown, mixed, empty, or computed input.
3218
+ * Ref markers and supported projection calls share the declaration's opaque identity.
3219
+ */
3220
+ inputOrder(source, node) {
3221
+ return classifyInput(source, node, (source, node) => this.asset(source, node));
3222
+ }
3223
+ /**
3224
+ * Maps a checker node to an exact range in its original document.
3225
+ * For projections, an anchor is accepted only when the intervening and selected text match
3226
+ * the original buffer. A conflicting mapping at the node's start prevents fallback to an anchor.
3227
+ *
3228
+ * @param source - Prepared source whose checker AST contains `node`.
3229
+ * @param node - Node from this index, with leading trivia excluded from its selected range.
3230
+ * @returns Inclusive start and exclusive end in original UTF-16 coordinates, or undefined
3231
+ * when a projection cannot map the text exactly.
3232
+ */
3233
+ range(source, node) {
3234
+ return this.#bindings.range(source, node);
3235
+ }
3236
+ /**
3237
+ * Resolves a native producer or an alias through stable variable initializers and imports.
3238
+ * Both successful resolutions and misses are cached for the AST node.
3239
+ *
3240
+ * @param source - Prepared source whose checker AST contains `node`.
3241
+ * @param node - Node from this index. Alias chains may reach another source in the same graph.
3242
+ * @returns A shared native record that callers must keep unchanged, or undefined when no
3243
+ * producer is found. Mutated bindings and cyclic aliases stop alias resolution.
3244
+ */
3245
+ asset(source, node) {
3246
+ return this.#bindings.asset(source, node);
3247
+ }
3248
+ /**
3249
+ * Returns the comments that contain `swlint-*` directives in `source`'s original buffer.
3250
+ *
3251
+ * @param source - Prepared source of this index.
3252
+ * @returns Comment bodies in original UTF-8 byte offsets, or an empty list when the scan
3253
+ * failed. Callers must keep the returned list unchanged.
3254
+ */
3255
+ lintComments(source) {
3256
+ return this.#bindings.lintComments(source);
3257
+ }
3258
+ /**
3259
+ * Finds a captured expression contribution at `node` in `source`'s checker AST.
3260
+ * Exact non-input ranges take precedence; calls then try their receiver's use site.
3261
+ * Invalid sites remain identifiable.
3262
+ *
3263
+ * @param source - Prepared source whose checker AST contains `node`.
3264
+ * @param node - Expression or call in this index.
3265
+ * @returns A shared captured occurrence, or undefined for unmapped or unrecognized expressions.
3266
+ * Callers must keep the returned site unchanged.
3267
+ */
3268
+ previewSite(source, node) {
3269
+ const range = this.range(source, node);
3270
+ if (!range) return;
3271
+ const sites = this.previews.sites(source);
3272
+ const exact = sites.find((site) => site.native.kind !== "input" && site.start === range[0] && site.end === range[1]);
3273
+ if (exact || !ts.isCallExpression(node)) return exact;
3274
+ const receiver = ts.isPropertyAccessExpression(node.expression) ? node.expression.expression : node.expression;
3275
+ const receiverRange = this.range(source, receiver);
3276
+ return receiverRange ? sites.find((site) => site.native.kind === "use" && site.start === receiverRange[0] && site.end === receiverRange[1]) : void 0;
3277
+ }
3278
+ /**
3279
+ * Finds the smallest mapped AST node that contains an original document position.
3280
+ *
3281
+ * @param source - Prepared source whose checker filename selects a file in this index.
3282
+ * @param offset - Original UTF-16 cursor offset. Containment uses half-open ranges.
3283
+ * @returns The containing node, or undefined when the file is absent or no mapped node
3284
+ * contains the position. A position at a node's exclusive end does not select that node.
3285
+ */
3286
+ nodeAt(source, offset) {
3287
+ return this.#bindings.nodeAt(source, offset);
3288
+ }
3289
+ /**
3290
+ * Indexes the static utility literals of one `style.css()` input with their group keys.
3291
+ * Runtime values and computed keys add no literals.
3292
+ *
3293
+ * @param source - Prepared source stored in this index.
3294
+ * @param node - Input in that source's checker AST.
3295
+ * @param prefix - Variants of the enclosing groups, each ending in `:`.
3296
+ * @param context - Input role of the call: `anchoredDocument` when it has a `selector`
3297
+ * option, and `document` otherwise.
3298
+ */
3299
+ #cssInput(source, node, prefix, context) {
3300
+ if (ts.isStringLiteralLike(node)) {
3301
+ this.#literal(source, node, prefix, context);
3302
+ return;
3303
+ }
3304
+ if (ts.isArrayLiteralExpression(node)) {
3305
+ for (const element of node.elements) this.#cssInput(source, element, prefix, context);
3306
+ return;
3307
+ }
3308
+ if (ts.isParenthesizedExpression(node) || ts.isAsExpression(node) || ts.isSatisfiesExpression(node)) {
3309
+ this.#cssInput(source, node.expression, prefix, context);
3310
+ return;
3311
+ }
3312
+ if (ts.isObjectLiteralExpression(node)) for (const property of node.properties) {
3313
+ if (!ts.isPropertyAssignment(property) || ts.isComputedPropertyName(property.name)) continue;
3314
+ const name = propertyName(property);
3315
+ if (name === "" || name.endsWith(":")) this.#cssInput(source, property.initializer, name === ":" ? prefix : prefix + name, context);
3316
+ }
3317
+ }
3318
+ /**
3319
+ * Records literals and sortable containers in recognized direct style input syntax.
3320
+ * Arrays and both conditional branches are traversed. Logical `&&`, `||`, and `??`
3321
+ * expressions contribute only their right operand, and unrecognized syntax adds nothing.
3322
+ *
3323
+ * @param source - Prepared source whose checker AST contains `node`.
3324
+ * @param node - Input expression to inspect. Object properties ending in `:` contribute
3325
+ * their values under the accumulated group variants. The keys `""` and `":"` add no variants.
3326
+ * @param prefix - Decoded enclosing variants, including trailing colons. Nested group
3327
+ * names are appended before their literals are recorded.
3328
+ */
3329
+ #input(source, node, prefix = "") {
3330
+ if (ts.isStringLiteralLike(node)) {
3331
+ this.#literal(source, node, prefix);
3332
+ return;
3333
+ }
3334
+ if (ts.isTemplateExpression(node)) {
3335
+ this.#literal(source, node.head, prefix);
3336
+ for (const span of node.templateSpans) this.#literal(source, span.literal, prefix);
3337
+ return;
3338
+ }
3339
+ if (ts.isArrayLiteralExpression(node)) {
3340
+ this.#containers.push({
3341
+ source,
3342
+ node
3343
+ });
3344
+ for (const element of node.elements) this.#input(source, element, prefix);
3345
+ return;
3346
+ }
3347
+ if (ts.isConditionalExpression(node)) {
3348
+ this.#input(source, node.whenTrue, prefix);
3349
+ this.#input(source, node.whenFalse, prefix);
3350
+ return;
3351
+ }
3352
+ if (ts.isBinaryExpression(node) && [
3353
+ ts.SyntaxKind.AmpersandAmpersandToken,
3354
+ ts.SyntaxKind.BarBarToken,
3355
+ ts.SyntaxKind.QuestionQuestionToken
3356
+ ].includes(node.operatorToken.kind)) {
3357
+ this.#input(source, node.right, prefix);
3358
+ return;
3359
+ }
3360
+ if (ts.isParenthesizedExpression(node) || ts.isAsExpression(node) || ts.isSatisfiesExpression(node)) {
3361
+ this.#input(source, node.expression, prefix);
3362
+ return;
3363
+ }
3364
+ if (ts.isElementAccessExpression(node) || ts.isPropertyAccessExpression(node)) {
3365
+ this.#table(source, node.expression, prefix);
3366
+ return;
3367
+ }
3368
+ if (ts.isObjectLiteralExpression(node)) {
3369
+ this.#containers.push({
3370
+ source,
3371
+ node
3372
+ });
3373
+ for (const property of node.properties) {
3374
+ if (!ts.isPropertyAssignment(property) || ts.isComputedPropertyName(property.name)) continue;
3375
+ const name = ts.isStringLiteralLike(property.name) ? property.name.text : property.name.getText();
3376
+ if (name !== "" && !name.endsWith(":")) continue;
3377
+ this.#input(source, property.initializer, name === ":" ? prefix : prefix + name);
3378
+ }
3379
+ }
3380
+ }
3381
+ /**
3382
+ * Records the literal values of an array or object literal that a style input indexes.
3383
+ * Literal spreads are traversed, and keys are not utilities. A table is not a sortable
3384
+ * container, because reordering its entries would change which entry an index selects.
3385
+ *
3386
+ * @param source - Prepared source whose checker AST contains `node`.
3387
+ * @param node - Receiver of the lookup. Other receivers add nothing.
3388
+ * @param prefix - Decoded enclosing group variants, including trailing colons.
3389
+ */
3390
+ #table(source, node, prefix) {
3391
+ while (ts.isParenthesizedExpression(node) || ts.isAsExpression(node) || ts.isSatisfiesExpression(node)) node = node.expression;
3392
+ const values = ts.isArrayLiteralExpression(node) ? [...node.elements] : [];
3393
+ if (ts.isObjectLiteralExpression(node)) {
3394
+ for (const property of node.properties) if (ts.isPropertyAssignment(property)) values.push(property.initializer);
3395
+ else if (ts.isSpreadAssignment(property)) this.#table(source, property.expression, prefix);
3396
+ }
3397
+ for (const value of values) if (ts.isSpreadElement(value)) this.#table(source, value.expression, prefix);
3398
+ else if (ts.isStringLiteralLike(value)) this.#literal(source, value, prefix);
3399
+ }
3400
+ /**
3401
+ * Records decoded content and original UTF-16 boundaries for a literal in `source`'s AST.
3402
+ * A captured `site` overrides an existing entry's context and plan at the same content start.
3403
+ * Unmapped ranges or decoding that disagrees with the AST add nothing.
3404
+ *
3405
+ * @param source - Prepared source whose checker AST contains `node`.
3406
+ * @param node - String or template token whose raw spelling supplies the source boundaries.
3407
+ * @param prefix - Decoded enclosing group variants, including trailing colons.
3408
+ * @param context - Input role stored with a new entry. Defaults to ordinary utilities.
3409
+ * @param site - Optional captured input. An existing entry keeps its prefix and boundaries
3410
+ * when this site replaces its context and plan.
3411
+ */
3412
+ #literal(source, node, prefix, context = "utility", site) {
3413
+ const range = this.range(source, node);
3414
+ if (!range) return;
3415
+ const raw = source.document.code.slice(...range);
3416
+ const suffix = ts.isTemplateHead(node) || ts.isTemplateMiddle(node) ? 2 : node.isUnterminated ? 0 : 1;
3417
+ const decoded = decodeLiteral(raw.slice(1, suffix ? -suffix : void 0), range[0] + 1);
3418
+ if (decoded?.text === node.text) {
3419
+ const previous = this.#literals.find((literal) => literal.source === source && literal.boundaries[0] === decoded.boundaries[0]);
3420
+ if (previous) {
3421
+ if (site) {
3422
+ previous.context = context;
3423
+ previous.site = site;
3424
+ }
3425
+ return;
3426
+ }
3427
+ this.#literals.push({
3428
+ source,
3429
+ node,
3430
+ prefix,
3431
+ context,
3432
+ site,
3433
+ ...decoded
3434
+ });
3435
+ }
3436
+ }
3437
+ };
3438
+ /**
3439
+ * Returns the written name of a property with a literal or identifier key.
3440
+ *
3441
+ * @param property - Property assignment whose key is not computed.
3442
+ * @returns The decoded key text.
3443
+ */
3444
+ function propertyName(property) {
3445
+ return ts.isStringLiteralLike(property.name) ? property.name.text : property.name.getText();
3446
+ }
3447
+ /**
3448
+ * Recognizes the options object of `style.css()`: an object literal whose properties
3449
+ * all have the name `template` or `selector`.
3450
+ *
3451
+ * @param node - Last argument of a `style.css()` call.
3452
+ * @returns Whether the compiler reads the argument as options rather than an input.
3453
+ */
3454
+ function isCssOptions(node) {
3455
+ return ts.isObjectLiteralExpression(node) && node.properties.length > 0 && node.properties.every((property) => ts.isPropertyAssignment(property) && !ts.isComputedPropertyName(property.name) && ["template", "selector"].includes(propertyName(property)));
3456
+ }
3457
+ // src/editor/colors.ts
3458
+ /**
3459
+ * Finds a spelling with an arbitrary color that preserves the candidate's variants, importance,
3460
+ * and modifier.
3461
+ * Existing opacity modifiers remain present, so their maximum opacity can prevent a replacement.
3462
+ * The emitted color must agree with every requested component within 2/255.
3463
+ *
3464
+ * @param text - Decoded candidate without enclosing group variants. Its current color must resolve.
3465
+ * @param outer - Enclosing decoded variants, including trailing colons, used when probing colors.
3466
+ * @param color - Finite sRGB components and effective alpha. Values are clamped to 0..1.
3467
+ * @param candidates - Query for the snapshot's design system, used to validate each proposed spelling.
3468
+ * @returns Decoded replacement text without `outer`, or undefined when the original color cannot
3469
+ * resolve or no supported spelling with an arbitrary color reproduces the requested components.
3470
+ * @throws If a matching utility definition has a malformed requirement.
3471
+ */
3472
+ function colorReplacement(text, outer, color, candidates) {
3473
+ if (![
3474
+ color.red,
3475
+ color.green,
3476
+ color.blue,
3477
+ color.alpha
3478
+ ].every(Number.isFinite) || !candidates.color(outer + text)) return;
3479
+ const parts = segments(text, ":");
3480
+ const utility = parts.pop();
3481
+ const prefix = parts.length ? `${parts.join(":")}:` : "";
3482
+ const importance = utility.startsWith("!") || utility.endsWith("!") ? "!" : "";
3483
+ const [base, modifier] = segments(utility.replace(/^!|!$/g, ""), "/");
3484
+ const spellings = [];
3485
+ if (base.startsWith("[") && base.endsWith("]")) {
3486
+ const property = base.slice(1).split(":", 1)[0];
3487
+ spellings.push((value) => `[${property}:${value}]`);
3488
+ } else for (let index = base.length - 1; index > 0; index--) if (base[index] === "-") {
3489
+ const root = base.slice(0, index);
3490
+ spellings.push((value) => `${root}-[${value}]`);
3491
+ }
3492
+ const rgba = [
3493
+ color.red,
3494
+ color.green,
3495
+ color.blue,
3496
+ color.alpha
3497
+ ].map((value) => Math.min(1, Math.max(0, value)));
3498
+ const rgb = rgba.slice(0, 3).map((value) => Math.round(value * 255));
3499
+ for (const spelling of spellings) {
3500
+ /**
3501
+ * Rebuilds a color candidate with its variants, importance, and opacity modifier preserved.
3502
+ *
3503
+ * @param value - CSS color encoded for an arbitrary utility value.
3504
+ * @returns A candidate using the current spelling, without the separately supplied outer variants.
3505
+ */
3506
+ const build = (value) => `${prefix}${importance}${spelling(value)}${modifier ? `/${modifier}` : ""}`;
3507
+ const probe = candidates.color(outer + build("#ffffff"));
3508
+ if (!probe || rgba[3] > probe[3] + 1 / 255) continue;
3509
+ const alpha = probe[3] ? rgba[3] / probe[3] : 1;
3510
+ const candidate = build(alpha >= 1 ? `#${rgb.map((value) => value.toString(16).padStart(2, "0")).join("")}` : `rgb(${rgb.join("_")}_/_${Number(alpha.toFixed(4))})`);
3511
+ if (candidates.color(outer + candidate)?.every((component, index) => Math.abs(component - rgba[index]) <= 2 / 255)) return candidate;
3512
+ }
3513
+ }
3514
+ /**
3515
+ * Serializes a picker color as a CSS literal for one local reference replacement.
3516
+ *
3517
+ * @param color - Finite sRGB components and effective alpha, clamped to 0..1.
3518
+ * @returns A hex or rgb() literal, or undefined for nonfinite components.
3519
+ */
3520
+ function cssColor(color) {
3521
+ const components = [
3522
+ color.red,
3523
+ color.green,
3524
+ color.blue,
3525
+ color.alpha
3526
+ ];
3527
+ if (!components.every(Number.isFinite)) return;
3528
+ const rgba = components.map((value) => Math.min(1, Math.max(0, value)));
3529
+ const rgb = rgba.slice(0, 3).map((value) => Math.round(value * 255));
3530
+ return rgba[3] === 1 ? `#${rgb.map((value) => value.toString(16).padStart(2, "0")).join("")}` : `rgb(${rgb.join(" ")} / ${Number(rgba[3].toFixed(4))})`;
3531
+ }
3532
+ // src/editor/completion.ts
3533
+ /**
3534
+ * Converts one empty arbitrary-value placeholder into an LSP snippet.
3535
+ * @param candidate - Decoded replacement text, including enclosing variants.
3536
+ * @param source - Encodes decoded text for its source string. CSS uses the unchanged text.
3537
+ * @returns A snippet with its first tab stop inside `[]`, or undefined without a placeholder.
3538
+ */
3539
+ function completionSnippet(candidate, source = (text) => text) {
3540
+ const text = candidate.endsWith(":") ? candidate.slice(0, -1) : candidate;
3541
+ const variant = segments(text, ":").at(-1);
3542
+ const placeholder = variant.lastIndexOf("[]");
3543
+ if (placeholder < 0) return;
3544
+ const index = text.length - variant.length + placeholder;
3545
+ return `${escape(source(candidate.slice(0, index + 1)))}\${1}${escape(source(candidate.slice(index + 1)))}\${0}`;
3546
+ }
3547
+ /**
3548
+ * Converts the start of a modifiable marker's modifier into an LSP snippet.
3549
+ * @param label - Decoded marker name followed by `/`.
3550
+ * @param source - Encodes decoded text for its source string.
3551
+ * @returns A snippet that inserts `label` and selects a `name` placeholder after it.
3552
+ */
3553
+ function markerModifierSnippet(label, source = (text) => text) {
3554
+ return `${escape(source(label))}\${1:name}`;
3555
+ }
3556
+ function escape(part) {
3557
+ return part.replace(/[\\$}]/g, "\\$&");
3558
+ }
3559
+ // src/editor/source/query.ts
3560
+ /** Most catalog candidates that one completion request adds. */
3561
+ const CATALOG_COMPLETIONS = 200;
3562
+ /**
3563
+ * Answers source completion, hover, and color queries using a captured editor snapshot.
3564
+ */
3565
+ var SourceQueries = class {
3566
+ /** Checker ASTs, stable aliases, and captured emission plans for the graph's sources. */
3567
+ #index;
3568
+ /** Native design system and effective lint policy captured during construction. */
3569
+ #query;
3570
+ /** Candidate caches shared by all queries against this snapshot. */
3571
+ #candidates;
3572
+ /** Dynamic-family candidates that plugins list for completion, sorted. */
3573
+ #catalog;
3574
+ /** Plugin suggestions for editor inputs that {@link SourceQueries.prepare} loaded, keyed by input. */
3575
+ #inputCatalogs = /* @__PURE__ */ new Map();
3576
+ /** Fingerprint of captures, graph dependencies, and configuration used for lazy resolution. */
3577
+ #revision;
3578
+ /** Comments added to formatted CSS previews. Omitted fields use native defaults. */
3579
+ #annotations;
3580
+ /** Queries that include callback CSS for selected completions in this snapshot. */
3581
+ #resolved = /* @__PURE__ */ new Map();
3582
+ /** Resolves completion CSS separately from the captured compiler session. */
3583
+ #plugins;
3584
+ /**
3585
+ * Shares the snapshot's source index and candidate caches for completion, hover, and color queries.
3586
+ *
3587
+ * @param index - Fixed source graph and captured preview plans.
3588
+ * @param query - Native query for the same CSS definitions.
3589
+ * @param candidates - Candidate caches also used by sorting.
3590
+ * @param revision - Snapshot fingerprint copied into lazy completion requests.
3591
+ * @param annotations - Comments to add to CSS previews.
3592
+ * @param catalog - Plugin candidates available without callback execution.
3593
+ * @param plugins - Optional plugin runtime used for lazy suggestions and selected candidates.
3594
+ */
3595
+ constructor(index, query, candidates, revision, annotations, catalog, plugins) {
3596
+ this.#index = index;
3597
+ this.#query = query;
3598
+ this.#candidates = candidates;
3599
+ this.#revision = revision;
3600
+ this.#annotations = annotations;
3601
+ this.#catalog = catalog;
3602
+ this.#plugins = plugins;
3603
+ }
3604
+ /**
3605
+ * Loads plugin suggestions for a completion input, and callback-generated CSS for a selected
3606
+ * completion from this captured snapshot, so that a following {@link SourceQueries.query} can
3607
+ * use them. Other requests are ignored.
3608
+ *
3609
+ * @param source - Fixed source for this request, or undefined for an unknown document.
3610
+ * @param request - Editor request. A `completion` request loads the plugin suggestions for the
3611
+ * candidate at its cursor. A `resolve` request for this snapshot's revision loads CSS, once for
3612
+ * each candidate.
3613
+ * @throws If a plugin fails or the native loader rejects the generated CSS.
3614
+ */
3615
+ async prepare(source, request) {
3616
+ if (request.kind === "completion" && source && this.#plugins) {
3617
+ const input = this.#completionInput(source, request.offset);
3618
+ const partial = input && this.#catalogContext(input.literal.context) ? segments(input.literal.prefix + input.prefix, ":").pop() : "";
3619
+ if (partial && !this.#inputCatalogs.has(partial)) this.#inputCatalogs.set(partial, await this.#plugins.catalog(partial));
3620
+ }
3621
+ if (request.kind === "resolve" && request.snapshot === this.#revision && this.#plugins && !this.#resolved.has(request.candidate)) this.#resolved.set(request.candidate, new CandidateQueries(await this.#plugins.query(request.candidate)));
3622
+ }
3623
+ /**
3624
+ * Answers a source completion, hover, resolution, or color request.
3625
+ *
3626
+ * @param source - Fixed source from this query's index.
3627
+ * @param request - Request with offsets in the original UTF-16 document.
3628
+ * @param result - Empty answer for the same source. This query fills its data fields.
3629
+ * @returns The supplied answer. Queries may fill caches but do not edit source text.
3630
+ * @throws If candidate resolution, CSS formatting, or native color queries fail.
3631
+ */
3632
+ query(source, request, result) {
3633
+ if (request.kind === "resolve") {
3634
+ const literal = this.#index.literals.find((literal) => literal.source === source && literal.boundaries[0] === request.input);
3635
+ const candidates = this.#resolved.get(request.candidate) ?? this.#candidates;
3636
+ const current = literal && request.snapshot === this.#revision;
3637
+ 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;
3638
+ const marker = current ? candidates.marker(request.candidate, literal.context) : null;
3639
+ if (css || marker) {
3640
+ const formatted = css ? this.#query.formatCss(css, this.#annotations) : "";
3641
+ result.hover = {
3642
+ start: 0,
3643
+ end: 0,
3644
+ css: formatted,
3645
+ detail: css ? this.#candidates.detail(formatted) : "marker class",
3646
+ ...marker ? { documentation: markerDocumentation(marker) } : {}
3647
+ };
3648
+ }
3649
+ return result;
3650
+ }
3651
+ const tokens = this.#sourceTokens(source);
3652
+ if (request.kind === "colors") {
3653
+ result.colors = tokens.flatMap((token) => {
3654
+ if (!this.#colorInput(token.literal) || !this.#preview(token.literal, token.text)) return [];
3655
+ const color = this.#candidates.color(token.literal.prefix + token.text);
3656
+ return color ? [{
3657
+ start: token.start,
3658
+ end: token.end,
3659
+ red: color[0],
3660
+ green: color[1],
3661
+ blue: color[2],
3662
+ alpha: color[3]
3663
+ }] : [];
3664
+ });
3665
+ return result;
3666
+ }
3667
+ if (request.kind === "colorPresentation") {
3668
+ const token = tokens.find((token) => token.start === request.start && token.end === request.end);
3669
+ if (!token || !this.#colorInput(token.literal)) return result;
3670
+ const candidate = colorReplacement(token.text, token.literal.prefix, request.color, this.#candidates);
3671
+ if (candidate && this.#preview(token.literal, candidate)) result.edits = [{
3672
+ start: token.start,
3673
+ end: token.end,
3674
+ newText: escapeContent(candidate, token.literal)
3675
+ }];
3676
+ return result;
3677
+ }
3678
+ const token = tokens.find((token) => token.start <= request.offset && request.offset <= token.end);
3679
+ if (request.kind === "hover") {
3680
+ if (token) {
3681
+ const css = this.#preview(token.literal, token.text);
3682
+ const marker = this.#candidates.marker(token.literal.prefix + token.text, token.literal.context);
3683
+ if (css || marker) result.hover = {
3684
+ start: token.start,
3685
+ end: token.end,
3686
+ css: css ? this.#query.formatCss(css, this.#annotations) : "",
3687
+ ...marker ? { documentation: markerDocumentation(marker) } : {}
3688
+ };
3689
+ } else result.hover = this.#expressionPreview(source, request.offset);
3690
+ return result;
3691
+ }
3692
+ const input = this.#completionInput(source, request.offset);
3693
+ if (!input) return result;
3694
+ const { literal, start, end, prefix } = input;
3695
+ const native = this.#candidates.complete(literal.prefix + prefix, literal.context, request.snippets === true).filter(({ label, marker }) => marker || label.endsWith(":") || !literal.site || this.#preview(literal, label.slice(literal.prefix.length)));
3696
+ const known = new Set(native.map(({ label }) => label));
3697
+ result.completions = [...native, ...this.#catalogCompletions(literal.prefix + prefix, literal.context).filter((candidate) => !known.has(candidate)).map((label) => ({
3698
+ label,
3699
+ marker: false
3700
+ }))].map(({ label: candidate, marker }) => {
3701
+ const label = candidate.slice(literal.prefix.length);
3702
+ const source = (text) => escapeContent(text, literal);
3703
+ return {
3704
+ label,
3705
+ candidate,
3706
+ input: literal.boundaries[0],
3707
+ snapshot: this.#revision,
3708
+ start,
3709
+ end,
3710
+ newText: escapeContent(label, literal),
3711
+ ...marker ? { marker } : {},
3712
+ snippet: !request.snippets ? void 0 : marker && candidate.endsWith("/") ? markerModifierSnippet(label, source) : candidate.endsWith(":") ? completionSnippet(label, source) : void 0,
3713
+ retrigger: candidate.endsWith(":") || candidate.endsWith("-")
3714
+ };
3715
+ });
3716
+ return result;
3717
+ }
3718
+ /**
3719
+ * Finds formatted CSS at an original UTF-16 `offset`, walking ancestors through the first call.
3720
+ * A captured occurrence takes precedence over a declaration reached through an alias. Its
3721
+ * missing or invalid output ends the search, preventing an enclosing partial preview.
3722
+ * Without a captured occurrence, the nearest expression with a resolvable declaration supplies
3723
+ * the fallback preview and range.
3724
+ *
3725
+ * @param source - Prepared source stored in this snapshot's index.
3726
+ * @param offset - Cursor offset in the original document's UTF-16 coordinates.
3727
+ * @returns Formatted CSS and its original range, or undefined when no complete preview is available.
3728
+ * @throws If the native formatter rejects the assembled CSS.
3729
+ */
3730
+ #expressionPreview(source, offset) {
3731
+ let node = this.#index.nodeAt(source, offset);
3732
+ let reference;
3733
+ while (node) {
3734
+ const site = this.#index.previewSite(source, node);
3735
+ if (site) {
3736
+ const preview = this.#index.previews.preview(site.native);
3737
+ const range = this.#index.range(source, node);
3738
+ return preview && range ? {
3739
+ start: range[0],
3740
+ end: range[1],
3741
+ css: this.#query.formatCss(preview.css, this.#annotations),
3742
+ ...preview.runtimeNames.length ? { runtimeNames: preview.runtimeNames } : {}
3743
+ } : void 0;
3744
+ }
3745
+ if (!reference) {
3746
+ const asset = this.#index.asset(source, node);
3747
+ const preview = asset && this.#index.previews.previewIdentity(asset.identity);
3748
+ const range = this.#index.range(source, node);
3749
+ if (preview && range) reference = {
3750
+ preview,
3751
+ range
3752
+ };
3753
+ }
3754
+ if (ts.isCallExpression(node)) break;
3755
+ node = node.parent;
3756
+ }
3757
+ return reference ? {
3758
+ start: reference.range[0],
3759
+ end: reference.range[1],
3760
+ css: this.#query.formatCss(reference.preview.css, this.#annotations),
3761
+ ...reference.preview.runtimeNames.length ? { runtimeNames: reference.preview.runtimeNames } : {}
3762
+ } : void 0;
3763
+ }
3764
+ /**
3765
+ * Renders candidate text in a captured input plan or the standalone input registry.
3766
+ * A captured plan already retains those variants; a standalone query receives the prefix
3767
+ * explicitly. The original source remains unchanged.
3768
+ *
3769
+ * @param literal - Indexed literal that supplies the input role, enclosing variants, and plan.
3770
+ * @param candidate - Decoded text without the literal's enclosing group prefix.
3771
+ * @returns CSS for the replacement, or undefined for failed or unavailable emission.
3772
+ * @throws If a matching ordinary utility requirement is malformed in a standalone query.
3773
+ */
3774
+ #preview(literal, candidate) {
3775
+ if (literal.site) return this.#index.previews.previewInput(literal.source, literal.site.native.start, candidate);
3776
+ return this.#candidates.preview(literal.prefix + candidate, literal.context) ?? void 0;
3777
+ }
3778
+ /**
3779
+ * Completes dynamic-family candidates that plugins list but compilation has not defined yet.
3780
+ *
3781
+ * @param text - Decoded partial candidate, including enclosing and written variants.
3782
+ * @param context - Input role of the literal. Only utility roles complete catalog names.
3783
+ * @returns Candidates with the written variants, for names that start with the partial
3784
+ * utility, at most {@link CATALOG_COMPLETIONS} of them in catalog order.
3785
+ */
3786
+ #catalogCompletions(text, context) {
3787
+ if (!this.#catalogContext(context)) return [];
3788
+ const parts = segments(text, ":");
3789
+ const partial = parts.pop();
3790
+ if (!partial) return [];
3791
+ const variants = parts.map((part) => `${part}:`).join("");
3792
+ return [.../* @__PURE__ */ new Set([...this.#catalog, ...this.#inputCatalogs.get(partial) ?? []])].filter((name) => name.startsWith(partial)).slice(0, CATALOG_COMPLETIONS).map((name) => variants + name);
3793
+ }
3794
+ /**
3795
+ * Reports whether an input role completes plugin catalog names.
3796
+ *
3797
+ * @param context - Input role of a literal.
3798
+ * @returns Whether the role accepts utilities.
3799
+ */
3800
+ #catalogContext(context) {
3801
+ return [
3802
+ "utility",
3803
+ "document",
3804
+ "anchoredDocument"
3805
+ ].includes(context);
3806
+ }
3807
+ /**
3808
+ * Lists the utility tokens of every literal in one source.
3809
+ *
3810
+ * @param source - Captured source.
3811
+ * @returns Tokens with their literals, in literal order.
3812
+ */
3813
+ #sourceTokens(source) {
3814
+ return this.#index.literals.filter((literal) => literal.source === source).flatMap((literal) => this.#tokens(literal).map((token) => ({
3815
+ ...token,
3816
+ literal
3817
+ })));
3818
+ }
3819
+ /**
3820
+ * Finds the completion input at a cursor: the token that contains it, or an empty position in a
3821
+ * literal.
3822
+ *
3823
+ * @param source - Captured source.
3824
+ * @param offset - Original UTF-16 cursor offset.
3825
+ * @returns The literal, the replaced UTF-16 range, and the decoded text before the cursor, or
3826
+ * undefined outside every literal.
3827
+ */
3828
+ #completionInput(source, offset) {
3829
+ const token = this.#sourceTokens(source).find((token) => token.start <= offset && offset <= token.end);
3830
+ const literal = token?.literal ?? this.#index.literals.find((literal) => literal.source === source && literal.boundaries[0] <= offset && offset <= literal.boundaries.at(-1));
3831
+ if (!literal) return;
3832
+ const start = token?.start ?? offset;
3833
+ const end = token?.end ?? offset;
3834
+ const decoded = literal.boundaries.findIndex((position) => position >= offset);
3835
+ const decodedStart = literal.boundaries.indexOf(start);
3836
+ return {
3837
+ literal,
3838
+ start,
3839
+ end,
3840
+ prefix: literal.text.slice(Math.max(0, decodedStart), Math.max(0, decoded))
3841
+ };
3842
+ }
3843
+ /**
3844
+ * Allows color operations only for input roles that emit utility declarations.
3845
+ * Option and definition-prefix inputs use different value contracts.
3846
+ *
3847
+ * @param literal - Indexed literal whose context supplies the input role.
3848
+ * @returns Whether its role supports a utility candidate's concrete color and replacement.
3849
+ */
3850
+ #colorInput(literal) {
3851
+ return [
3852
+ "utility",
3853
+ "keyframesFrame",
3854
+ "viewTransitionUtilities"
3855
+ ].includes(literal.context);
3856
+ }
3857
+ /**
3858
+ * Maps whitespace-separated decoded tokens to their exact original spellings.
3859
+ *
3860
+ * @param literal - Literal with one source boundary for every decoded UTF-16 position,
3861
+ * including the end. Whitespace is recognized by JavaScript's `\S` regular expression.
3862
+ * @returns Tokens in source order, without trimming or decoding them again.
3863
+ */
3864
+ #tokens(literal) {
3865
+ return [...literal.text.matchAll(/\S+/gu)].map((match) => ({
3866
+ text: match[0],
3867
+ start: literal.boundaries[match.index],
3868
+ end: literal.boundaries[match.index + match[0].length]
3869
+ }));
3870
+ }
3871
+ };
3872
+ // src/editor/snapshot.ts
3873
+ /**
3874
+ * Runs source editor requests and sorting diagnostics against captured compiler output.
3875
+ */
3876
+ var EditorSnapshot = class {
3877
+ /** Owned source buffers and projection metadata captured before publication. */
3878
+ #sources;
3879
+ /** First fix actions from compilation reports, captured in original coordinates. */
3880
+ #fixes;
3881
+ /** Checker ASTs, stable aliases, and captured emission plans for the graph's sources. */
3882
+ #index;
3883
+ /** Native design system and effective lint policy captured during construction. */
3884
+ #query;
3885
+ /** Candidate caches shared by all queries against this snapshot. */
3886
+ #candidates;
3887
+ /** Targets for explicit sorting and sorting fixes. False disables both. */
3888
+ #sort;
3889
+ /** Effective prefer-sorted-utilities severity. Off skips its diagnostics and sorting in fixes. */
3890
+ #sortSeverity;
3891
+ /** Sorting reports cached by full compiler module identity, including empty results. */
3892
+ #reports = /* @__PURE__ */ new Map();
3893
+ /** Completion, hover, and color queries over the same captured sources. */
3894
+ #queries;
3895
+ /**
3896
+ * Captures recognized producers and compiler output for one set of source revisions.
3897
+ * Copies source metadata, dependencies, fix actions, and sorting settings before indexing them.
3898
+ * Building the source index also scans graph sources in the session.
3899
+ *
3900
+ * @param graph - Original sources, demanded dependencies, emitted CSS, and lint reports.
3901
+ * @param session - Session that compiled the graph and recognizes its producer identities.
3902
+ * @param loader - Completed design system with the same compiler options as the session.
3903
+ * @param config - Sorting targets and preview comments to capture. Effective lint policy comes
3904
+ * from the loader.
3905
+ * @param catalog - Finite plugin candidates offered without running their callbacks.
3906
+ * @param plugins - Runtime for resolving selected plugin completions without changing the session.
3907
+ * @throws If source transport, a projection map, or an original UTF-8 boundary is invalid.
3908
+ */
3909
+ constructor(graph, session, loader, config, catalog = [], plugins) {
3910
+ const inputs = structuredClone({
3911
+ sources: graph.sources,
3912
+ dependencies: graph.dependencies
3913
+ });
3914
+ this.#sources = inputs.sources;
3915
+ this.#fixes = structuredClone(graph.fixes);
3916
+ this.#index = new SourceIndex(inputs, session, graph.modules.map((module) => module.moduleId));
3917
+ this.#query = (pluginLoader(session) ?? loader).editorQuery();
3918
+ this.#candidates = new CandidateQueries(this.#query);
3919
+ const css = this.#query.lintSettings();
3920
+ this.#sort = config.sort === false ? false : {
3921
+ stringLiterals: config.sort?.stringLiterals ?? true,
3922
+ arrays: config.sort?.arrays ?? true
3923
+ };
3924
+ this.#sortSeverity = css["prefer-sorted-utilities"] ?? "off";
3925
+ const annotations = { ...config.preview };
3926
+ const revision = fingerprint(JSON.stringify([this.#index.previews.revision, config]));
3927
+ this.#queries = new SourceQueries(this.#index, this.#query, this.#candidates, revision, annotations, catalog, plugins);
3928
+ }
3929
+ /**
3930
+ * Loads plugin suggestions for a completion input, and callback-generated CSS for a selected
3931
+ * completion from this captured snapshot, so that a following {@link EditorSnapshot.query} can
3932
+ * use them. Other requests are ignored.
3933
+ *
3934
+ * @param id - Full resolver identity of the requested source.
3935
+ * @param request - Editor request. A `completion` request loads the plugin suggestions for the
3936
+ * candidate at its cursor. A `resolve` request for this snapshot's revision loads CSS, once for
3937
+ * each candidate.
3938
+ * @throws If a plugin fails or the native loader rejects the generated CSS.
3939
+ */
3940
+ async prepare(id, request) {
3941
+ const source = this.#sources.find((source) => source.resolverId === id);
3942
+ await this.#queries.prepare(source, request);
3943
+ }
3944
+ /**
3945
+ * Computes sorting diagnostics for all graph sources and caches them by module identity.
3946
+ * Effective lint severity and source suppression determine which reports are returned.
3947
+ * Compilation reports already present in the graph remain separate.
3948
+ *
3949
+ * @returns Independent copies of sorting reports for the captured sources.
3950
+ * @throws If candidate ranking fails or native report construction rejects a source URI or range.
3951
+ */
3952
+ reports() {
3953
+ for (const source of this.#sources) this.#lint(source);
3954
+ return structuredClone([...this.#reports.values()].flat());
3955
+ }
3956
+ /**
3957
+ * Queries a source by resolver identity. Unknown or unmapped positions produce no data.
3958
+ * Queries may populate caches, and returned edits leave the original document unchanged.
3959
+ *
3960
+ * @param id - Full resolver identity captured in the graph, including any query suffix.
3961
+ * @param request - Operation and positions in the original document's UTF-16 coordinate space.
3962
+ * Completion resolution must reuse the candidate, input boundary, and snapshot fingerprint.
3963
+ * @returns Data with the original source fingerprint, or undefined for an unknown source.
3964
+ * A known source with no applicable answer returns a result with the relevant field absent or empty.
3965
+ * @throws If native candidate resolution, CSS formatting, or lint suppression checks fail.
3966
+ */
3967
+ query(id, request) {
3968
+ const source = this.#sources.find((source) => source.resolverId === id);
3969
+ if (!source) return;
3970
+ const result = editorResult(source.document.code);
3971
+ if (request.kind === "definition") return {
3972
+ ...result,
3973
+ definitions: []
3974
+ };
3975
+ if (request.kind === "links") return {
3976
+ ...result,
3977
+ links: []
3978
+ };
3979
+ if (request.kind === "fixes" || request.kind === "sort") {
3980
+ const seed = request.kind === "fixes" ? uniqueEdits(this.#fixes.filter((edits) => edits.every((edit) => edit.location.uri === source.document.uri && edit.location.revision === result.revision)).flat().map((edit) => ({
3981
+ start: edit.location.startUtf16,
3982
+ end: edit.location.endUtf16,
3983
+ newText: edit.replacement
3984
+ }))) : [];
3985
+ result.edits = request.kind === "sort" || this.#sortSeverity !== "off" ? sortSource(source, this.#index, this.#candidates, this.#sort, seed, request.kind === "sort" ? request.protectedRanges?.length ? (start, end) => !request.protectedRanges.some((range) => start < range.end && range.start < end) : void 0 : (start, end) => !this.#query.lintSuppressed(source.document.code, bytes(source.document.code, start), bytes(source.document.code, end), "prefer-sorted-utilities", this.#index.lintComments(source))) : seed;
3986
+ return result;
3987
+ }
3988
+ return this.#queries.query(source, request, result);
3989
+ }
3990
+ /**
3991
+ * Computes sorting edits once and records reports through the native lint policy.
3992
+ * UTF-16 edit boundaries are converted to original UTF-8 byte ranges before reporting.
3993
+ * Empty results are cached too, and a failed computation leaves the module uncached.
3994
+ *
3995
+ * @param source - Unchanged prepared source stored in this snapshot's graph.
3996
+ * @throws If candidate ranking fails or native reporting rejects the source URI or byte ranges.
3997
+ */
3998
+ #lint(source) {
3999
+ if (this.#reports.has(source.moduleId)) return;
4000
+ const edits = this.#sortSeverity === "off" ? [] : sortSource(source, this.#index, this.#candidates, this.#sort);
4001
+ const reports = this.#query.reportSortEdits(source.document.uri, source.document.code, edits.map((edit) => ({
4002
+ start: bytes(source.document.code, edit.start),
4003
+ end: bytes(source.document.code, edit.end),
4004
+ replacement: edit.newText
4005
+ })), this.#index.lintComments(source));
4006
+ this.#reports.set(source.moduleId, reports);
4007
+ }
4008
+ };
4009
+ /**
4010
+ * Converts an original document position to the native compiler's byte coordinates.
4011
+ *
4012
+ * @param text - Original source text whose encoding supplies the byte count.
4013
+ * @param offset - UTF-16 integer offset within `text`, at a Unicode scalar boundary.
4014
+ * The caller must ensure that the offset does not split a surrogate pair.
4015
+ * @returns Number of UTF-8 bytes before that position.
4016
+ */
4017
+ function bytes(text, offset) {
4018
+ return new TextEncoder().encode(text.slice(0, offset)).length;
4019
+ }
4020
+ /**
4021
+ * Sorts the supplied array in place and greedily keeps edits that do not overlap earlier ones.
4022
+ *
4023
+ * @param edits - Edits in the same original UTF-16 coordinate space. The array is reordered by
4024
+ * start and then end. Earlier starts win, and a shorter edit wins when starts are equal.
4025
+ * @returns A new array of accepted edit objects. Touching ranges and identical zero-width
4026
+ * insertions are retained. The edit objects themselves remain unchanged.
4027
+ */
4028
+ function uniqueEdits(edits) {
4029
+ const result = [];
4030
+ for (const edit of edits.sort((a, b) => a.start - b.start || a.end - b.end)) {
4031
+ if (result.some((other) => other.start < edit.end && edit.start < other.end)) continue;
4032
+ result.push(edit);
4033
+ }
4034
+ return result;
4035
+ }
4036
+ // src/compilation/project.ts
4037
+ /** Keeps prepared sources and checker inputs between analyses of one project. */
4038
+ var CompilationProject = class {
4039
+ /** Sources keyed by normalized resolver ID. Windows paths ignore case. */
4040
+ #sources = /* @__PURE__ */ new Map();
4041
+ /** Import answers for the currently installed checker inputs. */
4042
+ #resolutions;
4043
+ /** Advances on invalidation so pending loads cannot publish old sources. */
4044
+ #revision = 0;
4045
+ /** Advances when sources or import links change so checker inputs are installed again. */
4046
+ #generation = 0;
4047
+ /** Last backend and inputs installed by this project. */
4048
+ #installed;
4049
+ /** Revision that a pending load must still match before it stores a source. */
4050
+ get revision() {
4051
+ return this.#revision;
4052
+ }
4053
+ /**
4054
+ * Finds a source prepared since its last invalidation.
4055
+ *
4056
+ * @param id - Full resolver ID. Windows path spelling may differ in case or slashes.
4057
+ * @returns The shared source, or undefined when it has not been prepared. Do not mutate it.
4058
+ */
4059
+ source(id) {
4060
+ return this.#sources.get(sourceKey(id))?.source;
4061
+ }
4062
+ /** Returns the prepared documents' original text so plugins can find candidates together. */
4063
+ texts() {
4064
+ return [...this.#sources.values()].map((record) => record.source.document.code);
4065
+ }
4066
+ /**
4067
+ * Finds the scan results for a prepared source.
4068
+ *
4069
+ * @param source - Source whose text has not changed since preparation.
4070
+ * @returns Shared scan results, or undefined when the source is not retained. Do not mutate them.
4071
+ */
4072
+ summary(source) {
4073
+ return this.#sources.get(sourceKey(source.resolverId))?.summary;
4074
+ }
4075
+ /**
4076
+ * Stores a source and its successful scan results, copying the source before retaining it.
4077
+ *
4078
+ * @param source - Source passed to the scanner.
4079
+ * @param summary - Successful scan results for that source. Do not mutate them after this call.
4080
+ * @param revision - Revision captured before loading. Defaults to the current revision.
4081
+ * Old revisions and sources already stored under the same ID have no effect.
4082
+ */
4083
+ retain(source, summary, revision = this.#revision) {
4084
+ if (revision !== this.#revision || this.#sources.has(sourceKey(source.resolverId))) return;
4085
+ source = structuredClone(source);
4086
+ this.#sources.set(sourceKey(source.resolverId), {
4087
+ source,
4088
+ summary,
4089
+ linked: false,
4090
+ resolutions: []
4091
+ });
4092
+ this.#changed();
4093
+ }
4094
+ /**
4095
+ * Loads and scans targets together, then resolves their imports through the host.
4096
+ * Analysis retries failed loads and scans so it can report each target's own error.
4097
+ *
4098
+ * @param ids - Full resolver IDs of the targets to prepare.
4099
+ * @param host - Host used by later analysis of these targets.
4100
+ * @param session - Initialized native session that will analyze the prepared sources.
4101
+ * @returns Completion of preparation. Invalidation stops old work from storing results.
4102
+ * @throws If host import resolution fails. Source loading and scan failures are left for analysis.
4103
+ */
4104
+ async prepare(ids, host, session) {
4105
+ const revision = this.#revision;
4106
+ await Promise.allSettled(ids.map((id) => this.#load(id, host, session, revision)));
4107
+ if (revision !== this.#revision) return;
4108
+ for (const record of this.#sources.values()) {
4109
+ const { source, summary } = record;
4110
+ if (record.linked) continue;
4111
+ const resolutions = await Promise.all(summary.moduleSpecifiers.map(async (specifier) => {
4112
+ const resolved = await host.resolve(specifier.source, source.resolverId, { skipSelf: true });
4113
+ if (!resolved || resolved.external) return;
4114
+ await this.#load(resolved.id, host, session, revision).catch(() => {});
4115
+ return {
4116
+ id: this.source(resolved.id)?.resolverId ?? resolved.id,
4117
+ start: specifier.start,
4118
+ end: specifier.end
4119
+ };
4120
+ }));
4121
+ if (revision !== this.#revision) return;
4122
+ record.linked = true;
4123
+ this.#setResolutions(record, resolutions.filter((value) => value !== void 0));
4124
+ }
4125
+ }
4126
+ /**
4127
+ * Removes changed sources and clears all import links and cached resolution answers.
4128
+ *
4129
+ * @param ids - One changed resolver ID or several IDs. Omission removes every source.
4130
+ * Advances the revision so pending loads cannot restore the removed sources.
4131
+ */
4132
+ invalidate(ids) {
4133
+ this.#revision++;
4134
+ if (ids === void 0) this.#sources.clear();
4135
+ else for (const id of typeof ids === "string" ? [ids] : ids) this.#sources.delete(sourceKey(id));
4136
+ for (const record of this.#sources.values()) {
4137
+ record.resolutions = [];
4138
+ if (record.checker) record.checker.resolutions = record.resolutions;
4139
+ record.linked = false;
4140
+ }
4141
+ this.#changed();
4142
+ }
4143
+ /**
4144
+ * Installs prepared checker inputs when their sources, import links, or supplied files change.
4145
+ *
4146
+ * @param backend - Backend used by later queries. Receives inputs if it supports setProjectSources.
4147
+ * @param sources - Sources requested by the current analysis, with any known import resolutions.
4148
+ * @param inputs - File overlays and ambient declarations for these sources.
4149
+ * @returns Shared checker sources in the requested order. Do not mutate them.
4150
+ * @throws If a requested source's checker environment or backend installation fails.
4151
+ * Other sources with unavailable framework dependencies are left out of the installed inputs.
4152
+ */
4153
+ install(backend, sources, inputs) {
4154
+ const requested = sources.map((source) => {
4155
+ const record = this.#sources.get(sourceKey(source.resolverId));
4156
+ if (!record) return source;
4157
+ const checker = this.#checkerSource(record);
4158
+ if (!record.linked) {
4159
+ const resolutions = new Map(record.resolutions.map((item) => [`${item.start}:${item.end}`, item]));
4160
+ for (const item of source.resolutions ?? []) {
4161
+ const target = this.source(item.id);
4162
+ if (target) resolutions.set(`${item.start}:${item.end}`, {
4163
+ ...item,
4164
+ id: target.resolverId
4165
+ });
4166
+ }
4167
+ this.#setResolutions(record, [...resolutions.values()]);
4168
+ }
4169
+ return checker;
4170
+ });
4171
+ const all = /* @__PURE__ */ new Map();
4172
+ for (const [id, record] of this.#sources) try {
4173
+ all.set(id, this.#checkerSource(record));
4174
+ } catch {}
4175
+ for (const source of requested) all.set(sourceKey(source.resolverId), source);
4176
+ if (this.#installed?.backend !== backend || this.#installed.generation !== this.#generation || !sameFiles(this.#installed.inputs?.overlayFiles, inputs?.overlayFiles) || !sameFiles(this.#installed.inputs?.ambientDeclarations, inputs?.ambientDeclarations)) {
4177
+ const inventory = [...all.values()].sort((a, b) => {
4178
+ const left = sourceKey(a.resolverId);
4179
+ const right = sourceKey(b.resolverId);
4180
+ return left < right ? -1 : left > right ? 1 : 0;
4181
+ });
4182
+ backend.setProjectSources?.(inventory, this.assets(), inputs);
4183
+ this.#installed = {
4184
+ backend,
4185
+ generation: this.#generation,
4186
+ inputs,
4187
+ sources: inventory
4188
+ };
4189
+ this.#resolutions = void 0;
4190
+ }
4191
+ return requested;
4192
+ }
4193
+ /**
4194
+ * @returns Declarations grouped by module ID. The arrays belong to the retained scans.
4195
+ */
4196
+ assets() {
4197
+ return new Map([...this.#sources.values()].map(({ source, summary }) => [source.moduleId, summary.assets]));
4198
+ }
4199
+ /**
4200
+ * Resolves imports and caches the answers until checker inputs change.
4201
+ *
4202
+ * @param backend - Backend that resolves imports. Backends without setProjectSources query only sources.
4203
+ * @param sources - Sources requested by the current analysis, with any known import resolutions.
4204
+ * @param inputs - File overlays and ambient declarations for this analysis.
4205
+ * @returns Shared maps from resolver ID to authored specifier and resolved ID. Do not mutate them.
4206
+ * @throws If checker input preparation, installation, or import resolution fails.
4207
+ */
4208
+ async resolve(backend, sources, inputs) {
4209
+ if (!backend.setProjectSources) return backend.resolveModules(sources, this.assets(), inputs);
4210
+ this.install(backend, sources, inputs);
4211
+ if (!this.#resolutions) {
4212
+ const generation = this.#generation;
4213
+ const resolutions = await backend.resolveModules(this.#installed.sources, this.assets(), inputs);
4214
+ if (generation === this.#generation) this.#resolutions = resolutions;
4215
+ return resolutions;
4216
+ }
4217
+ return this.#resolutions;
4218
+ }
4219
+ /**
4220
+ * Loads and scans one supported source unless it is already prepared.
4221
+ *
4222
+ * @param id - Full resolver ID.
4223
+ * @param host - Source loader and format metadata for this project.
4224
+ * @param session - Initialized session used to scan the source.
4225
+ * @param revision - Revision captured before loading. A newer revision discards this work.
4226
+ * @returns Completion of loading and scanning. Failed scans are not stored.
4227
+ * @throws If loading, projection, or native transport fails.
4228
+ */
4229
+ async #load(id, host, session, revision) {
4230
+ if (revision !== this.#revision || this.source(id) || host.supports?.(id) === false) return;
4231
+ const input = await loadSource(host, id);
4232
+ const source = "kind" in input ? input : await prepareSource(input);
4233
+ if (revision !== this.#revision) return;
4234
+ const scan = session.scanSource(source);
4235
+ if (scan.kind !== "failed") this.retain(source, scan.summary, revision);
4236
+ }
4237
+ /**
4238
+ * Creates a source's checker inputs once, loading any required framework declarations.
4239
+ *
4240
+ * @param record - Retained source and scan results to update.
4241
+ * @returns Shared checker inputs. Later import updates also update this object.
4242
+ * @throws If the framework checker environment cannot be prepared.
4243
+ */
4244
+ #checkerSource(record) {
4245
+ return record.checker ??= {
4246
+ ...record.source,
4247
+ ...checkerEnvironment(record.source),
4248
+ probes: record.summary.typeProbes,
4249
+ checkerSpans: record.summary.checkerSpans,
4250
+ checkerBindings: record.summary.checkerBindings,
4251
+ resolutions: record.resolutions
4252
+ };
4253
+ }
4254
+ /**
4255
+ * Replaces import links and clears cached answers when a target or range changes.
4256
+ *
4257
+ * @param record - Retained source whose links are being replaced.
4258
+ * @param resolutions - Resolved targets with original UTF-8 byte ranges.
4259
+ */
4260
+ #setResolutions(record, resolutions) {
4261
+ if (record.resolutions.length === resolutions.length && record.resolutions.every((item, index) => item.id === resolutions[index].id && item.start === resolutions[index].start && item.end === resolutions[index].end)) return;
4262
+ record.resolutions = resolutions;
4263
+ if (record.checker) record.checker.resolutions = resolutions;
4264
+ this.#changed();
4265
+ }
4266
+ /**
4267
+ * Clears import answers and marks checker inputs for installation on the next query.
4268
+ */
4269
+ #changed() {
4270
+ this.#resolutions = void 0;
4271
+ this.#generation++;
4272
+ }
4273
+ };
4274
+ /**
4275
+ * Normalizes a resolver ID for map lookups.
4276
+ *
4277
+ * @param id - Resolver ID, with either slash style for Windows paths.
4278
+ * @returns Forward slashes and, for absolute Windows paths, lowercase text.
4279
+ */
4280
+ function sourceKey(id) {
4281
+ const normalized = id.replaceAll("\\", "/");
4282
+ return /^[a-z]:\//i.test(normalized) ? normalized.toLowerCase() : normalized;
4283
+ }
4284
+ /**
4285
+ * Compares supplied file contents without depending on map order.
4286
+ *
4287
+ * @param a - First map of filenames to text. Omission means no files.
4288
+ * @param b - Second map, interpreted in the same way.
4289
+ * @returns Whether both maps contain the same filenames and text.
4290
+ */
4291
+ function sameFiles(a, b) {
4292
+ return (a?.size ?? 0) === (b?.size ?? 0) && [...a ?? []].every(([id, text]) => b?.get(id) === text);
4293
+ }
4294
+ // src/css/plugins/paths.ts
4295
+ /**
4296
+ * Lists immediate virtual children without reading the physical filesystem.
4297
+ *
4298
+ * @param files - Absolute file identities, including unsaved documents.
4299
+ * @param directory - Absolute directory whose immediate children are requested.
4300
+ * @param caseSensitive - Whether directory identity is case sensitive. Defaults to true.
4301
+ * @returns Files and inferred parent directories, each listed once.
4302
+ */
4303
+ function pluginDirectory(files, directory, caseSensitive = true) {
4304
+ const prefix = directory.replaceAll("\\", "/").replace(/\/$/, "") + "/";
4305
+ const key = (text) => caseSensitive ? text : text.toLowerCase();
4306
+ const entries = /* @__PURE__ */ new Map();
4307
+ for (const file of files.keys()) {
4308
+ const path = file.replaceAll("\\", "/");
4309
+ if (!key(path).startsWith(key(prefix))) continue;
4310
+ const tail = path.slice(prefix.length);
4311
+ const name = tail.split("/", 1)[0];
4312
+ if (name) entries.set(key(name), {
4313
+ name,
4314
+ directory: tail.includes("/")
4315
+ });
4316
+ }
4317
+ return [...entries.values()];
4318
+ }
4319
+ /**
4320
+ * Completes local script files, directory prefixes, and package dependencies.
4321
+ *
4322
+ * @param prefix - Decoded specifier before the CSS cursor.
4323
+ * @param importer - Absolute stylesheet identity.
4324
+ * @param root - Project directory whose package manifest supplies package names.
4325
+ * @param host - Text reads and immediate directory entries from the same captured host.
4326
+ * @returns Complete specifiers in lexical order. Missing files and malformed manifests omit suggestions.
4327
+ */
4328
+ async function completePluginPaths(prefix, importer, root, host) {
4329
+ const entries = /* @__PURE__ */ new Map();
4330
+ if (!prefix || prefix.startsWith(".") || prefix.startsWith("/") || /^[A-Za-z]:\//.test(prefix)) {
4331
+ const slash = prefix.lastIndexOf("/");
4332
+ const before = slash < 0 ? "./" : prefix.slice(0, slash + 1);
4333
+ const partial = slash < 0 ? prefix : prefix.slice(slash + 1);
4334
+ const children = await host.directory(resolve(dirname(importer), before)).catch(() => []);
4335
+ for (const child of children) {
4336
+ if (!child.name.startsWith(partial) || child.name === ".git" || !child.directory && (!/\.[cm]?[jt]s$/i.test(child.name) || /\.d\.[cm]?ts$/i.test(child.name))) continue;
4337
+ const specifier = before + child.name + (child.directory ? "/" : "");
4338
+ entries.set(specifier, {
4339
+ specifier,
4340
+ kind: child.directory ? "directory" : "file"
4341
+ });
4342
+ }
4343
+ }
4344
+ if (!prefix.startsWith(".") && !prefix.startsWith("/") && !/^[A-Za-z]:/.test(prefix)) {
4345
+ const packages = /* @__PURE__ */ new Set();
4346
+ for (const directory of /* @__PURE__ */ new Set([dirname(importer), root])) {
4347
+ const metadata = await host.read(join(directory, "package.json")).then(JSON.parse).catch(() => void 0);
4348
+ if (!metadata || typeof metadata !== "object") continue;
4349
+ for (const key of [
4350
+ "dependencies",
4351
+ "devDependencies",
4352
+ "peerDependencies",
4353
+ "optionalDependencies"
4354
+ ]) {
4355
+ const dependencies = metadata[key];
4356
+ if (!dependencies || typeof dependencies !== "object" || Array.isArray(dependencies)) continue;
4357
+ for (const specifier of Object.keys(dependencies)) packages.add(specifier);
4358
+ }
4359
+ }
4360
+ for (const specifier of packages) {
4361
+ if (specifier.startsWith(prefix)) entries.set(specifier, {
4362
+ specifier,
4363
+ kind: "module"
4364
+ });
4365
+ if (!prefix.startsWith(specifier + "/")) continue;
4366
+ let base = dirname(importer);
4367
+ while (true) {
4368
+ const metadata = await host.read(join(base, "node_modules", specifier, "package.json")).then(JSON.parse).catch(() => void 0);
4369
+ if (metadata && typeof metadata === "object") {
4370
+ const exports = metadata.exports;
4371
+ if (exports && typeof exports === "object" && !Array.isArray(exports)) for (const [subpath, target] of Object.entries(exports)) {
4372
+ const name = specifier + subpath.slice(1);
4373
+ if (target !== null && subpath.startsWith("./") && !subpath.includes("*") && name.startsWith(prefix)) entries.set(name, {
4374
+ specifier: name,
4375
+ kind: "module"
4376
+ });
4377
+ }
4378
+ break;
4379
+ }
4380
+ const parent = dirname(base);
4381
+ if (parent === base) break;
4382
+ base = parent;
4383
+ }
4384
+ }
4385
+ }
4386
+ return [...entries.values()].sort((a, b) => a.specifier < b.specifier ? -1 : a.specifier > b.specifier ? 1 : 0);
4387
+ }
4388
+ /**
4389
+ * Answers plugin path completion and links without loading or evaluating plugins.
4390
+ *
4391
+ * @param id - Absolute stylesheet identity inside the project root.
4392
+ * @param text - Captured original CSS, including incomplete strings.
4393
+ * @param request - Original UTF-16 editor operation.
4394
+ * @param options - Configured plugin names, project scope, resolver, and URI mapping.
4395
+ * @returns An answer for links or a selected plugin path, otherwise undefined.
4396
+ * Unresolved and configured-only names have links without targets. Their callers can suppress
4397
+ * ambiguous targets when overlapping projects disagree.
4398
+ */
4399
+ async function queryPluginPaths(id, text, request, options) {
4400
+ if (request.kind !== "completion" && request.kind !== "resolve" && request.kind !== "links") return;
4401
+ const name = relative(options.root, id);
4402
+ if (name === ".." || name.startsWith("../") || isAbsolute(name)) return;
4403
+ const encoder = new TextEncoder();
4404
+ const bytes = encoder.encode(text);
4405
+ const utf16 = (offset) => new TextDecoder().decode(bytes.subarray(0, offset)).length;
4406
+ const offset = request.kind === "completion" ? request.offset : request.kind === "resolve" ? request.input : void 0;
4407
+ const paths = stylesheetPluginPaths(text, offset === void 0 ? void 0 : encoder.encode(text.slice(0, offset)).length);
4408
+ const result = { revision: fingerprint(text) };
4409
+ const snapshot = fingerprint(JSON.stringify([
4410
+ text,
4411
+ options.root,
4412
+ options.names
4413
+ ]));
4414
+ if (request.kind === "links") {
4415
+ result.links = await Promise.all(paths.filter((path) => path.closed).map(async (path) => {
4416
+ const target = options.names.includes(path.specifier) ? void 0 : await options.host?.resolve(path.specifier, id).catch(() => void 0);
4417
+ return {
4418
+ start: utf16(path.start),
4419
+ end: utf16(path.end),
4420
+ target: target ? options.documentUri(target) : void 0
4421
+ };
4422
+ }));
4423
+ return result;
4424
+ }
4425
+ const path = paths.find((path) => path.prefix != null);
4426
+ if (!path) return;
4427
+ const prefix = path.prefix;
4428
+ const available = new Map((await options.host?.complete?.(prefix, id, options.root).catch(() => []) ?? []).map((entry) => [entry.specifier, entry]));
4429
+ for (const specifier of options.names) if (specifier.startsWith(prefix)) available.set(specifier, {
4430
+ specifier,
4431
+ kind: "module"
4432
+ });
4433
+ const detail = (entry) => options.names.includes(entry.specifier) ? "Configured plugin" : entry.kind === "directory" ? "Directory" : "Plugin module";
4434
+ if (request.kind === "resolve") {
4435
+ if (request.snapshot === snapshot && available.has(request.candidate)) result.hover = {
4436
+ start: 0,
4437
+ end: 0,
4438
+ css: "",
4439
+ detail: detail(available.get(request.candidate)),
4440
+ documentation: detail(available.get(request.candidate))
4441
+ };
4442
+ return result;
4443
+ }
4444
+ result.completions = [...available.values()].filter((entry) => entry.specifier.startsWith(prefix)).sort((a, b) => a.specifier < b.specifier ? -1 : a.specifier > b.specifier ? 1 : 0).map((entry) => ({
4445
+ start: utf16(path.start),
4446
+ end: utf16(path.end),
4447
+ label: entry.specifier,
4448
+ candidate: entry.specifier,
4449
+ input: request.offset,
4450
+ snapshot,
4451
+ newText: entry.specifier.replaceAll("\\", "\\\\").replaceAll(path.quote, "\\" + path.quote).replace(/[\n\r\f]/g, (character) => "\\" + character.charCodeAt(0).toString(16) + " ") + (path.closed ? "" : path.quote),
4452
+ detail: detail(entry),
4453
+ category: entry.kind,
4454
+ retrigger: entry.kind === "directory"
4455
+ }));
4456
+ return result;
4457
+ }
4458
+ // src/project/stylesheet-editor.ts
4459
+ /** Answers semantic CSS queries and lint fixes from one original buffer and captured design system. */
4460
+ var StylesheetEditor = class {
4461
+ /** Resolver identity of the stylesheet. */
4462
+ #id;
4463
+ /** Fingerprint of the captured stylesheet text that every report range addresses. */
4464
+ #revision;
4465
+ /** Lint reports whose primary location is this stylesheet. */
4466
+ #reports;
4467
+ /** Original buffer whose UTF-16 coordinates are exposed to callers. */
4468
+ #text;
4469
+ /** UTF-8 encoding of the original buffer used to convert native byte ranges. */
4470
+ #bytes;
4471
+ /** Query pinned to the design system captured with this buffer. */
4472
+ #query;
4473
+ /** Captured comment settings. Omitted fields use native preview defaults. */
4474
+ #preview;
4475
+ /** Fingerprint of source, design-system revision, and serialized configuration for completion resolution. */
4476
+ #snapshot;
4477
+ /** Caches variant previews and completion summaries for this buffer's captured design system. */
4478
+ #candidates;
4479
+ /** Queries that include callback CSS for selected completions in this stylesheet. */
4480
+ #resolved = /* @__PURE__ */ new Map();
4481
+ /** Finite plugin suggestions captured with this stylesheet's design system. */
4482
+ #catalog;
4483
+ /** Plugin suggestions for editor inputs that {@link StylesheetEditor.prepare} loaded, keyed by input. */
4484
+ #inputCatalogs = /* @__PURE__ */ new Map();
4485
+ /** Resolves completion CSS without changing reports or a session's used utilities. */
4486
+ #plugins;
4487
+ /**
4488
+ * Captures original text, lint reports, and query settings for one stylesheet revision.
4489
+ * Callers must load the original CSS graph before using sorting or lint fixes.
4490
+ * @param id - Resolver identity of the stylesheet.
4491
+ * @param text - Complete stylesheet text that the reports were computed from.
4492
+ * @param reports - Reports whose primary location is this stylesheet. Reports and edits are copied.
4493
+ * Use an empty array when the design system was loaded from recovered CSS.
4494
+ * @param query - Immutable design system captured for this source revision.
4495
+ * @param config - Compiler and preview settings included in completion identity.
4496
+ * @param catalog - Finite plugin candidates offered without running their callbacks.
4497
+ * @param plugins - Runtime for resolving selected plugin completions without changing used CSS.
4498
+ * @throws If reports cannot be cloned or configuration cannot be serialized.
4499
+ */
4500
+ constructor(id, text, reports, query, config = {}, catalog = [], plugins) {
4501
+ this.#id = id;
4502
+ this.#catalog = catalog;
4503
+ this.#plugins = plugins;
4504
+ this.#revision = fingerprint(text);
4505
+ this.#reports = structuredClone(reports);
4506
+ this.#text = text;
4507
+ this.#bytes = new TextEncoder().encode(text);
4508
+ this.#query = query;
4509
+ this.#candidates = new CandidateQueries(query);
4510
+ this.#preview = { ...config.preview };
4511
+ this.#snapshot = fingerprint(JSON.stringify([
4512
+ text,
4513
+ query.revision(),
4514
+ config
4515
+ ]));
4516
+ }
4517
+ /**
4518
+ * Loads plugin suggestions for a completion input, and resolves callback CSS for a selected
4519
+ * completion without changing the captured source or reports, so that a following query can
4520
+ * use them. Other requests are ignored.
4521
+ *
4522
+ * @param id - Resolver identity of the requested source. Another identity is ignored.
4523
+ * @param request - Editor request. A `completion` request, and a `resolve` request for this
4524
+ * stylesheet's completion snapshot, load the plugin suggestions for the candidate at their input.
4525
+ * A `resolve` request also loads CSS, once for each candidate. A variant completion is resolved
4526
+ * with its `:`.
4527
+ * @throws If a plugin fails or the native loader rejects the generated CSS.
4528
+ */
4529
+ async prepare(id, request) {
4530
+ if (id !== this.#id) return;
4531
+ if (this.#plugins && (request.kind === "completion" || request.kind === "resolve" && request.snapshot === this.#completionSnapshot(request.registryDirectives, request.snippets))) {
4532
+ const input = catalogInput(this.#text.slice(0, request.kind === "completion" ? request.offset : request.input));
4533
+ if (input && !this.#inputCatalogs.has(input)) this.#inputCatalogs.set(input, await this.#plugins.catalog(input));
4534
+ }
4535
+ if (request.kind === "resolve" && request.snapshot === this.#completionSnapshot(request.registryDirectives, request.snippets) && this.#plugins && !this.#resolved.has(request.candidate)) {
4536
+ const variant = this.#query.completeStylesheet(this.#text, this.#byteOffset(request.input), { catalog: this.#catalogAt(request.input) }).some((item) => item.label === request.candidate && item.variant);
4537
+ this.#resolved.set(request.candidate, await this.#plugins.query(variant && !request.candidate.endsWith(":") ? `${request.candidate}:` : request.candidate));
4538
+ }
4539
+ }
4540
+ /**
4541
+ * Answers completion, hover, definitions, colors, sorting, and lint-fix requests.
4542
+ *
4543
+ * @param id - Resolver identity of the requested source.
4544
+ * @param request - Operation in the stylesheet's original UTF-16 coordinates. Cursor offsets must
4545
+ * be character boundaries within the captured text. Resolve uses the label, input, and snapshot
4546
+ * returned by completion. Completion and resolution accept `registryDirectives` and `snippets`,
4547
+ * editor-only settings whose defaults are false. Resolve requires the same settings.
4548
+ * @returns An answer with the captured source fingerprint, or undefined for another identity.
4549
+ * Completion includes original replacement ranges. Hover includes formatted CSS or documentation
4550
+ * when the input resolves. Resolve omits hover when its snapshot or label no longer matches.
4551
+ * Fixes select each report's first action when all edits address this revision and do not overlap
4552
+ * a selected action, then sort edits by offset. Sort uses captured CSS targets independently of
4553
+ * lint reporting. Colors include original utility or reference ranges; presentations replace
4554
+ * only a currently recognized range in this buffer. Link requests return an empty array;
4555
+ * the project host resolves plugin paths.
4556
+ * @throws If a matching utility definition has a malformed requirement or CSS formatting fails.
4557
+ */
4558
+ query(id, request) {
4559
+ if (id !== this.#id) return;
4560
+ const result = { revision: this.#revision };
4561
+ if (request.kind === "definition") {
4562
+ const definition = this.#query.stylesheetDefinition(this.#text, this.#byteOffset(request.offset));
4563
+ return {
4564
+ ...result,
4565
+ definitions: definition ? [definition] : []
4566
+ };
4567
+ }
4568
+ if (request.kind === "links") return {
4569
+ ...result,
4570
+ links: []
4571
+ };
4572
+ if (request.kind === "colors" || request.kind === "colorPresentation") {
4573
+ const colors = this.#query.stylesheetColors(this.#text).map((color) => ({
4574
+ ...color,
4575
+ start: this.#utf16(color.start),
4576
+ end: this.#utf16(color.end)
4577
+ }));
4578
+ if (request.kind === "colors") result.colors = colors.map(({ candidate: _candidate, ...color }) => color);
4579
+ else {
4580
+ const color = colors.find((color) => color.start === request.start && color.end === request.end);
4581
+ if (color) {
4582
+ const newText = color.candidate ? colorReplacement(color.candidate, "", request.color, new CandidateQueries(this.#query)) : cssColor(request.color);
4583
+ if (newText) result.edits = [{
4584
+ start: color.start,
4585
+ end: color.end,
4586
+ newText
4587
+ }];
4588
+ }
4589
+ }
4590
+ return result;
4591
+ }
4592
+ if (request.kind === "completion") result.completions = this.#query.completeStylesheet(this.#text, this.#byteOffset(request.offset), {
4593
+ registryDirectives: request.registryDirectives === true,
4594
+ snippets: request.snippets === true,
4595
+ catalog: this.#catalogAt(request.offset)
4596
+ }).map((item) => ({
4597
+ start: this.#utf16(item.start),
4598
+ end: this.#utf16(item.end),
4599
+ label: item.label,
4600
+ candidate: item.label,
4601
+ newText: item.label,
4602
+ snippet: request.snippets && item.variant ? completionSnippet(item.label) : void 0,
4603
+ retrigger: item.label.endsWith(":") || !item.keyword && item.label.endsWith("-"),
4604
+ keyword: item.keyword,
4605
+ variant: item.variant,
4606
+ detail: item.detail ?? void 0,
4607
+ sortText: item.sortText ?? void 0,
4608
+ input: request.offset,
4609
+ snapshot: this.#completionSnapshot(request.registryDirectives, request.snippets)
4610
+ }));
4611
+ if (request.kind === "hover") result.hover = this.#hover(this.#text, request.offset);
4612
+ if (request.kind === "resolve" && request.snapshot === this.#completionSnapshot(request.registryDirectives, request.snippets)) {
4613
+ const item = this.#query.completeStylesheet(this.#text, this.#byteOffset(request.input), {
4614
+ registryDirectives: request.registryDirectives === true,
4615
+ snippets: request.snippets === true,
4616
+ catalog: this.#catalogAt(request.input)
4617
+ }).find((item) => item.label === request.candidate);
4618
+ if (item) {
4619
+ const query = this.#resolved.get(request.candidate) ?? this.#query;
4620
+ const start = this.#utf16(item.start);
4621
+ const text = this.#text.slice(0, start) + item.label + this.#text.slice(this.#utf16(item.end));
4622
+ const variant = item.label.endsWith(":") && !item.keyword ? new CandidateQueries(query).variant(item.label, "utility") : void 0;
4623
+ const hover = variant ? {
4624
+ start: 0,
4625
+ end: 0,
4626
+ css: this.#query.formatCss(variant, this.#preview)
4627
+ } : this.#hover(text, start + item.label.length, query);
4628
+ if (hover) result.hover = {
4629
+ ...hover,
4630
+ start: 0,
4631
+ end: 0,
4632
+ detail: this.#candidates.detail(hover.css)
4633
+ };
4634
+ }
4635
+ }
4636
+ if (request.kind === "sort") result.edits = this.#query.sortStylesheet(this.#text, request.protectedRanges?.map((range) => ({
4637
+ start: this.#byteOffset(range.start),
4638
+ end: this.#byteOffset(range.end)
4639
+ }))).map((edit) => ({
4640
+ start: this.#utf16(edit.start),
4641
+ end: this.#utf16(edit.end),
4642
+ newText: edit.replacement
4643
+ }));
4644
+ if (request.kind === "fixes") {
4645
+ const edits = [];
4646
+ for (const report of this.#reports) {
4647
+ const action = report.actions[0];
4648
+ if (!action?.edits.every((edit) => edit.location.revision === this.#revision)) continue;
4649
+ const proposed = action.edits.map((edit) => ({
4650
+ start: edit.location.startUtf16,
4651
+ end: edit.location.endUtf16,
4652
+ newText: edit.replacement
4653
+ }));
4654
+ if (proposed.some((edit) => edits.some((other) => other.start < edit.end && edit.start < other.end))) continue;
4655
+ edits.push(...proposed);
4656
+ }
4657
+ edits.sort((a, b) => a.start - b.start || a.end - b.end);
4658
+ result.edits = edits;
4659
+ }
4660
+ return result;
4661
+ }
4662
+ /**
4663
+ * Pins completion resolution to the discovery and snippet settings used for its labels.
4664
+ * @param registryDirectives - Whether the request includes registry metadata.
4665
+ * @param snippets - Whether the client supports arbitrary variant snippets.
4666
+ * @returns A fingerprint of the captured snapshot and normalized editor settings.
4667
+ */
4668
+ #completionSnapshot(registryDirectives = false, snippets = false) {
4669
+ return fingerprint(JSON.stringify([
4670
+ this.#snapshot,
4671
+ registryDirectives,
4672
+ snippets
4673
+ ]));
4674
+ }
4675
+ /**
4676
+ * Returns the plugin suggestions for the candidate before a cursor.
4677
+ * @param offset - UTF-16 character boundary within the captured text.
4678
+ * @returns The finite catalog and the suggestions that {@link StylesheetEditor.prepare} loaded
4679
+ * for the candidate's input, without duplicates.
4680
+ */
4681
+ #catalogAt(offset) {
4682
+ const input = catalogInput(this.#text.slice(0, offset));
4683
+ return [.../* @__PURE__ */ new Set([...this.#catalog, ...this.#inputCatalogs.get(input) ?? []])];
4684
+ }
4685
+ /**
4686
+ * Converts a cursor in the original buffer to the native query's byte coordinates.
4687
+ * @param offset - UTF-16 character boundary within the captured text.
4688
+ * @returns The length in UTF-8 bytes of the text before the cursor.
4689
+ */
4690
+ #byteOffset(offset) {
4691
+ return new TextEncoder().encode(this.#text.slice(0, offset)).length;
4692
+ }
4693
+ /**
4694
+ * Converts a native range boundary back to the original buffer's coordinates.
4695
+ * @param offset - UTF-8 character boundary within the captured bytes, returned by the native query.
4696
+ * @returns The UTF-16 offset at that boundary.
4697
+ */
4698
+ #utf16(offset) {
4699
+ return new TextDecoder().decode(this.#bytes.subarray(0, offset)).length;
4700
+ }
4701
+ /**
4702
+ * Queries and formats a hover against original text or a completed copy of that text.
4703
+ * @param text - CSS buffer to query, including any synthetic completion replacement.
4704
+ * @param offset - UTF-16 character boundary within `text`.
4705
+ * @returns CSS and documentation at UTF-16 boundaries in `text`, or undefined for unresolved input.
4706
+ * Theme declarations retain their native spelling because the formatter expects complete rules.
4707
+ * @throws If candidate resolution or CSS formatting fails.
4708
+ */
4709
+ #hover(text, offset, query = this.#query) {
4710
+ const encoder = new TextEncoder();
4711
+ const bytes = encoder.encode(text);
4712
+ const hover = query.hoverStylesheet(text, encoder.encode(text.slice(0, offset)).length);
4713
+ if (!hover) return;
4714
+ const css = hover.css.startsWith("--") ? hover.css : hover.css ? this.#query.formatCss(hover.css, this.#preview) : "";
4715
+ const decoder = new TextDecoder();
4716
+ return {
4717
+ start: decoder.decode(bytes.subarray(0, hover.start)).length,
4718
+ end: decoder.decode(bytes.subarray(0, hover.end)).length,
4719
+ css,
4720
+ documentation: hover.documentation || void 0
4721
+ };
4722
+ }
4723
+ };
4724
+ // src/project/options.ts
4725
+ /**
4726
+ * Selects the design-system stylesheet request.
4727
+ *
4728
+ * @param config - Compiler settings. css identifies the stylesheet.
4729
+ * @returns The authored path without resolving it. The caller applies the project root.
4730
+ * @throws If css does not supply a nonempty stylesheet path.
4731
+ */
4732
+ function cssEntrypoint(config) {
4733
+ const entry = config.css;
4734
+ if (!entry) throw new Error("Stillwind requires a CSS-first entrypoint (`css`)");
4735
+ return entry;
4736
+ }
4737
+ /**
4738
+ * Applies host defaults to settings passed to a native design-system loader.
4739
+ *
4740
+ * @param config - Shared compiler settings. Naming callbacks are passed separately to sessions.
4741
+ * @returns Native loader options. CSS evaluation supplies utility and variant definitions.
4742
+ */
4743
+ function compilerOptions(config) {
4744
+ const resolved = normalizeCompilerConfig(config);
4745
+ return {
4746
+ lint: {
4747
+ ...Object.fromEntries(Object.entries(resolved.lint.rules).map(([name, setting]) => [lintRules[name].nativeName, setting])),
4748
+ checkLibraries: typeof resolved.lint.checkLibraries === "boolean" ? resolved.lint.checkLibraries : [...resolved.lint.checkLibraries],
4749
+ checkPlugins: typeof resolved.lint.checkPlugins === "boolean" ? resolved.lint.checkPlugins : [...resolved.lint.checkPlugins]
4750
+ },
4751
+ prefix: resolved.prefix,
4752
+ tailwindPrefix: resolved.tailwindPrefix,
4753
+ themePrefix: resolved.themePrefix,
4754
+ utilityOrder: resolved.utilityOrder,
4755
+ stylesheetSort: {
4756
+ applyUtilities: resolved.sort.applyUtilities,
4757
+ applyStatements: resolved.sort.applyStatements,
4758
+ variantBlocks: resolved.sort.variantBlocks
4759
+ },
4760
+ target: resolved.target,
4761
+ classNamespace: resolved.classNamespace,
4762
+ useCssIf: resolved.useCssIf,
4763
+ namingRevision: resolved.namingRevision,
4764
+ hashLength: resolved.hashLength,
4765
+ rootFontSize: resolved.rootFontSize
4766
+ };
4767
+ }
4768
+ export { prepareSourcePlugins as A, CompilationFailure as C, attachPlugins as D, TypeFactsError as E, compileWithPlugins as O, warnRejectedNames as S, fileSourceKind as T, defaultPluginExport as _, pluginDirectory as a, analyzeModule as b, EditorSnapshot as c, withRequestedProbes as d, isStylesheet as f, PluginRuntime as g, loadEditorCssGraph as h, completePluginPaths as i, pluginLoader as k, CheckerSource as l, loadCssGraph as m, cssEntrypoint as n, queryPluginPaths as o, lintsStylesheet as p, StylesheetEditor as r, CompilationProject as s, compilerOptions as t, checkerId as u, cssBannerPrefix as v, cleanModuleId as w, compileModule as x, finalizeCss as y };
4769
+
4770
+ //# sourceMappingURL=options-BrXyddsL.js.map