@stillwind/integration 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.
Files changed (103) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +67 -2
  3. package/dist/NPM-THIRD-PARTY-LICENSES +52 -0
  4. package/dist/astro/development.d.ts +15 -0
  5. package/dist/astro/development.js +34 -0
  6. package/dist/astro/development.js.map +1 -0
  7. package/dist/astro/index.d.ts +17 -0
  8. package/dist/astro/index.js +194 -0
  9. package/dist/astro/index.js.map +1 -0
  10. package/dist/astro/middleware.d.ts +2 -0
  11. package/dist/astro/middleware.js +64 -0
  12. package/dist/astro/middleware.js.map +1 -0
  13. package/dist/binding-files-Ds5NpyVV.js +45 -0
  14. package/dist/binding-files-Ds5NpyVV.js.map +1 -0
  15. package/dist/emission-BVi5aRbb.js +520 -0
  16. package/dist/emission-BVi5aRbb.js.map +1 -0
  17. package/dist/fresh/index.d.ts +10 -0
  18. package/dist/fresh/index.js +55 -0
  19. package/dist/fresh/index.js.map +1 -0
  20. package/dist/gen-mapping-D7jFzOEh.js +559 -0
  21. package/dist/gen-mapping-D7jFzOEh.js.map +1 -0
  22. package/dist/index-DFfbZxNT.d.ts +12 -0
  23. package/dist/next/css-loader.d.ts +14 -0
  24. package/dist/next/css-loader.js +58 -0
  25. package/dist/next/css-loader.js.map +1 -0
  26. package/dist/next/index.d.ts +15 -0
  27. package/dist/next/index.js +66 -0
  28. package/dist/next/index.js.map +1 -0
  29. package/dist/node-loader-D-3Ynpy1.d.ts +19 -0
  30. package/dist/nuxt/index.d.ts +13 -0
  31. package/dist/nuxt/index.js +64 -0
  32. package/dist/nuxt/index.js.map +1 -0
  33. package/dist/plugin-C_ZFfzo2.js +2572 -0
  34. package/dist/plugin-C_ZFfzo2.js.map +1 -0
  35. package/dist/plugin-aV0zIIAe.d.ts +278 -0
  36. package/dist/plugin-mPiBLdqa.js +79 -0
  37. package/dist/plugin-mPiBLdqa.js.map +1 -0
  38. package/dist/project-BNw0nZBE.d.ts +58 -0
  39. package/dist/project-C3IH7geC.js +182 -0
  40. package/dist/project-C3IH7geC.js.map +1 -0
  41. package/dist/project-DUGu8g_L.d.ts +15 -0
  42. package/dist/rsbuild/index.d.ts +28 -0
  43. package/dist/rsbuild/index.js +77 -0
  44. package/dist/rsbuild/index.js.map +1 -0
  45. package/dist/rspack/index.d.ts +3 -0
  46. package/dist/rspack/index.js +1 -0
  47. package/dist/rules-BvKsL2at.js +91 -0
  48. package/dist/rules-BvKsL2at.js.map +1 -0
  49. package/dist/session-B9_rp9TH.d.ts +72 -0
  50. package/dist/session-DHUCQMG5.js +117 -0
  51. package/dist/session-DHUCQMG5.js.map +1 -0
  52. package/dist/source-map-loader-CBLiYaBI.d.ts +128 -0
  53. package/dist/sveltekit/handle.d.ts +13 -0
  54. package/dist/sveltekit/handle.js +16 -0
  55. package/dist/sveltekit/handle.js.map +1 -0
  56. package/dist/trace-mapping-DV_eP3r7.d.ts +58 -0
  57. package/dist/turbopack/css-loader.d.ts +15 -0
  58. package/dist/turbopack/css-loader.js +44 -0
  59. package/dist/turbopack/css-loader.js.map +1 -0
  60. package/dist/turbopack/index.d.ts +54 -0
  61. package/dist/turbopack/index.js +1 -0
  62. package/dist/turbopack/loader.d.ts +13 -0
  63. package/dist/turbopack/loader.js +70 -0
  64. package/dist/turbopack/loader.js.map +1 -0
  65. package/dist/turbopack/node-loader.d.ts +2 -0
  66. package/dist/turbopack/node-loader.js +20 -0
  67. package/dist/turbopack/node-loader.js.map +1 -0
  68. package/dist/turbopack/stillwind-turbopack.css +0 -0
  69. package/dist/vite/index.d.ts +3 -0
  70. package/dist/vite/index.js +1 -0
  71. package/dist/vite/runtime-source-map.d.ts +19 -0
  72. package/dist/vite/runtime-source-map.js +106 -0
  73. package/dist/vite/runtime-source-map.js.map +1 -0
  74. package/dist/vite/runtime.d.ts +58 -0
  75. package/dist/vite/runtime.js +90 -0
  76. package/dist/vite/runtime.js.map +1 -0
  77. package/dist/webpack/css-loader.d.ts +17 -0
  78. package/dist/webpack/css-loader.js +36 -0
  79. package/dist/webpack/css-loader.js.map +1 -0
  80. package/dist/webpack/css-map-loader.d.ts +24 -0
  81. package/dist/webpack/css-map-loader.js +43 -0
  82. package/dist/webpack/css-map-loader.js.map +1 -0
  83. package/dist/webpack/document-loader.d.ts +12 -0
  84. package/dist/webpack/document-loader.js +19 -0
  85. package/dist/webpack/document-loader.js.map +1 -0
  86. package/dist/webpack/fragment-loader.d.ts +9 -0
  87. package/dist/webpack/fragment-loader.js +23 -0
  88. package/dist/webpack/fragment-loader.js.map +1 -0
  89. package/dist/webpack/index.d.ts +3 -0
  90. package/dist/webpack/index.js +1 -0
  91. package/dist/webpack/loader.d.ts +35 -0
  92. package/dist/webpack/loader.js +199 -0
  93. package/dist/webpack/loader.js.map +1 -0
  94. package/dist/webpack/source-loader.d.ts +11 -0
  95. package/dist/webpack/source-loader.js +17 -0
  96. package/dist/webpack/source-loader.js.map +1 -0
  97. package/dist/webpack/source-map-loader.d.ts +2 -0
  98. package/dist/webpack/source-map-loader.js +35 -0
  99. package/dist/webpack/source-map-loader.js.map +1 -0
  100. package/dist/webpack/stillwind-fragment.d.ts +1 -0
  101. package/dist/webpack/stillwind-fragment.js +1 -0
  102. package/dist/webpack/stillwind-webpack.css +1 -0
  103. package/package.json +133 -3
@@ -0,0 +1,2572 @@
1
+ import { a as eachMapping, i as TraceMap, n as addSegment, r as toEncodedMap, t as GenMapping } from "./gen-mapping-D7jFzOEh.js";
2
+ import { n as buildCompilerOptions, r as warnSkippedCss, t as IntegrationSession } from "./session-DHUCQMG5.js";
3
+ import { createHash } from "node:crypto";
4
+ import { fileURLToPath, pathToFileURL } from "node:url";
5
+ import { attachPlugins, cleanModuleId, compilerModuleId, composeFrameworkSourceMap, createStylesheetResolver, cssEntrypoint, cssWithSourceMap, decodeCssSourceMap, fileSourceKind, finalizeCss, finalizeModuleWithMap, isStylesheet, loadCssGraph, moduleSourceMap, nodePluginHost, warnRejectedNames } from "@stillwind/host";
6
+ import { dirname, isAbsolute, posix, resolve } from "node:path";
7
+ import { readFile, readdir, realpath } from "node:fs/promises";
8
+ import { minifyCss } from "@stillwind/native";
9
+ import { isFileServingAllowed } from "vite";
10
+ import { cssBanners } from "stillwind/css";
11
+ import { realpathSync, watch } from "node:fs";
12
+ import { resolveIntegrationConfig } from "@stillwind/config/node";
13
+ import { prepareSource } from "@stillwind/host/projection";
14
+ import { parseSync } from "rolldown/utils";
15
+ // src/vite/module-ids.ts
16
+ /** Shared stylesheet alias resolved to the environment's development runtime or production carrier. */
17
+ const virtualCssId = "virtual:stillwind.css";
18
+ /** Resolved runtime identity recognized before registry-backed modules. */
19
+ const runtimeId = "\0stillwind:runtime";
20
+ /** Public alias used by generated producer modules to import the environment runtime. */
21
+ const runtimeSpecifier = "virtual:stillwind/runtime";
22
+ /**
23
+ * Derives a compiler identity while retaining the source identity's query or fragment suffix.
24
+ * @param root - Absolute project root used by compilerModuleId.
25
+ * @param id - Full source resolver identity.
26
+ * @returns The compiler identity of the cleaned path followed by its original suffix.
27
+ */
28
+ function sourceModuleId(root, id) {
29
+ const file = cleanModuleId(id);
30
+ return compilerModuleId(root, file) + id.slice(file.length);
31
+ }
32
+ // src/vite/chunk-styles.ts
33
+ /**
34
+ * Associates emitted CSS with a chunk and loads its stylesheets in the browser.
35
+ *
36
+ * Split parts retain manifest order and relative-base URLs resolve against the chunk. Hosts can
37
+ * request a loader for single emission when they do not deliver CSS from chunk metadata.
38
+ *
39
+ * @param project - Project with build output produced by `renderStart`.
40
+ * @param name - Vite environment name, or `undefined` for `client`.
41
+ * @param context - Build context that reads module dependencies and resolves emitted filenames.
42
+ * @param code - Rendered JavaScript for the chunk.
43
+ * @param chunk - Chunk whose modules select CSS parts and whose Vite metadata is updated.
44
+ * @param loadSingleStylesheet - Loads single emission through a browser link. Defaults to false.
45
+ * @returns JavaScript with a null map when a loader is needed, otherwise `null`.
46
+ */
47
+ function renderChunkStyles(project, name, context, code, chunk, loadSingleStylesheet = false) {
48
+ const { config, settings, inputs, moduleRegistry } = project;
49
+ const { manifest, buildCss } = project.buildOutput(name);
50
+ /**
51
+ * Records a stylesheet in the chunk's Vite metadata, creating the metadata when absent.
52
+ * @param file - Emitted asset filename without the public base prefix.
53
+ */
54
+ const attachCss = (file) => {
55
+ chunk.viteMetadata ??= {
56
+ importedCss: /* @__PURE__ */ new Set(),
57
+ importedAssets: /* @__PURE__ */ new Set(),
58
+ __modules: /* @__PURE__ */ new Set()
59
+ };
60
+ chunk.viteMetadata.importedCss.add(file);
61
+ };
62
+ if (config.emission === "split" && manifest) {
63
+ const graph = new Set(Object.keys(chunk.modules));
64
+ if (chunk.facadeModuleId) graph.add(chunk.facadeModuleId);
65
+ for (const id of graph) for (const dependency of context.getModuleInfo(id)?.importedIds ?? []) graph.add(dependency);
66
+ const ids = new Set([...graph].flatMap((id) => {
67
+ const moduleId = inputs(name).get(id)?.moduleId ?? context.getModuleInfo(id)?.meta.stillwind?.moduleId ?? (id.startsWith("\0stillwind:producer:") ? (() => {
68
+ const entry = moduleRegistry(name).get(id);
69
+ return entry?.kind === "producer" ? entry.moduleId : "";
70
+ })() : "");
71
+ return manifest.modules[moduleId] ?? [];
72
+ }));
73
+ const parts = manifest.parts.filter((part) => ids.has(part.id)).map((part) => ({
74
+ ...part,
75
+ order: manifest.parts.indexOf(part),
76
+ relative: settings.publicBase === "./" || settings.publicBase === "",
77
+ href: settings.publicBase === "./" || settings.publicBase === "" ? posix.relative(posix.dirname(chunk.fileName), part.href.slice(settings.publicBase.length)) : part.href
78
+ }));
79
+ if (parts.length) {
80
+ for (const part of manifest.parts.filter((part) => ids.has(part.id))) attachCss(part.href.slice(settings.publicBase.length));
81
+ return {
82
+ code: `${code}
83
+
84
+ /* Stillwind CSS Loader */
85
+ if (typeof document !== "undefined") {
86
+ for (const p of ${JSON.stringify(parts)}) {
87
+ const links = [...document.querySelectorAll("link[data-stillwind-part]")];
88
+ if (links.some((l) => l.dataset.stillwindPart === p.id)) {
89
+ continue;
90
+ }
91
+ const l = document.createElement("link");
92
+ l.rel = "stylesheet";
93
+ l.href = p.relative ? new URL(p.href, import.meta.url).href : p.href;
94
+ l.dataset.stillwindPart = p.id;
95
+ l.dataset.stillwindOrder = String(p.order);
96
+ document.head.insertBefore(l, links.find((e) => Number(e.dataset.stillwindOrder) > p.order) ?? null);
97
+ }
98
+ }
99
+ `,
100
+ map: null
101
+ };
102
+ }
103
+ }
104
+ if (buildCss) {
105
+ const file = context.getFileName(buildCss);
106
+ attachCss(file);
107
+ if (!loadSingleStylesheet) return null;
108
+ const relative = settings.publicBase === "./" || settings.publicBase === "";
109
+ const href = relative ? posix.relative(posix.dirname(chunk.fileName), file) : settings.publicBase + file;
110
+ return {
111
+ code: `${code}
112
+
113
+ /* Stillwind CSS Loader */
114
+ if (typeof document !== "undefined") {
115
+ const href = new URL(${JSON.stringify(href)}, ${relative ? "import.meta.url" : "document.baseURI"}).href;
116
+ if (![...document.querySelectorAll('link[rel="stylesheet"]')].some((link) => link.href === href)) {
117
+ const link = document.createElement("link");
118
+ link.rel = "stylesheet";
119
+ link.href = href;
120
+ document.head.append(link);
121
+ }
122
+ }
123
+ `,
124
+ map: null
125
+ };
126
+ }
127
+ return null;
128
+ }
129
+ // src/vite/css-minify.ts
130
+ /**
131
+ * Minifies expanded CSS and reports native parser warnings through the bundler.
132
+ * @param css - Generated CSS with valid resource URLs or resource placeholder tokens.
133
+ * @param settings - Browser targets shared with compiler generation.
134
+ * @param context - Bundler warning reporter.
135
+ * @param sourceMap - Optional v3 map for this exact input, composed into the returned map.
136
+ * @returns Minified CSS and an optional separate map without embedded source contents.
137
+ * @throws If native parsing, minification, or source-map composition fails.
138
+ */
139
+ function minifyStylesheet(css, settings, context, sourceMap) {
140
+ const result = minifyCss(css, {
141
+ filename: "stillwind.css",
142
+ targets: settings.cssTargets,
143
+ sourceMap: sourceMap !== void 0,
144
+ inputSourceMap: sourceMap,
145
+ includeSourcesContent: false
146
+ });
147
+ for (const warning of result.warnings) context.warn(warning);
148
+ return result;
149
+ }
150
+ // src/vite/file-access.ts
151
+ /**
152
+ * Checks both the requested and canonical file before a plugin reads it.
153
+ * @param id - Absolute filesystem identity, optionally with a query or fragment removed for access checks.
154
+ * @param server - Optional development server whose file-serving policy applies to both paths.
155
+ * @returns The canonical absolute path after resolving symlinks.
156
+ * @throws If the identity is invalid, either path is denied, or realpath fails.
157
+ */
158
+ async function readableFile(id, server) {
159
+ const file = cleanModuleId(id);
160
+ if (!isAbsolute(file) || file.includes("\0")) throw new Error("Stillwind requires an absolute file path");
161
+ if (server && !isFileServingAllowed(file, server)) throw new Error("Stillwind file access denied");
162
+ const canonical = await realpath(file);
163
+ if (server && !isFileServingAllowed(canonical, server)) throw new Error("Stillwind file access denied");
164
+ return canonical;
165
+ }
166
+ // src/vite/build-assets.ts
167
+ /**
168
+ * Emits referenced resource files and computes URLs relative to the CSS asset directory.
169
+ *
170
+ * Only resources referenced by `css` are emitted. References to the same readable file share one
171
+ * emitted asset within this call.
172
+ *
173
+ * @param context - Build context that emits assets and resolves their filenames.
174
+ * @param css - CSS text containing resource placeholder tokens.
175
+ * @param resources - Resolved resources indexed by placeholder token.
176
+ * @param assetsDirectory - Output directory containing the emitted CSS, using forward slashes.
177
+ * @returns Placeholder replacements containing escaped paths relative to `assetsDirectory`.
178
+ * @throws If a referenced resource cannot be read or emitted.
179
+ */
180
+ async function emitBuildResources(context, css, resources, assetsDirectory) {
181
+ const assets = /* @__PURE__ */ new Map();
182
+ const replacements = /* @__PURE__ */ new Map();
183
+ for (const [placeholder, resource] of resources) {
184
+ if (!css.includes(placeholder)) continue;
185
+ const file = await readableFile(resource.id);
186
+ let reference = assets.get(file);
187
+ if (!reference) {
188
+ reference = context.emitFile({
189
+ type: "asset",
190
+ name: file.replaceAll("\\", "/").split("/").at(-1),
191
+ source: await readFile(file)
192
+ });
193
+ assets.set(file, reference);
194
+ }
195
+ replacements.set(placeholder, JSON.stringify(posix.relative(assetsDirectory, context.getFileName(reference))).slice(1, -1));
196
+ }
197
+ return replacements;
198
+ }
199
+ /**
200
+ * Emits a stylesheet and its optional external source map with filenames derived from its content.
201
+ *
202
+ * Minification follows project settings. Source maps use public source names and are emitted beside
203
+ * the CSS asset.
204
+ *
205
+ * @param project - CSS minification settings, asset directory, and public source-map rewriting
206
+ * operations.
207
+ * @param name - Vite environment name, or `undefined` for `client`.
208
+ * @param context - Build context used to emit the CSS and map assets.
209
+ * @param text - CSS text whose resource placeholders have already been replaced.
210
+ * @param sourceMap - Serialized upstream CSS map, or `undefined` to omit a map.
211
+ * @returns The bundler reference ID of the emitted CSS asset, suitable for `getFileName`.
212
+ * @throws If CSS transformation, map decoding, or asset emission fails.
213
+ */
214
+ async function emitBuildCss(project, name, context, text, sourceMap) {
215
+ const { settings, publicSourceMap } = project;
216
+ if (settings.minifyCss) {
217
+ const result = minifyStylesheet(text, settings, context, sourceMap);
218
+ text = result.css;
219
+ sourceMap = result.sourceMap ?? void 0;
220
+ }
221
+ const hash = createHash("sha256").update(text).digest("hex").slice(0, 16);
222
+ if (sourceMap) {
223
+ sourceMap = JSON.stringify(publicSourceMap(name, sourceMap));
224
+ context.emitFile({
225
+ type: "asset",
226
+ fileName: `${settings.assetsDirectory}/stillwind-${hash}.css.map`,
227
+ source: sourceMap
228
+ });
229
+ text += `\n/*# sourceMappingURL=stillwind-${hash}.css.map */`;
230
+ }
231
+ return context.emitFile({
232
+ type: "asset",
233
+ fileName: `${settings.assetsDirectory}/stillwind-${hash}.css`,
234
+ source: text
235
+ });
236
+ }
237
+ // src/vite/emission.ts
238
+ /**
239
+ * Packs adjacent occurrences with identical ordered producer lists without moving any rule.
240
+ *
241
+ * @param parts - Native partitions in stylesheet order. Input records and source-map arrays are unchanged.
242
+ * @returns New partitions with concatenated CSS, shifted UTF-8 source-map offsets, and content hashes for merged parts.
243
+ */
244
+ function partitionStylesheet(parts) {
245
+ const output = [];
246
+ for (const part of parts) {
247
+ const previous = output.at(-1);
248
+ if (previous && JSON.stringify(previous.producers) === JSON.stringify(part.producers)) {
249
+ const byteOffset = Buffer.byteLength(previous.css);
250
+ const sourceOffset = previous.sourceMap.sources.length;
251
+ previous.sourceMap.sources.push(...part.sourceMap.sources);
252
+ previous.sourceMap.entries.push(...part.sourceMap.entries.map((entry) => ({
253
+ ...entry,
254
+ source: entry.source + sourceOffset,
255
+ generatedStart: entry.generatedStart + byteOffset,
256
+ generatedEnd: entry.generatedEnd + byteOffset
257
+ })));
258
+ previous.css += part.css;
259
+ previous.banners = cssBanners([...previous.banners, ...part.banners]);
260
+ previous.key = createHash("sha256").update(previous.css).update(JSON.stringify(previous.banners)).digest("hex");
261
+ } else output.push({
262
+ ...part,
263
+ sourceMap: {
264
+ sources: [...part.sourceMap.sources],
265
+ entries: [...part.sourceMap.entries]
266
+ }
267
+ });
268
+ }
269
+ return output;
270
+ }
271
+ // src/vite/resources.ts
272
+ /**
273
+ * Converts local resource placeholders to escaped Vite filesystem URLs.
274
+ * @param resources - Placeholder records whose files have already passed access checks.
275
+ * @returns A new map of placeholders to JSON-escaped URL contents without surrounding quotes.
276
+ */
277
+ function resourceReplacements(resources) {
278
+ return new Map([...resources].map(([placeholder, resource]) => [placeholder, JSON.stringify(resourceUrl(resource.file)).slice(1, -1)]));
279
+ }
280
+ /**
281
+ * Encodes an absolute file path as a Vite filesystem URL.
282
+ * @param file - Canonical absolute path, using either path separator spelling.
283
+ * @returns An /@fs/ URL with each path segment encoded for use in stylesheet resource requests.
284
+ */
285
+ function resourceUrl(file) {
286
+ return `/@fs/${file.replaceAll("\\", "/").split("/").map((segment) => encodeURIComponent(segment).replaceAll("'", "%27").replaceAll("(", "%28").replaceAll(")", "%29")).join("/")}`;
287
+ }
288
+ /**
289
+ * Extracts a readable identity from a bundler resolution without checking file existence or access.
290
+ * @param result - Resolution, possibly external or a file URI. Absolute external paths remain readable.
291
+ * @param description - Resource description included in failure messages.
292
+ * @returns The resolved identity, converting file URIs to filesystem paths.
293
+ * @throws If resolution is absent, an external identity is not an absolute path, or a file URI is invalid.
294
+ */
295
+ function resolvedFile(result, description) {
296
+ if (!result) throw new Error(`Cannot resolve ${description}`);
297
+ if (result.id.startsWith("file:")) return fileURLToPath(result.id);
298
+ if (!result.external || isAbsolute(result.id)) return result.id;
299
+ throw new Error(`Cannot read external ${description}: ${result.id}`);
300
+ }
301
+ /**
302
+ * Replaces recorded CSS tokens in map order without further URL escaping.
303
+ * @param css - Generated text containing resource placeholders.
304
+ * @param references - Placeholders mapped to replacement contents already escaped for CSS.
305
+ * @returns Replaced CSS. The supplied map is unchanged.
306
+ */
307
+ function resolveResources(css, references = /* @__PURE__ */ new Map()) {
308
+ for (const [placeholder, url] of references) css = css.replaceAll(placeholder, url);
309
+ return css;
310
+ }
311
+ // src/vite/build.ts
312
+ /**
313
+ * Creates production hooks that emit complete document CSS and associate it with rendered chunks.
314
+ *
315
+ * @param project - Project whose compiler hooks collect producers and initialize environment
316
+ * settings.
317
+ * @returns Hooks for stylesheet emission at render start and CSS association during chunk
318
+ * rendering.
319
+ */
320
+ function buildHooks(project) {
321
+ const { config, settings, inputs, cssForBrowser, documentPlan, compile } = project;
322
+ return {
323
+ /**
324
+ * Recovers cached producers from the completed graph and emits CSS, resources, and the
325
+ * manifest.
326
+ *
327
+ * The Vite hook context must expose the completed module graph. Recovered inputs include lazy
328
+ * modules before the stylesheet receives complete coverage.
329
+ *
330
+ * @returns A promise that resolves after build output is stored, or immediately for development
331
+ * and graphs without document CSS references.
332
+ */
333
+ async renderStart() {
334
+ if (settings.watching) return;
335
+ const name = this.environment?.name;
336
+ for (const id of this.getModuleIds()) {
337
+ const metadata = this.getModuleInfo(id)?.meta.stillwind;
338
+ if (metadata?.input !== void 0 && !inputs(name).has(metadata.id ?? id)) await compile(name, metadata.input, metadata.id ?? id, this);
339
+ if (metadata?.projection) await project.environment(name).markProjection(metadata.id ?? id);
340
+ }
341
+ const plan = await documentPlan(name, this, true);
342
+ if (![...this.getModuleIds()].some((id) => id === "\0stillwind:runtime" || id.startsWith("\0stillwind:producer:") || id.startsWith("\0stillwind:projection:"))) return;
343
+ const replacements = await emitBuildResources(this, plan.originalCss, plan.resources, settings.assetsDirectory);
344
+ const css = resolveResources(plan.originalCss, replacements);
345
+ /**
346
+ * Emits a stylesheet using this build's environment, asset directory, and map settings.
347
+ *
348
+ * @param text - Final CSS with resource placeholders replaced.
349
+ * @param sourceMap - Optional serialized map for the final CSS.
350
+ * @returns The bundler's reference for the emitted asset.
351
+ */
352
+ const emitCss = (text, sourceMap) => emitBuildCss(project, name, this, text, sourceMap);
353
+ /**
354
+ * Builds the stylesheet URL recorded in the document manifest.
355
+ *
356
+ * @param reference - Asset reference already issued by this build context.
357
+ * @returns The emitted filename prefixed by the configured public base.
358
+ */
359
+ const href = (reference) => settings.publicBase + this.getFileName(reference);
360
+ const revision = createHash("sha256").update(plan.designSystem).update("\0").update(plan.originalCss).update(JSON.stringify(plan.banners)).update("\0").update(JSON.stringify(plan.producers)).update("\0").digest("hex");
361
+ const output = {};
362
+ if (config.emission !== "split") {
363
+ const mapped = settings.sourceMaps ? decodeCssSourceMap(cssForBrowser(name, {
364
+ css: plan.originalCss,
365
+ sourceMap: plan.sourceMap,
366
+ banners: plan.banners
367
+ }, replacements)) : void 0;
368
+ output.buildCss = await emitCss(mapped?.code ?? finalizeCss({
369
+ css,
370
+ banners: plan.banners
371
+ }), mapped?.map ? JSON.stringify(mapped.map) : void 0);
372
+ output.manifest = {
373
+ version: 1,
374
+ revision,
375
+ parts: [{
376
+ id: "document",
377
+ href: href(output.buildCss)
378
+ }],
379
+ modules: Object.fromEntries(plan.producers.map((producer) => [producer.module, ["document"]]))
380
+ };
381
+ } else {
382
+ const references = /* @__PURE__ */ new Map();
383
+ const parts = [];
384
+ const partitions = partitionStylesheet(plan.rawParts);
385
+ for (const [index, part] of partitions.entries()) {
386
+ let reference = references.get(part.key);
387
+ if (!reference) {
388
+ const mapped = settings.sourceMaps ? decodeCssSourceMap(cssForBrowser(name, part, replacements)) : void 0;
389
+ references.set(part.key, reference = await emitCss(mapped?.code ?? finalizeCss({
390
+ css: resolveResources(part.css, replacements),
391
+ banners: part.banners
392
+ }), mapped?.map ? JSON.stringify(mapped.map) : void 0));
393
+ }
394
+ parts.push({
395
+ id: `${index}:${part.key}`,
396
+ href: href(reference)
397
+ });
398
+ }
399
+ const dependencies = new Map([...inputs(name).values()].map((input) => [input.moduleId, input.dependencies]));
400
+ output.manifest = {
401
+ version: 1,
402
+ revision,
403
+ parts,
404
+ modules: Object.fromEntries(plan.producers.map((producer) => {
405
+ const closure = /* @__PURE__ */ new Set([producer.module]);
406
+ for (const module of closure) for (const dependency of dependencies.get(module) ?? []) closure.add(dependency);
407
+ return [producer.module, parts.filter((_, index) => partitions[index].producers.length === 0 || partitions[index].producers.some((owner) => closure.has(owner))).map((part) => part.id)];
408
+ }))
409
+ };
410
+ }
411
+ project.setBuildOutput(name, output);
412
+ this.emitFile({
413
+ type: "asset",
414
+ fileName: "stillwind-manifest.json",
415
+ source: JSON.stringify(output.manifest, null, 2)
416
+ });
417
+ },
418
+ /**
419
+ * Adds CSS metadata or a split stylesheet loader to a rendered production chunk.
420
+ *
421
+ * @param code - Rendered JavaScript for this chunk.
422
+ * @param chunk - Chunk metadata, updated with the selected CSS files.
423
+ * @returns A rewritten chunk with a null map for split CSS, otherwise `null`.
424
+ */
425
+ renderChunk(code, chunk) {
426
+ return renderChunkStyles(project, this.environment?.name, this, code, chunk);
427
+ }
428
+ };
429
+ }
430
+ // src/vite/http.ts
431
+ /**
432
+ * Ends a response with JSON and disables caching for development snapshots.
433
+ * @param response - Writable response whose status and content-type/cache-control headers are replaced.
434
+ * @param value - Value accepted by JSON.stringify.
435
+ * @param statusCode - HTTP status to send, defaulting to 200.
436
+ * @throws If serialization or writing the response fails.
437
+ */
438
+ function sendJson(response, value, statusCode = 200) {
439
+ response.statusCode = statusCode;
440
+ response.setHeader("content-type", "application/json; charset=utf-8");
441
+ response.setHeader("cache-control", "no-store");
442
+ response.end(JSON.stringify(value));
443
+ }
444
+ // src/vite/development.ts
445
+ /**
446
+ * Returns development hooks that use `project`'s state for each Vite environment. The server hook
447
+ * adds routes for requesting stylesheets. Hot updates compile changed inputs and send CSS before
448
+ * invalidating JS modules. The caller must also install the compiler hooks to initialize project
449
+ * settings.
450
+ *
451
+ * @param project - Shared project configured and attached to the server by the compiler plugin.
452
+ * @returns Hooks for serving stylesheet requests and handling CSS hot updates.
453
+ */
454
+ function developmentHooks(project) {
455
+ const { settings, inputs, valueSpecifier, documentPlan, publish, compile } = project;
456
+ return {
457
+ /**
458
+ * Recompiles changed styles and selects JavaScript modules that require hot invalidation.
459
+ *
460
+ * The hook publishes CSS before returning modules for invalidation. Failed updates warn and
461
+ * leave the last published styles in use.
462
+ *
463
+ * @param context - Vite hot-update event with the current server, changed file, and source
464
+ * reader.
465
+ * @returns Modules affected by a design-system update, an empty list for a CSS-only producer
466
+ * change, or `undefined` to retain normal Vite handling.
467
+ */
468
+ async hotUpdate(context) {
469
+ const name = this.environment.name;
470
+ const state = project.environment(name);
471
+ const id = cleanModuleId(context.file);
472
+ const host = {
473
+ resolve: (specifier, importer, options) => this.environment.pluginContainer.resolveId(specifier, importer, options),
474
+ addWatchFile: (id) => {
475
+ context.server.watcher.add(id);
476
+ },
477
+ warn: (message) => {
478
+ this.warn(message);
479
+ }
480
+ };
481
+ try {
482
+ if (state.designSystem.observes(resolve(context.file), context.type !== "update")) {
483
+ await state.refreshDesignSystem(host);
484
+ await publish(name, host);
485
+ const changed = state.takeThemeChanges();
486
+ const modules = [...inputs(name).values()].filter((input) => input.manual || changed.has(input.moduleId)).flatMap((input) => [...this.environment.moduleGraph.getModulesByFile(cleanModuleId(input.id)) ?? [], ...input.manual ? [this.environment.moduleGraph.getModuleById(valueSpecifier(input.id, name).replace("virtual:stillwind/", "\0stillwind:"))].filter((module) => Boolean(module)) : []]);
487
+ for (const module of modules) this.environment.moduleGraph.invalidateModule(module, /* @__PURE__ */ new Set(), context.timestamp, true);
488
+ return modules;
489
+ }
490
+ const previous = inputs(name).get(id);
491
+ if (previous && context.type !== "delete") {
492
+ const result = await compile(name, await context.read(), id, host);
493
+ await publish(name, host);
494
+ const values = [];
495
+ for (const input of inputs(name).values()) {
496
+ if (!input.manual) continue;
497
+ const value = this.environment.moduleGraph.getModuleById(valueSpecifier(input.id, name).replace("virtual:stillwind/", "\0stillwind:"));
498
+ if (!value) continue;
499
+ if ((await state.modulePlan([input.moduleId], host, false)).producers.some((producer) => producer.module === previous.moduleId)) {
500
+ this.environment.moduleGraph.invalidateModule(value, /* @__PURE__ */ new Set(), context.timestamp, true);
501
+ values.push(value);
502
+ }
503
+ }
504
+ if (values.length) return [.../* @__PURE__ */ new Set([...context.modules, ...values])];
505
+ if (!previous.manual && result?.code === previous.javascript) return [];
506
+ }
507
+ } catch (error) {
508
+ this.warn(`Stillwind update failed; retaining published styles: ${String(error)}`);
509
+ }
510
+ },
511
+ /**
512
+ * Registers routes that serve document CSS and revisioned stylesheet snapshots.
513
+ *
514
+ * The document route supports repeated `module` selections and defaults to `ssr`. The snapshot
515
+ * route defaults to `client`. Unknown environments return 404 and stylesheet failures return
516
+ * 500.
517
+ *
518
+ * @param server - Active server with the project's initialized Vite environments.
519
+ */
520
+ configureServer(server) {
521
+ server.middlewares.use("/__stillwind/style.css", (request, response) => {
522
+ const params = new URL(request.url ?? "", "http://stillwind.local").searchParams;
523
+ const name = params.get("environment") ?? "ssr";
524
+ const selection = params.getAll("module");
525
+ const environment = server.environments[name];
526
+ if (!environment) return sendJson(response, { error: "Unknown environment" }, 404);
527
+ documentPlan(name, {
528
+ resolve: (specifier, importer, options) => environment.pluginContainer.resolveId(specifier, importer, options),
529
+ addWatchFile: (id) => {
530
+ server.watcher.add(id);
531
+ },
532
+ warn: (message) => {
533
+ server.config.logger.warn(message);
534
+ }
535
+ }, false, selection.length ? selection : void 0).then((plan) => {
536
+ response.setHeader("Content-Type", "text/css; charset=utf-8");
537
+ response.setHeader("Cache-Control", "no-store");
538
+ response.end(plan.css);
539
+ }).catch((error) => {
540
+ sendJson(response, { error: String(error) }, 500);
541
+ });
542
+ });
543
+ server.middlewares.use(`${settings.publicBase}__stillwind/css`, (request, response) => {
544
+ const name = new URL(request.url ?? "", "http://stillwind.local").searchParams.get("environment") ?? "client";
545
+ const environment = server.environments[name];
546
+ if (!environment) return sendJson(response, { error: "Unknown environment" }, 404);
547
+ project.snapshot(name, {
548
+ resolve: (specifier, importer, options) => environment.pluginContainer.resolveId(specifier, importer, options),
549
+ addWatchFile: (id) => {
550
+ server.watcher.add(id);
551
+ },
552
+ warn: (message) => {
553
+ server.config.logger.warn(message);
554
+ }
555
+ }).then((snapshot) => sendJson(response, snapshot)).catch((error) => {
556
+ sendJson(response, { error: String(error) }, 500);
557
+ });
558
+ });
559
+ }
560
+ };
561
+ }
562
+ // src/vite/browser-source-map.ts
563
+ /**
564
+ * Publishes positions with caller-approved source names and no source text or symbol names.
565
+ *
566
+ * @param input - Serialized or object source map accepted by the tracing library.
567
+ * @param sourceName - Maps each original source name to the name approved for browser delivery.
568
+ * @returns An encoded map retaining positions with the approved names and no embedded source text.
569
+ * @throws If the input is not a valid source map.
570
+ */
571
+ function browserSourceMap(input, sourceName) {
572
+ const trace = new TraceMap(input);
573
+ const map = new GenMapping();
574
+ const sources = /* @__PURE__ */ new Map();
575
+ eachMapping(trace, (entry) => {
576
+ if (entry.source !== null && entry.originalLine !== null) {
577
+ let source = sources.get(entry.source);
578
+ if (source === void 0) {
579
+ source = sourceName(entry.source);
580
+ sources.set(entry.source, source);
581
+ }
582
+ addSegment(map, entry.generatedLine - 1, entry.generatedColumn, source, entry.originalLine - 1, entry.originalColumn);
583
+ } else addSegment(map, entry.generatedLine - 1, entry.generatedColumn);
584
+ });
585
+ const result = toEncodedMap(map);
586
+ delete result.sourcesContent;
587
+ return result;
588
+ }
589
+ // src/vite/browser-css.ts
590
+ /**
591
+ * Rewrites CSS map sources without exposing absolute paths or embedded source text.
592
+ *
593
+ * Known CSS files inside the project and ordinary client scripts receive project-relative names.
594
+ * All other source identities receive SHA-256 names.
595
+ *
596
+ * @param sources - Known CSS files and producer inputs for one project environment.
597
+ * @param map - Encoded map object or serialized source map.
598
+ * @returns An encoded map with positions preserved, no source text or symbol names, and approved or
599
+ * hashed source names.
600
+ */
601
+ function publicCssSourceMap(sources, map) {
602
+ const visible = /* @__PURE__ */ new Map();
603
+ /**
604
+ * Allows a known source inside the project to use a public relative name.
605
+ * @param id - Resolver identity whose query and fragment are removed before checking its path.
606
+ */
607
+ const add = (id) => {
608
+ const relative = sourceModuleId(sources.root, cleanModuleId(id));
609
+ if (relative !== ".." && !relative.startsWith("../") && !isAbsolute(relative)) visible.set(pathToFileURL(cleanModuleId(id)).href, `stillwind-source:/${relative}`);
610
+ };
611
+ for (const file of sources.cssFiles) add(file);
612
+ if (sources.environment === "client") {
613
+ for (const input of sources.inputs) if (!input.projection && !/\.(?:astro|svelte|vue)$/.test(cleanModuleId(input.id))) add(input.id);
614
+ }
615
+ const publicNames = new Set(visible.values());
616
+ return browserSourceMap(map, (source) => {
617
+ if (/^stillwind-source:[a-f0-9]{64}$/.test(source) || publicNames.has(source)) return source;
618
+ return visible.get(source) ?? `stillwind-source:${createHash("sha256").update(source).digest("hex")}`;
619
+ });
620
+ }
621
+ /**
622
+ * Replaces CSS resource placeholders and composes a source map for browser delivery.
623
+ *
624
+ * @param sources - Environment sources and upstream producer maps.
625
+ * @param output - Compiler CSS and its native source map.
626
+ * @param replacements - Map from resource placeholder tokens to escaped URL text.
627
+ * @returns CSS with replaced resources and, when a map is available, an inline map containing
628
+ * public source names.
629
+ */
630
+ function cssForBrowser(sources, output, replacements) {
631
+ const decoded = decodeCssSourceMap(cssWithSourceMap(output, replacements, sources.inputs.flatMap((input) => input.upstream ? [input.upstream] : []), false));
632
+ if (!decoded.map) return decoded.code;
633
+ const encoded = Buffer.from(JSON.stringify(publicCssSourceMap(sources, decoded.map))).toString("base64");
634
+ return `${decoded.code}\n/*# sourceMappingURL=data:application/json;base64,${encoded} */`;
635
+ }
636
+ // src/vite/css-targets.ts
637
+ const browserTarget = /^(android|chrome|edge|firefox|ie|ios|opera|safari|samsung)(\d+(?:\.\d+){0,2})$/;
638
+ /**
639
+ * Selects browser versions from Vite's resolved CSS target without inferring versions from JS levels.
640
+ * @param target - Resolved CSS target, including disabled targets and language-level strings.
641
+ * @returns A copy of the browser list, or an empty list if any entry cannot identify browser versions.
642
+ */
643
+ function inheritCssTarget(target) {
644
+ const entries = typeof target === "string" ? [target] : target || [];
645
+ return entries.every((entry) => browserTarget.test(entry)) ? [...entries] : [];
646
+ }
647
+ /**
648
+ * Converts Stillwind browser versions to Lightning CSS's packed minimum versions.
649
+ * @param target - Validated compiler targets. Omission and empty lists leave minifier targets unspecified.
650
+ * @returns Browser versions with the oldest entry retained for each browser and ios named ios_saf.
651
+ * @throws If a target cannot be represented by Lightning CSS's three one-byte version components.
652
+ */
653
+ function minifyTargets(target) {
654
+ const entries = typeof target === "string" ? [target] : target ?? [];
655
+ if (!entries.length) return;
656
+ const targets = {};
657
+ for (const entry of entries) {
658
+ const match = browserTarget.exec(entry);
659
+ const parts = match?.[2].split(".").map(Number);
660
+ if (!match || !parts || parts.some((part) => part > 255)) throw new Error(`Cannot represent CSS minifier target ${JSON.stringify(entry)}: each version component must be 0..255`);
661
+ const [major, minor = 0, patch = 0] = parts;
662
+ const version = major * 65536 + minor * 256 + patch;
663
+ const browser = match[1] === "ios" ? "ios_saf" : match[1];
664
+ targets[browser] = Math.min(targets[browser] ?? version, version);
665
+ }
666
+ return targets;
667
+ }
668
+ // src/vite/finalize.ts
669
+ /**
670
+ * Finalizes source while retaining prefix metadata for source-map generation.
671
+ * @param code - Compiled JavaScript before finalization.
672
+ * @param includeStylesheet - Whether to prepend the shared virtual stylesheet import.
673
+ * @returns Final code, the inserted prefix, and host finalization's removed intervals.
674
+ */
675
+ function finalizeModuleWithMap$1(code, includeStylesheet = true) {
676
+ return finalizeModuleWithMap(code, includeStylesheet ? virtualCssId : void 0);
677
+ }
678
+ // src/vite/compile.ts
679
+ /**
680
+ * Compiles a producer and prepares its generated imports, source map, and cache metadata.
681
+ *
682
+ * Successful compilation updates the session and registers CSS references. The caller must store
683
+ * the returned input. SFC output keeps framework syntax, while script output is finalized and may
684
+ * import an automatic producer module.
685
+ *
686
+ * @param compiler - Initialized session for the current environment.
687
+ * @param settings - Configured root used to derive compiler and checker file identities.
688
+ * @param config - Compiler config, including whether document CSS is automatic.
689
+ * @param registry - Virtual reference registry for the same environment.
690
+ * @param code - Source text before Stillwind transformation.
691
+ * @param id - Full Vite identity of the source, including any query suffix.
692
+ * @param context - Resolver, watcher, warning handler, and optional upstream-map reader.
693
+ * @param previous - Previously recorded input whose projection flag and upstream map may be
694
+ * retained.
695
+ * @returns A promise for the recorded input and Vite transform result, or `undefined` when the
696
+ * compiler produces no code.
697
+ * @throws If dependency loading, compilation, or upstream-map reading fails.
698
+ */
699
+ async function compileProducer(compiler, settings, config, registry, code, id, context, previous) {
700
+ const sfc = /\.(?:astro|svelte|vue)$/.test(cleanModuleId(id));
701
+ /**
702
+ * Gives a producer a document identity suitable for compiler reports and maps.
703
+ * @param id - Full resolver identity. Queries and fragments are removed from the document name.
704
+ * @returns An encoded `stillwind-virtual:` URI for virtual modules, or a file URL for a file.
705
+ */
706
+ const documentUri = (id) => {
707
+ const clean = cleanModuleId(id);
708
+ return clean.startsWith("\0") || clean.startsWith("virtual:") ? `stillwind-virtual:${encodeURIComponent(clean)}` : pathToFileURL(clean).href;
709
+ };
710
+ const output = await compiler.compile(code, id, {
711
+ resolve: (specifier, importer) => context.resolve(specifier, importer, {
712
+ skipSelf: true,
713
+ custom: { "react-router:dot-server": true }
714
+ }),
715
+ read: (id) => readFile(cleanModuleId(id), "utf8"),
716
+ describe: (resolvedId) => {
717
+ const virtual = resolvedId.startsWith("\0") || resolvedId.startsWith("virtual:");
718
+ const file = virtual ? resolve(settings.projectRoot, ".stillwind-checker", `${createHash("sha256").update(resolvedId).digest("hex")}.ts`) : cleanModuleId(resolvedId);
719
+ const { syntax, format } = fileSourceKind(resolvedId);
720
+ return {
721
+ moduleId: virtual ? `virtual:${encodeURIComponent(resolvedId)}` : sourceModuleId(settings.projectRoot, resolvedId),
722
+ document: {
723
+ uri: documentUri(resolvedId),
724
+ format
725
+ },
726
+ checkerFileName: file,
727
+ projectionFileName: file.replaceAll("\\", "/"),
728
+ syntax
729
+ };
730
+ },
731
+ watch: (id) => {
732
+ context.addWatchFile(id);
733
+ },
734
+ warn: (message) => {
735
+ context.warn(message);
736
+ }
737
+ }, {
738
+ stylesheetImports: sfc && config.automatic !== false ? [registry.source("producer", id)] : void 0,
739
+ moduleCssImport: registry.source("value", id)
740
+ });
741
+ if (!output?.code) return;
742
+ const finalized = sfc ? {
743
+ code: output.code,
744
+ removed: [],
745
+ prefix: ""
746
+ } : finalizeModuleWithMap$1(output.code, false);
747
+ const suffix = sfc || output.hasModuleCssImport || config.automatic === false ? "" : `\nimport ${JSON.stringify(registry.source("producer", id))};\n`;
748
+ const javascript = finalized.code + suffix;
749
+ const sourceMap = moduleSourceMap(code, output.code, id, output.mappings, finalized.removed, finalized.prefix);
750
+ return {
751
+ input: {
752
+ sourceMap,
753
+ projection: previous?.projection,
754
+ upstream: context.getCombinedSourcemap ? {
755
+ id: cleanModuleId(id),
756
+ sourceMapSource: documentUri(id),
757
+ map: JSON.stringify(context.getCombinedSourcemap())
758
+ } : previous?.upstream,
759
+ code,
760
+ id,
761
+ moduleId: output.moduleId,
762
+ manual: output.hasModuleCssImport || config.automatic === false,
763
+ hasModuleCssImport: output.hasModuleCssImport,
764
+ javascript,
765
+ dependencies: output.compositionModules
766
+ },
767
+ result: {
768
+ code: javascript,
769
+ map: JSON.stringify(sourceMap),
770
+ meta: { stillwind: {
771
+ input: code,
772
+ id,
773
+ moduleId: output.moduleId,
774
+ manual: output.hasModuleCssImport
775
+ } }
776
+ }
777
+ };
778
+ }
779
+ // src/vite/design-system.ts
780
+ /**
781
+ * Owns one environment's compiler, design-system resources, and CSS reload state.
782
+ */
783
+ var DesignSystem = class {
784
+ settings;
785
+ config;
786
+ /** Compiler session retained across CSS reloads and replaced when initialization restarts. */
787
+ #compiler;
788
+ /** Plugin runtime of the applied design system, kept as the previous runtime of reloads. */
789
+ #plugins;
790
+ /** Whether the compiler is ready for producer compilation and stylesheet planning. */
791
+ #initialized = false;
792
+ /**
793
+ * Resource placeholders mapped to resolved file identities and readable paths from the last
794
+ * successful load.
795
+ */
796
+ resources = /* @__PURE__ */ new Map();
797
+ /**
798
+ * Absolute paths required by the last successful design-system load, including referenced
799
+ * resource files.
800
+ */
801
+ cssFiles = /* @__PURE__ */ new Set();
802
+ /**
803
+ * Absolute paths tracked for changes, including unresolved relative candidates discovered during
804
+ * failed loads.
805
+ */
806
+ cssObservedFiles = /* @__PURE__ */ new Set();
807
+ /** Absolute directories that plugins list. Adding or removing an entry is an observed change. */
808
+ cssObservedDirectories = /* @__PURE__ */ new Set();
809
+ /** Content fingerprint used to detect changes when development runs without a CSS watcher. */
810
+ cssVersion;
811
+ /** Counter advanced by changes to observed files. */
812
+ cssChange = 0;
813
+ /** Change counter last applied successfully to the compiler. */
814
+ cssApplied = 0;
815
+ /**
816
+ * Change counter last attempted. Starts at -1 so the first watched revision cannot be skipped.
817
+ */
818
+ cssAttempted = -1;
819
+ /**
820
+ * Latest refresh error. Recording an error does not clear the initialized compiler session.
821
+ */
822
+ cssError;
823
+ /**
824
+ * Creates design-system state without loading CSS or opening a compiler session.
825
+ *
826
+ * @param settings - Shared project settings configured before initialization.
827
+ * @param config - Compiler options that identify the CSS entrypoint.
828
+ */
829
+ constructor(settings, config) {
830
+ this.settings = settings;
831
+ this.config = config;
832
+ }
833
+ /**
834
+ * Obtains the initialized compiler session.
835
+ *
836
+ * @returns The session currently holding the loaded design system.
837
+ * @throws If `ensure` has not initialized the session or `reset` has invalidated it.
838
+ */
839
+ get compiler() {
840
+ if (!this.#initialized || !this.#compiler) throw new Error("Stillwind environment has not been initialized");
841
+ return this.#compiler;
842
+ }
843
+ /**
844
+ * Reports whether producer compilation can use the current session.
845
+ *
846
+ * @returns True after successful initialization and until the next reset.
847
+ */
848
+ get initialized() {
849
+ return this.#initialized;
850
+ }
851
+ /**
852
+ * Invalidates initialization so the next `ensure` reloads CSS and replaces the retained compiler
853
+ * session.
854
+ */
855
+ reset() {
856
+ this.#initialized = false;
857
+ }
858
+ /**
859
+ * Closes the compiler's type-facts service while retaining native compilation state and CSS
860
+ * reload metadata.
861
+ */
862
+ close() {
863
+ this.#compiler?.close();
864
+ }
865
+ /**
866
+ * Checks whether a file event changes an input of the loaded design system.
867
+ *
868
+ * @param file - Absolute path of the changed file.
869
+ * @param entry - Whether the event adds or removes the file, rather than changing its content.
870
+ * @returns Whether `cssObservedFiles` contains the file, or the event adds or removes an entry
871
+ * of a directory in `cssObservedDirectories`.
872
+ */
873
+ observes(file, entry) {
874
+ return this.cssObservedFiles.has(file) || entry && this.cssObservedDirectories.has(dirname(file));
875
+ }
876
+ /**
877
+ * Marks a design-system revision pending when an observed file changes.
878
+ *
879
+ * @param file - Absolute path of the changed file. Paths that {@link DesignSystem.observes}
880
+ * rejects have no effect.
881
+ * @param entry - Whether the event adds or removes the file.
882
+ */
883
+ changed(file, entry) {
884
+ if (this.observes(file, entry)) this.cssChange++;
885
+ }
886
+ /**
887
+ * Loads a stable design-system revision and creates the compiler if initialization is pending.
888
+ *
889
+ * While watching, changes observed during loading cause the load to retry.
890
+ *
891
+ * @param context - Vite resolver and watch operations for the current build or server.
892
+ * @param onInitialize - Called after the new session and CSS state are installed.
893
+ * @returns A promise that resolves when the compiler is ready. An initialized session is reused.
894
+ * @throws If loading CSS, resolving resources, or creating the compiler fails.
895
+ */
896
+ async ensure(context, onInitialize) {
897
+ if (this.#initialized) return;
898
+ while (true) {
899
+ const change = this.cssChange;
900
+ let loaded;
901
+ try {
902
+ loaded = await this.#loadRevision(context);
903
+ } catch (error) {
904
+ if (this.settings.cssWatching && change !== this.cssChange) continue;
905
+ throw error;
906
+ }
907
+ const version = this.settings.watching && !this.settings.cssWatching ? await designSystemVersion(loaded.dependencies, loaded.directories) : void 0;
908
+ if (this.settings.cssWatching && change !== this.cssChange) continue;
909
+ this.#compiler?.close();
910
+ this.#compiler = new IntegrationSession(this.settings.projectRoot, loaded.loader, this.config, this.settings.watching, this.settings.compilerMode, loaded.plugins);
911
+ this.#plugins = loaded.plugins;
912
+ this.#initialized = true;
913
+ this.resources = loaded.resources;
914
+ this.cssFiles = loaded.dependencies;
915
+ this.cssObservedFiles = loaded.observed;
916
+ this.cssObservedDirectories = loaded.directories;
917
+ this.cssVersion = version;
918
+ this.cssApplied = this.cssAttempted = change;
919
+ this.cssError = void 0;
920
+ warnSkippedCss(loaded.skipped, (message) => context.warn(message));
921
+ onInitialize();
922
+ return;
923
+ }
924
+ }
925
+ /**
926
+ * Reloads changed development CSS and records failed refresh attempts.
927
+ *
928
+ * Production returns after initialization. Development uses observed change counters or file
929
+ * fingerprints. Refresh failures are recorded and warned. If loading the next CSS revision
930
+ * fails, the compiler keeps the previously loaded design system.
931
+ *
932
+ * @param context - Vite resolver and watch operations for loading the next design-system
933
+ * revision.
934
+ * @param onInitialize - Called if initialization must create a compiler session.
935
+ * @param onReload - Receives compiler module identities whose generated JavaScript changed after
936
+ * a reload.
937
+ * @returns A promise that resolves after initialization and any required refresh.
938
+ * @throws If initial loading fails. Failures during a later refresh are recorded in `cssError`.
939
+ */
940
+ async refresh(context, onInitialize, onReload) {
941
+ await this.ensure(context, onInitialize);
942
+ if (!this.settings.watching) return;
943
+ while (true) {
944
+ const change = this.cssChange;
945
+ if (this.settings.cssWatching && this.cssAttempted === change) return;
946
+ try {
947
+ const version = this.settings.cssWatching ? void 0 : await designSystemVersion(this.cssFiles, this.cssObservedDirectories);
948
+ if (!this.settings.cssWatching && version === this.cssVersion) return;
949
+ const loaded = await this.#loadRevision(context);
950
+ const nextVersion = this.settings.cssWatching ? void 0 : await designSystemVersion(loaded.dependencies, loaded.directories);
951
+ if (this.settings.cssWatching ? change !== this.cssChange : version !== await designSystemVersion(this.cssFiles, this.cssObservedDirectories)) continue;
952
+ const update = this.compiler.native.reload(loaded.loader);
953
+ attachPlugins(this.compiler.native, loaded.plugins);
954
+ this.#plugins = loaded.plugins;
955
+ onReload(update.transformedModules);
956
+ this.resources = loaded.resources;
957
+ this.cssFiles = loaded.dependencies;
958
+ this.cssObservedFiles = loaded.observed;
959
+ this.cssObservedDirectories = loaded.directories;
960
+ this.cssVersion = nextVersion;
961
+ this.cssApplied = this.cssAttempted = change;
962
+ this.cssError = void 0;
963
+ warnSkippedCss(loaded.skipped, (message) => context.warn(message));
964
+ return;
965
+ } catch (error) {
966
+ if (this.settings.cssWatching && change !== this.cssChange) continue;
967
+ this.cssAttempted = change;
968
+ this.cssError = error;
969
+ this.settings.devServerRef?.config.logger.warn(`Stillwind update failed; retaining published styles: ${String(error)}`);
970
+ return;
971
+ }
972
+ }
973
+ }
974
+ /**
975
+ * Loads CSS and resources while recording successful dependencies and attempted file reads.
976
+ *
977
+ * Files are registered with Vite and the development watcher as they are discovered. Failed loads
978
+ * retain newly observed paths so later edits can trigger another attempt.
979
+ *
980
+ * @param context - Vite resolver and watch operations.
981
+ * @returns The loaded design system, resolved resources, required file set, and observed file
982
+ * set.
983
+ * @throws If CSS loading or resource resolution fails.
984
+ */
985
+ async #loadRevision(context) {
986
+ const dependencies = /* @__PURE__ */ new Set();
987
+ const observed = /* @__PURE__ */ new Set();
988
+ const tracking = this.cssObservedFiles;
989
+ /**
990
+ * Records a dependency once for this load and registers it with Vite's watchers.
991
+ *
992
+ * @param file - Attempted or resolved file path, normalized to an absolute path.
993
+ */
994
+ const watch = (file) => {
995
+ const path = resolve(file);
996
+ if (observed.has(path)) return;
997
+ observed.add(path);
998
+ tracking.add(path);
999
+ context.addWatchFile(path);
1000
+ this.settings.devServerRef?.watcher.add(path);
1001
+ };
1002
+ const directories = /* @__PURE__ */ new Set();
1003
+ const trackingDirectories = this.cssObservedDirectories;
1004
+ /**
1005
+ * Records a directory that a plugin lists once for this load and registers it with Vite's
1006
+ * watchers.
1007
+ *
1008
+ * @param directory - Absolute directory path.
1009
+ */
1010
+ const watchDirectory = (directory) => {
1011
+ const path = resolve(directory);
1012
+ if (directories.has(path)) return;
1013
+ directories.add(path);
1014
+ trackingDirectories.add(path);
1015
+ context.addWatchFile(path);
1016
+ this.settings.devServerRef?.watcher.add(path);
1017
+ };
1018
+ return {
1019
+ ...await loadDesignSystem(this.settings, this.config, async (specifier, importer) => resolvedFile(await context.resolve(specifier, importer, { skipSelf: true }), `CSS ${specifier} from ${importer}`), dependencies, this.#initialized ? this.#compiler?.native : void 0, watch, watchDirectory, this.#plugins),
1020
+ dependencies,
1021
+ observed,
1022
+ directories
1023
+ };
1024
+ }
1025
+ };
1026
+ /**
1027
+ * Loads the configured CSS graph and resolves each referenced resource to a readable file.
1028
+ *
1029
+ * @param settings - Configured project root and optional development server used to check resource
1030
+ * access.
1031
+ * @param config - Compiler settings and the CSS entrypoint, resolved against the project root.
1032
+ * @param resolveImport - Resolves a specifier relative to its importer and returns a file identity.
1033
+ * @param dependencies - Mutable set receiving files required by the CSS graph and its resources.
1034
+ * @param session - Existing native session used to create a compatible loader during reload.
1035
+ * @param watch - Records attempted and resolved file paths, including unresolved relative
1036
+ * candidates.
1037
+ * @param watchDirectory - Records directories that plugins list.
1038
+ * @param previous - Plugin runtime of the previous load, whose candidates are resolved again.
1039
+ * @returns A native design-system loader, a map from resource placeholders to resolved files, the
1040
+ * plugin runtime, and the skipped statements.
1041
+ * @throws If the entrypoint is missing or not readable, CSS cannot be divided into statements, or a
1042
+ * referenced resource is not readable. Imports that cannot be resolved or read are skipped.
1043
+ */
1044
+ async function loadDesignSystem(settings, config, resolveImport, dependencies, session, watch = () => {}, watchDirectory = () => {}, previous) {
1045
+ const entry = resolve(settings.projectRoot, cssEntrypoint(config));
1046
+ watch(entry);
1047
+ const root = realpathSync(entry);
1048
+ /**
1049
+ * Watches relative candidates before resolution and the resolved file after success.
1050
+ * @param specifier - CSS import or resource request passed to the configured resolver.
1051
+ * @param importer - Full identity of the source containing the request.
1052
+ * @returns The resolver's identity with its query and fragment retained.
1053
+ * @throws If resolution or a watch callback fails.
1054
+ */
1055
+ const resolveCss = async (specifier, importer) => {
1056
+ if (specifier.startsWith(".")) watch(resolve(dirname(importer), cleanModuleId(specifier)));
1057
+ const file = await resolveImport(specifier, importer);
1058
+ watch(cleanModuleId(file));
1059
+ return file;
1060
+ };
1061
+ const nativeOptions = buildCompilerOptions(config);
1062
+ const resolvePackageCss = createStylesheetResolver();
1063
+ const { loader, resources: resourceReferences, plugins, skipped } = await loadCssGraph(root, nativeOptions, {
1064
+ resolve: async (specifier, importer) => {
1065
+ let resolved;
1066
+ let failure;
1067
+ try {
1068
+ resolved = await resolveCss(specifier, importer);
1069
+ } catch (error) {
1070
+ failure = error;
1071
+ }
1072
+ if (resolved && isStylesheet(cleanModuleId(resolved))) return realpath(cleanModuleId(resolved));
1073
+ const stylesheet = !specifier.startsWith(".") && !specifier.startsWith("/") ? await resolvePackageCss(specifier, importer) : void 0;
1074
+ if (stylesheet) return realpath(stylesheet);
1075
+ if (resolved) return realpath(cleanModuleId(resolved));
1076
+ throw failure;
1077
+ },
1078
+ read: (name) => readFile(name, "utf8"),
1079
+ documentUri: (name) => pathToFileURL(name).href,
1080
+ sourceMapSource: (name) => pathToFileURL(name).href,
1081
+ watch: (name) => {
1082
+ dependencies.add(name);
1083
+ watch(name);
1084
+ },
1085
+ watchDirectory,
1086
+ plugins: nodePluginHost
1087
+ }, void 0, session?.newLoader(nativeOptions), {
1088
+ plugins: config.plugins,
1089
+ tailwind: config.tailwind,
1090
+ important: config.important,
1091
+ root: settings.projectRoot,
1092
+ previous
1093
+ });
1094
+ const references = /* @__PURE__ */ new Map();
1095
+ for (const resource of resourceReferences) {
1096
+ const resolved = await resolveCss(resource.specifier, resource.sourceName);
1097
+ const file = await readableFile(resolved, settings.devServerRef);
1098
+ references.set(resource.placeholder, {
1099
+ id: resolved,
1100
+ file
1101
+ });
1102
+ dependencies.add(cleanModuleId(resolved));
1103
+ }
1104
+ return {
1105
+ loader,
1106
+ resources: references,
1107
+ plugins,
1108
+ skipped
1109
+ };
1110
+ }
1111
+ /**
1112
+ * Computes a stable fingerprint of the paths and contents used by the design system, and of the
1113
+ * entry names of the directories that plugins list.
1114
+ *
1115
+ * @param files - Absolute dependency paths. Iteration order does not affect the fingerprint.
1116
+ * @param directories - Absolute directory paths. Iteration order and entry order do not affect the
1117
+ * fingerprint.
1118
+ * @returns A SHA-256 hexadecimal fingerprint. Missing files and directories contribute a fixed
1119
+ * marker.
1120
+ * @throws If reading a file or directory fails for a reason other than `ENOENT`.
1121
+ */
1122
+ async function designSystemVersion(files, directories) {
1123
+ const hash = createHash("sha256");
1124
+ for (const directory of [...directories].sort()) {
1125
+ let names;
1126
+ try {
1127
+ names = (await readdir(directory)).sort().join("\0");
1128
+ } catch (error) {
1129
+ if (error.code !== "ENOENT") throw error;
1130
+ names = "\0missing";
1131
+ }
1132
+ hash.update(directory).update("\0\0").update(names).update("\0");
1133
+ }
1134
+ const ordered = [...files].sort();
1135
+ for (let offset = 0; offset < ordered.length; offset += 64) {
1136
+ const batch = ordered.slice(offset, offset + 64);
1137
+ const contents = await Promise.all(batch.map(async (file) => {
1138
+ try {
1139
+ return await readFile(file);
1140
+ } catch (error) {
1141
+ if (error.code !== "ENOENT") throw error;
1142
+ return "\0missing";
1143
+ }
1144
+ }));
1145
+ for (const [index, file] of batch.entries()) hash.update(file).update("\0").update(contents[index]).update("\0");
1146
+ }
1147
+ return hash.digest("hex");
1148
+ }
1149
+ // src/vite/module-registry.ts
1150
+ /** References issued by one project environment. Unknown IDs never supply file paths. */
1151
+ var ModuleRegistry = class {
1152
+ root;
1153
+ environment;
1154
+ /** Issued virtual identities mapped to their payloads. References are not interpreted as paths. */
1155
+ #entries = /* @__PURE__ */ new Map();
1156
+ /** Projection imports keyed by full importer identity and authored specifier. */
1157
+ #projections = /* @__PURE__ */ new Map();
1158
+ /**
1159
+ * Creates an empty registry for one project environment.
1160
+ * @param root - Project root used to derive compiler identities from source resolver identities.
1161
+ * @param environment - Environment name included in every issued reference's fingerprint.
1162
+ */
1163
+ constructor(root, environment) {
1164
+ this.root = root;
1165
+ this.environment = environment;
1166
+ }
1167
+ /**
1168
+ * Issues a deterministic reference. Identical fragments reuse their fixed payloads.
1169
+ * @param kind - Reference family included in the virtual prefix and fingerprint.
1170
+ * @param key - Source identity or serialized fragment content used within that family.
1171
+ * @param entry - Owned payload fixed under the resulting identity.
1172
+ * @returns A virtual:stillwind reference containing a SHA-256 token scoped to the environment.
1173
+ */
1174
+ #register(kind, key, entry) {
1175
+ const id = `virtual:stillwind/${kind}:${createHash("sha256").update(JSON.stringify([
1176
+ this.environment,
1177
+ kind,
1178
+ key
1179
+ ])).digest("hex")}`;
1180
+ if (entry.kind === "fragment" && this.#entries.has(id)) return id;
1181
+ this.#entries.set(id, entry);
1182
+ return id;
1183
+ }
1184
+ /**
1185
+ * Registers a source-backed generated module.
1186
+ * @param kind - CSS value, projection, or producer registration module family.
1187
+ * @param sourceId - Full resolver identity, including queries that select distinct source.
1188
+ * @returns A deterministic reference for that environment, family, and compiler module identity.
1189
+ */
1190
+ source(kind, sourceId) {
1191
+ const moduleId = sourceModuleId(this.root, sourceId);
1192
+ return this.#register(kind, moduleId, {
1193
+ kind,
1194
+ sourceId,
1195
+ moduleId
1196
+ });
1197
+ }
1198
+ /**
1199
+ * Registers CSS with only the resource records whose placeholders occur in it.
1200
+ * @param css - Generated fragment text before resource replacement.
1201
+ * @param resources - Available placeholder records. The supplied map is unchanged.
1202
+ * @returns A reference fingerprinted from CSS and selected records in map order.
1203
+ */
1204
+ fragment(css, resources) {
1205
+ const selected = [];
1206
+ for (const [placeholder, resource] of resources) if (css.includes(placeholder)) selected.push([placeholder, {
1207
+ id: resource.id,
1208
+ file: resource.file
1209
+ }]);
1210
+ return this.#register("fragment", JSON.stringify([css, selected]), {
1211
+ kind: "fragment",
1212
+ css,
1213
+ resources: selected
1214
+ });
1215
+ }
1216
+ /**
1217
+ * Looks up an issued public or resolved virtual reference.
1218
+ * @param id - virtual:stillwind identity or its NUL-prefixed resolved spelling.
1219
+ * @returns The retained payload, or undefined for an unregistered identity.
1220
+ */
1221
+ get(id) {
1222
+ return this.#entries.get(id.replace(/^\0stillwind:/, "virtual:stillwind/"));
1223
+ }
1224
+ /**
1225
+ * Replaces an importer's projection edges and removes previous references with no remaining owner.
1226
+ * @param importer - Full resolver identity of the original importing document.
1227
+ * @param sources - Authored projection specifiers mapped to resolved source identities. The map is copied.
1228
+ */
1229
+ projections(importer, sources) {
1230
+ const previous = this.#projections.get(importer);
1231
+ this.#projections.set(importer, new Map([...sources].map(([specifier, source]) => [specifier, this.source("projection", source)])));
1232
+ for (const reference of previous?.values() ?? []) if (![...this.#projections.values()].some((edges) => [...edges.values()].includes(reference))) this.#entries.delete(reference);
1233
+ }
1234
+ /**
1235
+ * Resolves a projection only through an importer's previously registered edge.
1236
+ * @param specifier - Authored projection request, including ?stillwind.css.
1237
+ * @param importer - Full importer identity. Omission cannot select an edge.
1238
+ * @returns The issued reference, or undefined when no corresponding edge exists.
1239
+ */
1240
+ projection(specifier, importer) {
1241
+ return importer === void 0 ? void 0 : this.#projections.get(importer)?.get(specifier);
1242
+ }
1243
+ /**
1244
+ * Removes source-backed references and projection edges after source removal.
1245
+ * @param sourceId - Full resolver identity to remove.
1246
+ * @param file - Whether to match all queries and fragments of the cleaned file identity.
1247
+ */
1248
+ remove(sourceId, file = false) {
1249
+ /**
1250
+ * Applies the selected source-removal policy to a registered identity.
1251
+ * @param id - Full resolver identity from a source entry or projection importer.
1252
+ * @returns Whether the exact identity, or its cleaned file identity when requested, matches.
1253
+ */
1254
+ const matches = (id) => file ? cleanModuleId(id) === cleanModuleId(sourceId) : id === sourceId;
1255
+ for (const [id, entry] of this.#entries) if ("sourceId" in entry && matches(entry.sourceId)) this.#entries.delete(id);
1256
+ for (const [importer, edges] of this.#projections) if (matches(importer)) this.#projections.delete(importer);
1257
+ else for (const [specifier, target] of edges) if (!this.#entries.has(target)) edges.delete(specifier);
1258
+ }
1259
+ /** Removes every issued reference and projection edge when the environment is reset. */
1260
+ clear() {
1261
+ this.#entries.clear();
1262
+ this.#projections.clear();
1263
+ }
1264
+ };
1265
+ // src/vite/stylesheet.ts
1266
+ /**
1267
+ * Plans selected compiler modules and resolves their stylesheet resource placeholders.
1268
+ *
1269
+ * Referenced resources are checked for readability and registered as watch dependencies.
1270
+ * Development parts include public source maps only when development CSS maps are enabled.
1271
+ *
1272
+ * @param designSystem - Initialized design system for the current environment.
1273
+ * @param settings - Project root, source-map settings, and optional server used to validate
1274
+ * resource access.
1275
+ * @param sources - Environment sources used to compose browser CSS maps.
1276
+ * @param revision - Environment revision recorded in the resulting plan.
1277
+ * @param modules - Compiler module identities selected for document placement.
1278
+ * @param context - Vite resolver and watch operations for referenced resources.
1279
+ * @param complete - Whether the caller has collected the complete application graph. False uses
1280
+ * observed coverage.
1281
+ * @returns A promise for resolved CSS, raw compiler parts, browser-ready parts, and resource
1282
+ * replacements.
1283
+ * @throws If the compiler is uninitialized, stylesheet planning fails, or a resource cannot be
1284
+ * resolved or read.
1285
+ */
1286
+ async function resolveStylesheet(designSystem, settings, sources, revision, modules, context, complete = false) {
1287
+ const plan = designSystem.compiler.native.planStylesheet({
1288
+ modules,
1289
+ coverage: complete ? {
1290
+ kind: "complete",
1291
+ target: "application",
1292
+ revision: String(revision)
1293
+ } : { kind: "observed" },
1294
+ placement: "document"
1295
+ }, settings.watching ? settings.devSourceMaps : settings.sourceMaps);
1296
+ warnRejectedNames(plan.rejectedNames, (message) => context.warn(message));
1297
+ const resources = new Map(designSystem.resources);
1298
+ for (const resource of plan.resources) {
1299
+ const id = resolvedFile(await context.resolve(resource.specifier, designSystem.compiler.resolverId(resource.moduleId), { skipSelf: true }), `Stillwind resource ${resource.specifier}`);
1300
+ const file = await readableFile(id, settings.devServerRef);
1301
+ context.addWatchFile(file);
1302
+ resources.set(resource.placeholder, {
1303
+ id,
1304
+ file
1305
+ });
1306
+ }
1307
+ const replacements = resourceReplacements(resources);
1308
+ return {
1309
+ ...plan,
1310
+ revision,
1311
+ originalCss: plan.css,
1312
+ resources,
1313
+ resourceReplacements: replacements,
1314
+ css: finalizeCss({
1315
+ css: resolveResources(plan.css, replacements),
1316
+ banners: plan.banners
1317
+ }),
1318
+ rawParts: plan.parts,
1319
+ parts: plan.parts.map((part) => {
1320
+ const mapped = settings.watching && settings.devSourceMaps ? decodeCssSourceMap(cssForBrowser(sources, {
1321
+ ...part,
1322
+ banners: []
1323
+ }, replacements)) : void 0;
1324
+ return {
1325
+ banners: part.banners,
1326
+ key: part.key,
1327
+ producers: part.producers,
1328
+ css: mapped?.code ?? resolveResources(part.css, replacements),
1329
+ map: mapped?.map
1330
+ };
1331
+ })
1332
+ };
1333
+ }
1334
+ // src/vite/environment.ts
1335
+ /** Owns compiler inputs, virtual references, and serialized CSS work for one Vite environment. */
1336
+ var ViteEnvironment = class {
1337
+ name;
1338
+ settings;
1339
+ config;
1340
+ invalidate;
1341
+ /** Design system and compiler used only by this environment. */
1342
+ #designSystem;
1343
+ /** Producer inputs keyed by their full Vite identities, including query suffixes. */
1344
+ #inputs = /* @__PURE__ */ new Map();
1345
+ /**
1346
+ * Compiler module identities whose JavaScript changed after a CSS reload, pending consumption by
1347
+ * hot-update handling.
1348
+ */
1349
+ #themeChanges = /* @__PURE__ */ new Set();
1350
+ /**
1351
+ * Promise released by the latest queued operation. It resolves even when that operation fails, so
1352
+ * later work can continue.
1353
+ */
1354
+ #work = Promise.resolve();
1355
+ /** Virtual references created lazily after the project root has been configured. */
1356
+ #registry;
1357
+ /** Revision counter advanced when the compiler initializes or a snapshot is published. */
1358
+ revision = 0;
1359
+ /**
1360
+ * Production assets and manifest from the latest stylesheet emission. Build start clears this
1361
+ * value.
1362
+ */
1363
+ buildOutput;
1364
+ /**
1365
+ * Creates isolated compilation state for a Vite environment.
1366
+ *
1367
+ * @param name - Vite environment name used for virtual module identities and runtime snapshots.
1368
+ * @param settings - Shared project settings that must be configured before compilation starts.
1369
+ * @param config - Compiler options shared by the project.
1370
+ * @param invalidate - Invalidates Vite source identities whose JavaScript changes after a
1371
+ * design-system reload.
1372
+ */
1373
+ constructor(name, settings, config, invalidate) {
1374
+ this.name = name;
1375
+ this.settings = settings;
1376
+ this.config = config;
1377
+ this.invalidate = invalidate;
1378
+ this.#designSystem = new DesignSystem(settings, config);
1379
+ }
1380
+ /**
1381
+ * Exposes design-system reload progress without allowing callers to replace its state.
1382
+ *
1383
+ * @returns The current environment's live design-system status.
1384
+ */
1385
+ get designSystem() {
1386
+ return this.#designSystem;
1387
+ }
1388
+ /**
1389
+ * Exposes compiled producers for stylesheet selection and graph recovery.
1390
+ *
1391
+ * @returns The live producer map keyed by full Vite source identity. Callers must not mutate its
1392
+ * entries.
1393
+ */
1394
+ get inputs() {
1395
+ return this.#inputs;
1396
+ }
1397
+ /**
1398
+ * Obtains the registry of virtual references for this environment.
1399
+ *
1400
+ * @returns The existing registry, or a registry created using the configured project root.
1401
+ */
1402
+ get registry() {
1403
+ this.#registry ??= new ModuleRegistry(this.settings.projectRoot, this.name);
1404
+ return this.#registry;
1405
+ }
1406
+ /**
1407
+ * Collects source metadata for composing browser-visible CSS maps.
1408
+ *
1409
+ * @returns The project root, environment name, current CSS file set, and current producer inputs.
1410
+ */
1411
+ get browserSources() {
1412
+ return {
1413
+ root: this.settings.projectRoot,
1414
+ environment: this.name,
1415
+ cssFiles: this.#designSystem.cssFiles,
1416
+ inputs: [...this.#inputs.values()]
1417
+ };
1418
+ }
1419
+ /**
1420
+ * Records a changed file for the next design-system refresh.
1421
+ *
1422
+ * @param file - Absolute path of the changed file.
1423
+ * @param entry - Whether the event adds or removes the file, rather than changing its content.
1424
+ */
1425
+ changed(file, entry) {
1426
+ this.#designSystem.changed(file, entry);
1427
+ }
1428
+ /**
1429
+ * Closes the environment's type-facts service while retaining native compiler state and producer
1430
+ * inputs.
1431
+ */
1432
+ closeTypeFacts() {
1433
+ this.#designSystem.close();
1434
+ }
1435
+ /**
1436
+ * Closes type facts and clears virtual references. Producer inputs and native compiler state
1437
+ * remain allocated.
1438
+ */
1439
+ close() {
1440
+ this.closeTypeFacts();
1441
+ this.#registry?.clear();
1442
+ }
1443
+ /**
1444
+ * Starts a compilation cycle by clearing inputs and loading a fresh design system.
1445
+ *
1446
+ * The operation clears virtual references and build output. It runs after earlier environment
1447
+ * operations have finished.
1448
+ *
1449
+ * @param context - Vite resolver and watch operations for this environment.
1450
+ * @returns A promise that resolves after compiler initialization, or rejects if initialization
1451
+ * fails.
1452
+ */
1453
+ start(context) {
1454
+ return this.#inTurn(async () => {
1455
+ this.#designSystem.reset();
1456
+ this.#inputs.clear();
1457
+ this.registry.clear();
1458
+ this.buildOutput = void 0;
1459
+ await this.#designSystem.ensure(context, () => {
1460
+ this.revision++;
1461
+ });
1462
+ });
1463
+ }
1464
+ /**
1465
+ * Applies any pending CSS changes and records producers whose JavaScript changed.
1466
+ *
1467
+ * @param context - Vite resolver and watch operations.
1468
+ * @returns A promise that resolves after the serialized refresh. Initial loading failures reject
1469
+ * it.
1470
+ */
1471
+ refreshDesignSystem(context) {
1472
+ return this.#inTurn(async () => {
1473
+ await this.#refresh(context);
1474
+ });
1475
+ }
1476
+ /**
1477
+ * Compiles a source producer and records its input for document or explicit CSS emission.
1478
+ *
1479
+ * Compilation runs after design-system refresh and earlier environment work. A successful result
1480
+ * replaces the recorded producer input.
1481
+ *
1482
+ * @param code - Source text received before Stillwind transformation.
1483
+ * @param id - Full Vite source identity, including any query suffix.
1484
+ * @param context - Vite resolution, watch, warning, and optional upstream-map operations.
1485
+ * @returns A promise for the transformed module, or `undefined` when the compiler produces no
1486
+ * code.
1487
+ */
1488
+ compile(code, id, context) {
1489
+ return this.#compile(code, id, context, false);
1490
+ }
1491
+ /**
1492
+ * Compiles source for a stylesheet projection and forces its styles into document selection.
1493
+ *
1494
+ * A successful input is marked as a projection and made automatic even when the source uses
1495
+ * explicit CSS values.
1496
+ *
1497
+ * @param code - Original producer source read for the projection.
1498
+ * @param id - Full identity of the projected producer.
1499
+ * @param context - Resolver, watcher, and warning operations for the projection.
1500
+ * @returns A promise for the transformed producer, or `undefined` when the compiler produces no
1501
+ * code.
1502
+ */
1503
+ compileProjection(code, id, context) {
1504
+ return this.#compile(code, id, context, true);
1505
+ }
1506
+ /**
1507
+ * Serializes producer compilation and updates recorded input after a successful transform.
1508
+ *
1509
+ * @param code - Producer source before Stillwind compilation.
1510
+ * @param id - Full Vite producer identity.
1511
+ * @param context - Compilation operations and optional upstream source map.
1512
+ * @param projection - Whether to mark the result as an automatic stylesheet projection.
1513
+ * @returns A promise for the transformed module, or `undefined` if no code was produced.
1514
+ */
1515
+ #compile(code, id, context, projection) {
1516
+ return this.#inTurn(async () => {
1517
+ await this.#refresh(context);
1518
+ const output = await compileProducer(this.#designSystem.compiler, this.settings, this.config, this.registry, code, id, context, this.#inputs.get(id));
1519
+ if (!output) return;
1520
+ if (projection) {
1521
+ output.input.manual = false;
1522
+ output.input.projection = true;
1523
+ }
1524
+ this.#inputs.set(id, output.input);
1525
+ return output.result;
1526
+ });
1527
+ }
1528
+ /**
1529
+ * Marks a recovered producer as a stylesheet projection.
1530
+ *
1531
+ * @param id - Exact identity of an input already recorded in this environment.
1532
+ * @returns A promise that resolves after the input is updated. Missing inputs have no effect.
1533
+ */
1534
+ markProjection(id) {
1535
+ return this.#inTurn(async () => {
1536
+ const input = this.#inputs.get(id);
1537
+ if (input) this.#inputs.set(id, {
1538
+ ...input,
1539
+ projection: true
1540
+ });
1541
+ });
1542
+ }
1543
+ /**
1544
+ * Replaces the stylesheet projection imports recorded for an importer.
1545
+ *
1546
+ * @param id - Full identity of the importing module.
1547
+ * @param sources - Projection specifiers mapped to their resolved producer identities.
1548
+ * @returns A promise that resolves after registry references are updated and unused previous
1549
+ * references are removed.
1550
+ */
1551
+ projections(id, sources) {
1552
+ return this.#inTurn(async () => {
1553
+ this.registry.projections(id, sources);
1554
+ });
1555
+ }
1556
+ /**
1557
+ * Removes one source identity from producer inputs, virtual references, and the native compiler.
1558
+ *
1559
+ * @param id - Exact producer identity, including its query suffix.
1560
+ * @returns A promise resolving to true when a producer input was removed.
1561
+ */
1562
+ removeSource(id) {
1563
+ return this.#remove(id, false);
1564
+ }
1565
+ /**
1566
+ * Removes every producer identity associated with a file, including query-qualified inputs.
1567
+ *
1568
+ * @param id - File identity. Its query is ignored when matching producer inputs and references.
1569
+ * @returns A promise resolving to true when at least one producer input was removed.
1570
+ */
1571
+ removeFile(id) {
1572
+ return this.#remove(id, true);
1573
+ }
1574
+ /**
1575
+ * Removes matching producer inputs and their associated compiler artifacts.
1576
+ *
1577
+ * @param id - Producer or file identity to remove.
1578
+ * @param file - Whether to match all query variants of the underlying file.
1579
+ * @returns A promise resolving to true when at least one recorded input was removed.
1580
+ */
1581
+ #remove(id, file) {
1582
+ return this.#inTurn(async () => {
1583
+ this.registry.remove(id, file);
1584
+ let removed = false;
1585
+ for (const [key, input] of this.#inputs) if (file ? cleanModuleId(input.id) === cleanModuleId(id) : input.id === id) {
1586
+ this.#inputs.delete(key);
1587
+ if (this.#designSystem.initialized) this.#designSystem.compiler.native.remove(input.moduleId);
1588
+ removed = true;
1589
+ }
1590
+ return removed;
1591
+ });
1592
+ }
1593
+ /**
1594
+ * Reserves identifiers from authored CSS before generating conflicting compiler identifiers.
1595
+ *
1596
+ * @param id - Identity of the authored stylesheet. Its query is ignored for the compiler module
1597
+ * path.
1598
+ * @param code - Authored CSS text containing identifiers to reserve.
1599
+ * @param context - Resolver and watch operations used if the design system needs initialization.
1600
+ * @returns A promise that resolves after identifiers are registered in the native compiler.
1601
+ */
1602
+ reserveAuthoredCss(id, code, context) {
1603
+ return this.#inTurn(async () => {
1604
+ await this.#designSystem.ensure(context, () => {
1605
+ this.revision++;
1606
+ });
1607
+ this.#designSystem.compiler.native.reserveAuthoredCss(compilerModuleId(this.settings.projectRoot, cleanModuleId(id)), code);
1608
+ });
1609
+ }
1610
+ /**
1611
+ * Plans document styles for automatic producers after applying pending CSS changes.
1612
+ *
1613
+ * @param context - Resolver and watch operations for resources referenced by the selected styles.
1614
+ * @param complete - Whether the caller has collected the complete application graph. Defaults to
1615
+ * observed coverage.
1616
+ * @param selection - Optional compiler module paths without query suffixes. Omission selects all
1617
+ * automatic inputs. An empty list selects none.
1618
+ * @returns A promise for an ordered stylesheet with resolved resources and browser-ready parts.
1619
+ */
1620
+ documentPlan(context, complete = false, selection) {
1621
+ return this.#inTurn(async () => {
1622
+ await this.#refresh(context);
1623
+ return this.#plan(this.#documentModules(selection), context, complete);
1624
+ });
1625
+ }
1626
+ /**
1627
+ * Plans styles for explicitly selected compiler modules.
1628
+ *
1629
+ * @param modules - Compiler module identities in selection order, including manual producers when
1630
+ * needed.
1631
+ * @param context - Resolver and watch operations for referenced resources.
1632
+ * @param complete - Whether the selection comes from a complete application graph. Defaults to
1633
+ * observed coverage.
1634
+ * @returns A promise for the stylesheet and its ordered parts after any design-system refresh.
1635
+ */
1636
+ modulePlan(modules, context, complete = false) {
1637
+ return this.#inTurn(async () => {
1638
+ await this.#refresh(context);
1639
+ return this.#plan(modules, context, complete);
1640
+ });
1641
+ }
1642
+ /**
1643
+ * Builds a development snapshot without incrementing the publication revision.
1644
+ *
1645
+ * @param context - Resolver and watch operations for the current stylesheet.
1646
+ * @returns A promise for document parts and producer dependencies at the current revision.
1647
+ */
1648
+ snapshot(context) {
1649
+ return this.#inTurn(async () => {
1650
+ await this.#refresh(context);
1651
+ return this.#snapshot(await this.#plan(this.#documentModules(), context));
1652
+ });
1653
+ }
1654
+ /**
1655
+ * Advances the publication revision and delivers a current document stylesheet snapshot.
1656
+ *
1657
+ * The operation is serialized with compilation. A planning failure rejects before the callback is
1658
+ * called.
1659
+ *
1660
+ * @param context - Resolver and watch operations for stylesheet planning.
1661
+ * @param send - Receives the snapshot if its revision is still current when planning finishes.
1662
+ * @returns A promise that resolves after planning and any delivery.
1663
+ */
1664
+ publish(context, send) {
1665
+ return this.#inTurn(async () => {
1666
+ await this.#refresh(context);
1667
+ const revision = ++this.revision;
1668
+ const plan = await this.#plan(this.#documentModules(), context);
1669
+ if (revision === this.revision) send(this.#snapshot(plan));
1670
+ });
1671
+ }
1672
+ /**
1673
+ * Consumes producer identities changed by design-system reloads since the previous call.
1674
+ *
1675
+ * @returns A copy of the pending identities. The internal set is cleared.
1676
+ */
1677
+ takeThemeChanges() {
1678
+ const changes = new Set(this.#themeChanges);
1679
+ this.#themeChanges.clear();
1680
+ return changes;
1681
+ }
1682
+ /**
1683
+ * Refreshes the design system and records compiler modules requiring JavaScript invalidation.
1684
+ *
1685
+ * @param context - Resolver and watch operations for CSS reloads.
1686
+ * @returns A promise that resolves after refresh and invalidation callbacks.
1687
+ */
1688
+ async #refresh(context) {
1689
+ await this.#designSystem.refresh(context, () => {
1690
+ this.revision++;
1691
+ }, (modules) => {
1692
+ for (const module of modules) this.#themeChanges.add(module);
1693
+ if (modules.length) this.invalidate([...this.#inputs.values()].filter((input) => modules.includes(input.moduleId)).map((input) => input.id));
1694
+ });
1695
+ }
1696
+ /**
1697
+ * Selects automatic producer identities for document stylesheet planning.
1698
+ *
1699
+ * @param selection - Optional compiler module paths without query suffixes. An empty list selects
1700
+ * no inputs.
1701
+ * @returns Compiler module identities from nonmanual inputs, in their recorded order.
1702
+ */
1703
+ #documentModules(selection) {
1704
+ return [...this.#inputs.values()].filter((input) => !input.manual && (!selection || selection.includes(cleanModuleId(input.moduleId)))).map((input) => input.moduleId);
1705
+ }
1706
+ /**
1707
+ * Resolves a stylesheet using the initialized compiler and current environment revision.
1708
+ *
1709
+ * @param modules - Compiler module identities selected for the stylesheet.
1710
+ * @param context - Resolver and watch operations for referenced resources.
1711
+ * @param complete - Whether to claim complete application coverage for this selection.
1712
+ * @returns A promise for resolved CSS and its ordered parts.
1713
+ */
1714
+ #plan(modules, context, complete = false) {
1715
+ return resolveStylesheet(this.#designSystem, this.settings, this.browserSources, this.revision, modules, context, complete);
1716
+ }
1717
+ /**
1718
+ * Adds the current composition graph to a resolved development stylesheet.
1719
+ *
1720
+ * @param plan - Resolved stylesheet plan whose revision and parts are ready for the browser.
1721
+ * @returns A snapshot containing the plan's revision and parts plus dependencies from all
1722
+ * recorded inputs.
1723
+ */
1724
+ #snapshot(plan) {
1725
+ return {
1726
+ revision: plan.revision,
1727
+ parts: plan.parts,
1728
+ dependencies: Object.fromEntries([...this.#inputs.values()].map((input) => [input.moduleId, input.dependencies]))
1729
+ };
1730
+ }
1731
+ /**
1732
+ * Runs an operation after earlier work and always releases the queue afterward.
1733
+ *
1734
+ * The queue release is independent of the operation result, so one failed operation does not
1735
+ * block later work.
1736
+ *
1737
+ * @param operation - Asynchronous compiler or registry operation. It must not enqueue and await
1738
+ * another environment operation.
1739
+ * @returns A promise for the operation's result, preserving any rejection.
1740
+ */
1741
+ async #inTurn(operation) {
1742
+ const previous = this.#work;
1743
+ let release;
1744
+ this.#work = new Promise((resolve) => {
1745
+ release = resolve;
1746
+ });
1747
+ await previous;
1748
+ try {
1749
+ return await operation();
1750
+ } finally {
1751
+ release();
1752
+ }
1753
+ }
1754
+ };
1755
+ // src/vite/project.ts
1756
+ /**
1757
+ * Creates project state shared by compiler, development, and build plugins.
1758
+ *
1759
+ * Call `configure` before environment initialization, then `attachServer` when serving. Close the
1760
+ * project when its build or server lifetime ends.
1761
+ *
1762
+ * @param supplied - Configuration discovery, compiler overrides, and production CSS emission mode.
1763
+ * Omission reads stillwind.config.* when configure runs.
1764
+ * @param applicationRoot - Called during each configuration evaluation. Its directory overrides
1765
+ * Vite's root as the base for discovery and inline paths. Undefined uses Vite's root.
1766
+ * @returns An unconfigured project whose environments are created lazily.
1767
+ */
1768
+ function createViteProject(supplied = {}, applicationRoot = () => void 0) {
1769
+ const settings = {
1770
+ watching: false,
1771
+ cssWatching: false,
1772
+ compilerMode: "release",
1773
+ projectRoot: "",
1774
+ assetsDirectory: "assets",
1775
+ publicBase: "/",
1776
+ sourceMaps: false,
1777
+ devSourceMaps: false,
1778
+ minifyCss: true
1779
+ };
1780
+ const config = {};
1781
+ const generations = /* @__PURE__ */ new WeakMap();
1782
+ let claimed = false;
1783
+ const configurationFiles = /* @__PURE__ */ new Set();
1784
+ let resolvedViteConfig;
1785
+ let configurationDirty = false;
1786
+ let configurationDependencies = [];
1787
+ let missingConfigurations = [];
1788
+ const environments = /* @__PURE__ */ new Map();
1789
+ let bindings = /* @__PURE__ */ new WeakMap();
1790
+ /**
1791
+ * Gets or creates the compiler state owned by one Vite environment.
1792
+ * @param owner - Owning Vite instance, or a name selecting the current state. Omission selects `client`.
1793
+ * @returns The retained environment state. Newly created non-client states invalidate their
1794
+ * affected modules in the corresponding development module graph.
1795
+ */
1796
+ const environment = (owner = "client") => {
1797
+ const name = typeof owner === "string" ? owner : owner.name;
1798
+ let state = typeof owner === "string" ? environments.get(name) : bindings.get(owner);
1799
+ if (!state) {
1800
+ state = new ViteEnvironment(name, settings, config, (ids) => {
1801
+ if (name === "client") return;
1802
+ const graph = settings.devServerRef?.environments[name]?.moduleGraph;
1803
+ for (const id of ids) for (const module of graph?.getModulesByFile(cleanModuleId(id)) ?? []) graph.invalidateModule(module);
1804
+ });
1805
+ environments.set(name, state);
1806
+ if (typeof owner !== "string") bindings.set(owner, state);
1807
+ }
1808
+ return state;
1809
+ };
1810
+ const closeEnvironment = (owner) => {
1811
+ const state = bindings.get(owner);
1812
+ if (!state) return;
1813
+ state.close();
1814
+ if (settings.watching && environments.get(owner.name) === state) environments.delete(owner.name);
1815
+ };
1816
+ /** Releases checker services in all currently retained compiler environments. */
1817
+ const closeTypeFacts = () => {
1818
+ for (const state of environments.values()) state.closeTypeFacts();
1819
+ };
1820
+ /**
1821
+ * Replaces compiler environments and applied settings after resolving project configuration.
1822
+ * @param viteConfig - Resolved Vite configuration supplying root, asset, source-map, and watch settings.
1823
+ * @returns A promise that resolves after old environments close and configuration dependencies
1824
+ * and missing paths replace the previous discovery state.
1825
+ * @throws If the emission mode is invalid, project configuration fails, or an old environment cannot close.
1826
+ */
1827
+ const configure = async (viteConfig) => {
1828
+ const { emission, ...inline } = supplied;
1829
+ if (emission !== void 0 && emission !== "single" && emission !== "split") throw new Error("config.emission: must be single or split");
1830
+ const cssTarget = viteConfig.environments.client?.build.cssTarget ?? viteConfig.build.cssTarget;
1831
+ const resolved = await resolveIntegrationConfig(inline, applicationRoot() ?? viteConfig.root, { target: inheritCssTarget(cssTarget) });
1832
+ for (const state of environments.values()) state.close();
1833
+ environments.clear();
1834
+ bindings = /* @__PURE__ */ new WeakMap();
1835
+ for (const key of Object.keys(config)) delete config[key];
1836
+ Object.assign(config, resolved.config, { emission });
1837
+ configurationFiles.clear();
1838
+ configurationDependencies = resolved.dependencies;
1839
+ missingConfigurations = resolved.missing;
1840
+ for (const file of [...resolved.dependencies, ...resolved.missing]) configurationFiles.add(file);
1841
+ resolvedViteConfig = viteConfig;
1842
+ configurationDirty = false;
1843
+ settings.projectRoot = resolve(viteConfig.root, config.root ?? ".");
1844
+ settings.assetsDirectory = viteConfig.build.assetsDir;
1845
+ settings.publicBase = viteConfig.base;
1846
+ settings.sourceMaps = Boolean(viteConfig.build.sourcemap);
1847
+ settings.devSourceMaps = Boolean(viteConfig.css.devSourcemap);
1848
+ settings.minifyCss = viteConfig.build.cssMinify !== false;
1849
+ settings.cssTargets = settings.minifyCss ? minifyTargets(config.target) : void 0;
1850
+ settings.watching = viteConfig.command === "serve";
1851
+ settings.compilerMode = settings.watching ? "development" : "release";
1852
+ };
1853
+ /** Detaches the current server's change listeners and closes its configuration discovery watchers. */
1854
+ let stopCssWatching = () => {};
1855
+ /**
1856
+ * Replaces server watch registrations and retains the server for module invalidation and HMR.
1857
+ * @param server - Configured development server. A null watch setting disables these watches.
1858
+ * @throws If a missing configuration's parent directory cannot be watched.
1859
+ */
1860
+ const attachServer = (server) => {
1861
+ settings.devServerRef = server;
1862
+ stopCssWatching();
1863
+ settings.cssWatching = server.config.server.watch !== null;
1864
+ if (!settings.cssWatching) return;
1865
+ /**
1866
+ * Restarts on configuration changes or invalidates affected compiler environments.
1867
+ * @param event - Watch event. Only `add`, `change`, and `unlink` are handled.
1868
+ * @param file - Changed filesystem path, normalized before dependency lookup.
1869
+ */
1870
+ const changed = (event, file) => {
1871
+ if (event !== "add" && event !== "change" && event !== "unlink") return;
1872
+ const path = resolve(file);
1873
+ if (configurationFiles.has(path)) {
1874
+ server.restart();
1875
+ return;
1876
+ }
1877
+ for (const state of environments.values()) state.changed(path, event !== "change");
1878
+ };
1879
+ /** Closes discovery watchers, detaches server listeners, and clears the CSS-watching flag. */
1880
+ const stop = () => {
1881
+ for (const watcher of discoveryWatchers) watcher.close();
1882
+ server.watcher.off("all", changed);
1883
+ server.httpServer?.off("close", stop);
1884
+ settings.cssWatching = false;
1885
+ };
1886
+ const discoveryWatchers = [...new Set(missingConfigurations.map(dirname))].map((directory) => watch(directory, (_event, filename) => {
1887
+ if (filename && configurationFiles.has(resolve(directory, String(filename)))) server.restart();
1888
+ }));
1889
+ server.watcher.on("all", changed);
1890
+ server.watcher.add(configurationDependencies);
1891
+ server.httpServer?.once("close", stop);
1892
+ stopCssWatching = stop;
1893
+ };
1894
+ /** Detaches server listeners, closes discovery watchers, and closes every retained compiler environment. */
1895
+ const close = () => {
1896
+ stopCssWatching();
1897
+ for (const state of environments.values()) state.close();
1898
+ };
1899
+ /**
1900
+ * Publishes a CSS snapshot through the matching environment's HMR channel when serving.
1901
+ * @param name - Vite environment name, or undefined for `client`.
1902
+ * @param context - Resolver and watch operations used to refresh the environment's CSS.
1903
+ * @returns A promise that resolves after publication, or immediately when no active server exists.
1904
+ * @throws If refreshing the environment or generating its CSS snapshot fails.
1905
+ */
1906
+ const publish = (name, context) => {
1907
+ if (!settings.watching || !settings.devServerRef) return Promise.resolve();
1908
+ return environment(name).publish(context, (snapshot) => {
1909
+ settings.devServerRef?.environments[name ?? "client"]?.hot.send({
1910
+ type: "custom",
1911
+ event: "stillwind:css",
1912
+ data: snapshot
1913
+ });
1914
+ });
1915
+ };
1916
+ const project = {
1917
+ forConfig: (viteConfig) => {
1918
+ let generation = generations.get(viteConfig);
1919
+ if (!generation) {
1920
+ generation = claimed ? createViteProject(supplied, applicationRoot) : project;
1921
+ claimed = true;
1922
+ generations.set(viteConfig, generation);
1923
+ }
1924
+ return generation;
1925
+ },
1926
+ config,
1927
+ configurationFiles,
1928
+ configurationChanged: (id) => {
1929
+ if (!configurationFiles.has(resolve(id))) return false;
1930
+ configurationDirty = true;
1931
+ return true;
1932
+ },
1933
+ refreshConfiguration: async () => {
1934
+ if (configurationDirty && resolvedViteConfig) await configure(resolvedViteConfig);
1935
+ },
1936
+ settings,
1937
+ environment,
1938
+ closeEnvironment,
1939
+ configure,
1940
+ attachServer,
1941
+ closeTypeFacts,
1942
+ close,
1943
+ inputs: (name) => environment(name).inputs,
1944
+ moduleRegistry: (name) => environment(name).registry,
1945
+ producerSpecifier: (id, name) => environment(name).registry.source("producer", id),
1946
+ valueSpecifier: (id, name) => environment(name).registry.source("value", id),
1947
+ compile: (name, code, id, context) => environment(name).compile(code, id, context),
1948
+ documentPlan: (name, context, complete = false, selection) => environment(name).documentPlan(context, complete, selection),
1949
+ snapshot: (name, context) => environment(name).snapshot(context),
1950
+ publish,
1951
+ publicSourceMap: (name, map) => publicCssSourceMap(environment(name).browserSources, map),
1952
+ cssForBrowser: (name, output, replacements) => cssForBrowser(environment(name).browserSources, output, replacements),
1953
+ buildOutput: (name) => environment(name).buildOutput ?? {},
1954
+ setBuildOutput: (name, output) => {
1955
+ environment(name).buildOutput = output;
1956
+ }
1957
+ };
1958
+ return project;
1959
+ }
1960
+ // src/vite/projection-imports.ts
1961
+ /**
1962
+ * Finds literal projection imports in a source document without evaluating its code.
1963
+ * @param code - Original source, optionally in a supported component format.
1964
+ * @param id - Full source identity whose cleaned path determines the frontend and parser language.
1965
+ * @returns Distinct static and literal dynamic requests ending in ?stillwind.css, in traversal order.
1966
+ * @throws If preparation or parsing fails.
1967
+ */
1968
+ async function projectionImports(code, id) {
1969
+ if (!code.includes("stillwind.css")) return [];
1970
+ const file = cleanModuleId(id);
1971
+ const { format, syntax } = fileSourceKind(id);
1972
+ const prepared = await prepareSource({
1973
+ resolverId: id,
1974
+ checkerFileName: file,
1975
+ projectionFileName: file,
1976
+ moduleId: id,
1977
+ document: {
1978
+ code,
1979
+ uri: pathToFileURL(file).href,
1980
+ format
1981
+ },
1982
+ syntax
1983
+ });
1984
+ const script = prepared.kind === "projected" ? prepared.projection.code : code;
1985
+ const parser = prepared.kind === "projected" ? prepared.projection.syntax : syntax;
1986
+ const parsed = parseSync(file, script, {
1987
+ lang: parser.language,
1988
+ sourceType: parser.moduleKind
1989
+ });
1990
+ if (parsed.errors.length) throw new Error(`${id}: ${parsed.errors.map((error) => error.message).join("\n")}`);
1991
+ const imports = /* @__PURE__ */ new Set();
1992
+ /**
1993
+ * Collects literal projection requests while traversing enumerable AST fields.
1994
+ * @param node - Parser AST node or child value. Primitive values are skipped.
1995
+ */
1996
+ const visit = (node) => {
1997
+ if (!node || typeof node !== "object") return;
1998
+ const record = node;
1999
+ if (record.declare === true) return;
2000
+ if (record.type === "ImportDeclaration" && record.importKind !== "type" || (record.type === "ExportNamedDeclaration" || record.type === "ExportAllDeclaration") && record.exportKind !== "type" || record.type === "ImportExpression") {
2001
+ const source = record.source;
2002
+ if (typeof source?.value === "string" && source.value.endsWith("?stillwind.css")) imports.add(source.value);
2003
+ }
2004
+ for (const value of Object.values(record)) if (Array.isArray(value)) value.forEach(visit);
2005
+ else if (value && typeof value === "object") visit(value);
2006
+ };
2007
+ visit(parsed.program);
2008
+ return [...imports];
2009
+ }
2010
+ // src/vite/transform.ts
2011
+ /**
2012
+ * Creates source transform and watch hooks for the project compiler plugin.
2013
+ *
2014
+ * Development changes publish CSS after compilation. Invalid projection imports fail through the
2015
+ * Vite hook context.
2016
+ *
2017
+ * @param project - Project configured and initialized by the compiler plugin.
2018
+ * @param virtualModules - Virtual module hooks for the same project, used to reload cached
2019
+ * generated modules.
2020
+ * @param options - Source selection and ordering required by the framework integration.
2021
+ * @returns Hooks that recompile cached producers, register stylesheet projections, reserve authored
2022
+ * CSS identifiers, and remove deleted inputs.
2023
+ */
2024
+ function transformHooks(project, virtualModules, options = {}) {
2025
+ const { settings, publish, compile } = project;
2026
+ const cachedVirtualModules = /* @__PURE__ */ new Map();
2027
+ return {
2028
+ /**
2029
+ * Selects cached modules that need current compiler state and records virtual modules for reloading.
2030
+ * @param module - Cached module descriptor whose id includes any source query.
2031
+ * @returns Whether to rerun transformation for Stillwind virtual modules or supported application sources.
2032
+ */
2033
+ shouldTransformCachedModule({ id }) {
2034
+ if (id.startsWith("\0stillwind:")) {
2035
+ const name = this.environment?.name ?? "client";
2036
+ let modules = cachedVirtualModules.get(name);
2037
+ if (!modules) {
2038
+ modules = /* @__PURE__ */ new Set();
2039
+ cachedVirtualModules.set(name, modules);
2040
+ }
2041
+ modules.add(id);
2042
+ return true;
2043
+ }
2044
+ return /\.(?:[cm]?[jt]sx?|astro|svelte|vue)$/.test(cleanModuleId(id)) && !id.includes("node_modules");
2045
+ },
2046
+ /**
2047
+ * Invalidates changed configuration or removes deleted source state and publishes resulting CSS.
2048
+ * @param id - Watched filesystem identity.
2049
+ * @param change - Vite event. Source removal is performed only for delete events.
2050
+ * @returns Completion of removal and publication when required.
2051
+ * @throws If environment removal or CSS publication fails.
2052
+ */
2053
+ async watchChange(id, change) {
2054
+ if (project.configurationChanged(id)) return;
2055
+ if (change.event !== "delete") return;
2056
+ const name = this.environment?.name;
2057
+ if (await project.environment(name).removeFile(id)) await publish(name, this);
2058
+ },
2059
+ transform: {
2060
+ order: options.order === "normal" ? void 0 : "pre",
2061
+ /**
2062
+ * Reserves authored CSS names, registers source projections, and compiles supported producers.
2063
+ * @param code - Source after earlier transforms in the configured order.
2064
+ * @param id - Full Vite identity, including queries that select distinct source.
2065
+ * @returns Compiler output, a reloaded virtual module, or undefined when no transformed source is needed.
2066
+ * @throws If a projection cannot resolve or pass access checks, or compilation or publication fails.
2067
+ */
2068
+ async handler(code, id) {
2069
+ const name = this.environment?.name;
2070
+ if (cachedVirtualModules.get(name ?? "client")?.delete(id)) {
2071
+ const load = virtualModules.load;
2072
+ if (typeof load === "function") return load.call(this, id);
2073
+ }
2074
+ if (isAuthoredStylesheet(id)) {
2075
+ await project.environment(name).reserveAuthoredCss(id, code, this);
2076
+ return;
2077
+ }
2078
+ if (!/\.(?:[cm]?[jt]sx?|astro|svelte|vue)$/.test(cleanModuleId(id)) || id.includes("node_modules") || id.startsWith("\0") || /[?&](?:raw|url|type)(?:[=&]|$)/.test(id)) return;
2079
+ if (options.originalSource) {
2080
+ id = cleanModuleId(id);
2081
+ code = await readFile(await readableFile(id, settings.devServerRef), "utf8");
2082
+ }
2083
+ const projections = /* @__PURE__ */ new Map();
2084
+ for (const specifier of await projectionImports(code, id)) {
2085
+ const source = await this.resolve(specifier.slice(0, -14), id, {
2086
+ skipSelf: true,
2087
+ custom: { "react-router:dot-server": true }
2088
+ });
2089
+ if (!source || source.external) this.error(`Cannot resolve Stillwind projection ${specifier}`);
2090
+ await readableFile(source.id, settings.devServerRef);
2091
+ projections.set(specifier, source.id);
2092
+ }
2093
+ if (!/stillwind\/(?:alpine|astro|lit|preact|qwik|react|solid|svelte|vanilla|vue|module-css)/.test(code)) {
2094
+ if (project.inputs(name).get(id)) {
2095
+ await project.environment(name).removeSource(id);
2096
+ await publish(name, this);
2097
+ }
2098
+ await project.environment(name).projections(id, projections);
2099
+ return;
2100
+ }
2101
+ await project.environment(name).projections(id, projections);
2102
+ const context = options.originalSource ? {
2103
+ resolve: this.resolve.bind(this),
2104
+ addWatchFile: this.addWatchFile.bind(this),
2105
+ warn: this.warn.bind(this)
2106
+ } : this;
2107
+ const result = await compile(name, code, id, context);
2108
+ await publish(name, this);
2109
+ return result;
2110
+ }
2111
+ }
2112
+ };
2113
+ }
2114
+ /**
2115
+ * Checks whether a module contains authored CSS whose identifiers must be reserved.
2116
+ *
2117
+ * @param id - Vite module identity, optionally containing a resource query.
2118
+ * @returns True for a plain `.css` file that is neither virtual nor query-qualified.
2119
+ */
2120
+ function isAuthoredStylesheet(id) {
2121
+ if (!cleanModuleId(id).endsWith(".css")) return false;
2122
+ if (id.startsWith("virtual:") || id.includes("?")) return false;
2123
+ return !cleanModuleId(id).replaceAll("\\", "/").startsWith("\0stillwind:");
2124
+ }
2125
+ // src/vite/virtual-modules.ts
2126
+ /**
2127
+ * Public specifier for the packaged development runtime, resolved through the published Vite
2128
+ * entrypoint.
2129
+ */
2130
+ const runtimeEntry = "virtual:stillwind/runtime-entry";
2131
+ /** Public specifier for the optional runtime that renders development CSS source maps. */
2132
+ const sourceMapEntry = "virtual:stillwind/runtime-source-map";
2133
+ /**
2134
+ * Locates a packaged runtime module beside the published Vite entrypoint.
2135
+ *
2136
+ * @param file - Runtime basename without an extension, such as `runtime` or `runtime-source-map`.
2137
+ * @returns Absolute path to the runtime JavaScript file.
2138
+ */
2139
+ function runtimeFile(file) {
2140
+ return fileURLToPath(new URL(`./${file}.js`, import.meta.resolve("@stillwind/integration/vite")));
2141
+ }
2142
+ /**
2143
+ * Creates hooks that resolve registered Stillwind references and load their generated modules.
2144
+ *
2145
+ * Unregistered references fail through the hook context. Projections compile source for CSS without
2146
+ * importing its application JavaScript.
2147
+ *
2148
+ * @param project - Configured project whose environment registry owns the references and producer
2149
+ * inputs.
2150
+ * @returns Resolution and loading hooks for runtime, producer, projection, fragment, CSS value, and
2151
+ * stylesheet snapshot modules.
2152
+ */
2153
+ function virtualModuleHooks(project) {
2154
+ const { settings, inputs, cssForBrowser, moduleRegistry, producerSpecifier, documentPlan, publish } = project;
2155
+ return {
2156
+ /**
2157
+ * Resolves runtime aliases and issued references in the current environment's registry.
2158
+ * @param id - Authored request or resolved virtual identity.
2159
+ * @param importer - Full importer identity required for registered projection edges.
2160
+ * @returns A resolved virtual identity or packaged runtime path, or undefined for unrelated requests.
2161
+ * @throws If a projection or source-backed reference is unregistered.
2162
+ */
2163
+ async resolveId(id, importer) {
2164
+ const registry = moduleRegistry(this.environment?.name);
2165
+ if (id === runtimeEntry) return runtimeFile("runtime");
2166
+ if (id === sourceMapEntry) return runtimeFile("runtime-source-map");
2167
+ if (id.endsWith("?stillwind.css")) {
2168
+ const registered = registry.projection(id, importer);
2169
+ if (!registered) this.error("Unregistered Stillwind projection");
2170
+ return registered.replace("virtual:stillwind/", "\0stillwind:");
2171
+ }
2172
+ if (id === "virtual:stillwind/runtime" || id === "virtual:stillwind.css" || id === "\0stillwind:runtime") return runtimeId;
2173
+ if (id === "virtual:stillwind/snapshot.css" || id === "\0stillwind:snapshot.css") return "\0stillwind:snapshot.css";
2174
+ if (/^(?:virtual:stillwind\/|\0stillwind:)(?:value|fragment|producer|projection):/.test(id)) {
2175
+ if (!registry.get(id)) this.error("Unregistered Stillwind module");
2176
+ return id.replace("virtual:stillwind/", "\0stillwind:");
2177
+ }
2178
+ },
2179
+ /**
2180
+ * Loads generated runtime, producer, projection, fragment, and explicit CSS-value modules.
2181
+ * @param id - Resolved virtual identity issued or recognized by this environment.
2182
+ * @returns Generated JavaScript or snapshot CSS and its map, or undefined for unrelated modules.
2183
+ * @throws If a reference is invalid, source or resource access fails, or CSS planning or compilation fails.
2184
+ */
2185
+ async load(id) {
2186
+ const name = this.environment?.name;
2187
+ const registry = moduleRegistry(name);
2188
+ const entry = registry.get(id);
2189
+ if ([
2190
+ "\0stillwind:producer:",
2191
+ "\0stillwind:projection:",
2192
+ "\0stillwind:fragment:",
2193
+ "\0stillwind:value:"
2194
+ ].some((prefix) => id.startsWith(prefix)) && !entry) this.error("Unregistered Stillwind module");
2195
+ if (id === "\0stillwind:snapshot.css") {
2196
+ const plan = await documentPlan(name, this);
2197
+ return decodeCssSourceMap(cssForBrowser(name, {
2198
+ css: plan.originalCss,
2199
+ sourceMap: plan.sourceMap,
2200
+ banners: plan.banners
2201
+ }, plan.resourceReplacements));
2202
+ }
2203
+ if (id.startsWith("\0stillwind:producer:")) {
2204
+ if (!settings.watching) return "// Stillwind producer (vite)\nexport {};\n";
2205
+ if (entry?.kind !== "producer") this.error("Invalid Stillwind producer");
2206
+ const producer = entry.moduleId;
2207
+ return `// Stillwind producer (vite)
2208
+ import { register, synchronize, unregister } from ${JSON.stringify(runtimeSpecifier)};
2209
+
2210
+ await synchronize(${project.environment(name).revision});
2211
+ register(${JSON.stringify(producer)});
2212
+ if (import.meta.hot) {
2213
+ import.meta.hot.prune(() => {
2214
+ unregister(${JSON.stringify(producer)});
2215
+ });
2216
+ }
2217
+ `;
2218
+ }
2219
+ if (id.startsWith("\0stillwind:projection:")) {
2220
+ if (entry?.kind !== "projection") this.error("Invalid Stillwind projection");
2221
+ const source = entry.sourceId;
2222
+ const file = await readableFile(source, settings.devServerRef);
2223
+ const context = settings.watching ? {
2224
+ resolve: this.resolve.bind(this),
2225
+ warn: this.warn.bind(this),
2226
+ addWatchFile: (id) => {
2227
+ settings.devServerRef?.watcher.add(cleanModuleId(id));
2228
+ }
2229
+ } : this;
2230
+ context.addWatchFile(source);
2231
+ const result = await project.environment(name).compileProjection(await readFile(file, "utf8"), source, context);
2232
+ await publish(name, context);
2233
+ return {
2234
+ code: `// Stillwind projection (vite)\nimport ${JSON.stringify(producerSpecifier(source, name))};\n`,
2235
+ meta: { stillwind: {
2236
+ ...result?.meta.stillwind,
2237
+ projection: true
2238
+ } }
2239
+ };
2240
+ }
2241
+ if (id === "\0stillwind:runtime") {
2242
+ if (!settings.watching) return "// Stillwind runtime (vite)\nexport {};\n";
2243
+ const snapshot = await project.snapshot(name, this);
2244
+ const endpoint = `${settings.publicBase}__stillwind/css?environment=${encodeURIComponent(name ?? "client")}`;
2245
+ return `// Stillwind runtime (vite)
2246
+ import { createDevelopmentRuntime } from ${JSON.stringify(runtimeEntry)};
2247
+ ${settings.devSourceMaps ? `import { renderCssWithSourceMap } from ${JSON.stringify(sourceMapEntry)};` : ""}
2248
+
2249
+ const runtime = createDevelopmentRuntime({
2250
+ snapshot: ${JSON.stringify(snapshot)},
2251
+ endpoint: ${JSON.stringify(endpoint)},
2252
+ ${settings.devSourceMaps ? "renderCss: renderCssWithSourceMap," : ""}
2253
+ });
2254
+
2255
+ export const register = runtime.register;
2256
+ export const unregister = runtime.unregister;
2257
+ export const synchronize = runtime.synchronize;
2258
+
2259
+ if (import.meta.hot) {
2260
+ import.meta.hot.on("stillwind:css", runtime.apply);
2261
+ import.meta.hot.accept();
2262
+ import.meta.hot.dispose(() => {
2263
+ import.meta.hot.off("stillwind:css", runtime.apply);
2264
+ });
2265
+ }
2266
+ `;
2267
+ }
2268
+ if (id.startsWith("\0stillwind:fragment:")) {
2269
+ if (entry?.kind !== "fragment") this.error("Invalid Stillwind fragment");
2270
+ let css = entry.css;
2271
+ if (!settings.watching && settings.minifyCss) css = minifyStylesheet(css, settings, this).css;
2272
+ const resources = [...entry.resources];
2273
+ for (const [, resource] of resources) await readableFile(resource.id, settings.devServerRef);
2274
+ const imports = resources.map(([, resource], index) => `import asset${index} from ${JSON.stringify(resource.id + (resource.id.includes("?") ? "&url" : "?url"))};\n`);
2275
+ if (settings.watching && settings.devSourceMaps) return [
2276
+ "// Stillwind CSS fragment (vite)\n",
2277
+ ...imports,
2278
+ `import { replaceCssResources } from ${JSON.stringify(sourceMapEntry)};\n`,
2279
+ `export const css = replaceCssResources(${JSON.stringify(css)}, [${resources.map(([placeholder], index) => `[${JSON.stringify(placeholder)}, JSON.stringify(asset${index}).slice(1, -1)]`).join(",")}]);\n`
2280
+ ].join("");
2281
+ const replacements = resources.map(([placeholder], index) => `.replaceAll(${JSON.stringify(placeholder)}, JSON.stringify(asset${index}).slice(1, -1))`).join("");
2282
+ return [
2283
+ "// Stillwind CSS fragment (vite)\n",
2284
+ ...imports,
2285
+ "\n",
2286
+ `export const css = ${JSON.stringify(css)}${replacements};\n`
2287
+ ].join("");
2288
+ }
2289
+ if (id.startsWith("\0stillwind:value:")) {
2290
+ if (entry?.kind !== "value") this.error("Invalid Stillwind value");
2291
+ const sourceId = entry.sourceId;
2292
+ const input = inputs(name).get(sourceId);
2293
+ if (!input) this.error(`No Stillwind producer for ${sourceId}`);
2294
+ const watchSource = settings.watching ? (file) => settings.devServerRef?.watcher.add(cleanModuleId(file)) : this.addWatchFile.bind(this);
2295
+ watchSource(sourceId);
2296
+ const plan = await project.environment(name).modulePlan([input.moduleId], this, !settings.watching);
2297
+ for (const producer of plan.producers) watchSource(resolve(settings.projectRoot, cleanModuleId(producer.module)));
2298
+ for (const file of project.environment(name).designSystem.cssFiles) this.addWatchFile(file);
2299
+ return [
2300
+ "// Stillwind CSS value (vite)\n",
2301
+ "import { cssText } from \"stillwind/css\";\n",
2302
+ ...plan.rawParts.map((part, index) => `import { css as p${index} } from ${JSON.stringify(registry.fragment(settings.watching && settings.devSourceMaps ? cssForBrowser(name, {
2303
+ ...part,
2304
+ banners: []
2305
+ }, /* @__PURE__ */ new Map()) : part.css, plan.resources))};\n`),
2306
+ "\n",
2307
+ "export const parts = [",
2308
+ ...plan.parts.map((part, index) => ` { key: ${JSON.stringify(part.key)}, banners: ${JSON.stringify(part.banners)}, css: p${index} },\n`),
2309
+ "];\n",
2310
+ "export const css = cssText(parts);\n",
2311
+ "export default css;\n"
2312
+ ].join("");
2313
+ }
2314
+ }
2315
+ };
2316
+ }
2317
+ // src/vite/vue.ts
2318
+ /**
2319
+ * Original Vue hooks saved before wrapping. Reusing them prevents repeated configuration from
2320
+ * composing a wrapper with itself.
2321
+ */
2322
+ const hooks = /* @__PURE__ */ new WeakMap();
2323
+ /**
2324
+ * Wraps Vue hooks to compose source maps and reload components with explicit CSS values.
2325
+ *
2326
+ * Only Vue query results with a source map and a recorded Stillwind map are composed. Repeated
2327
+ * calls reuse the saved original hooks. Explicit CSS values require component reloads during
2328
+ * template edits so Vue replaces the component's styles.
2329
+ *
2330
+ * @param plugins - Resolved plugin instances. Hooks on plugins named `vite:vue` are replaced in
2331
+ * place.
2332
+ * @param project - Project containing Stillwind transforms for the corresponding environment and
2333
+ * original Vue file.
2334
+ */
2335
+ function attachVueHooks(plugins, project) {
2336
+ /**
2337
+ * Composes a Vue block's map through the recorded Stillwind transform for its source file.
2338
+ * @param result - Original load or transform result, left unchanged when a required map is absent.
2339
+ * @param id - Full Vue block identity, including its `vue` query.
2340
+ * @param environment - Vite environment whose top-level configuration owns the recorded input.
2341
+ * @returns The original result or a copy containing a serialized composed map.
2342
+ * @throws If the input map cannot be parsed or the maps cannot be composed.
2343
+ */
2344
+ const compose = (result, id, environment) => {
2345
+ if (!result || typeof result !== "object" || !/[?&]vue(?:[=&]|$)/.test(id) || !result.map) return result;
2346
+ const input = (environment ? project.forConfig(environment.getTopLevelConfig()) : project).inputs(environment?.name).get(cleanModuleId(id));
2347
+ if (!input?.sourceMap) return result;
2348
+ const map = typeof result.map === "string" ? JSON.parse(result.map) : result.map;
2349
+ if (!map.sources?.length) return result;
2350
+ return {
2351
+ ...result,
2352
+ map: JSON.stringify(composeFrameworkSourceMap(map, JSON.stringify(input.sourceMap), input.javascript))
2353
+ };
2354
+ };
2355
+ for (const plugin of plugins) {
2356
+ if (plugin.name !== "vite:vue") continue;
2357
+ const original = hooks.get(plugin) ?? {
2358
+ load: plugin.load,
2359
+ transform: plugin.transform
2360
+ };
2361
+ hooks.set(plugin, original);
2362
+ if (original.load) {
2363
+ const hook = original.load;
2364
+ const handler = typeof hook === "function" ? hook : hook.handler;
2365
+ /**
2366
+ * Runs the saved Vue load hook with its original receiver, then composes its map.
2367
+ * @param id - Resolver identity passed by Vite.
2368
+ * @param args - Remaining load-hook arguments forwarded unchanged.
2369
+ * @returns The delegated result with its map composed when the recorded input permits it.
2370
+ * @throws If the original hook or map composition fails.
2371
+ */
2372
+ const wrapped = async function(id, ...args) {
2373
+ return compose(await handler.call(this, id, ...args), id, this.environment);
2374
+ };
2375
+ plugin.load = typeof hook === "function" ? wrapped : {
2376
+ ...hook,
2377
+ handler: wrapped
2378
+ };
2379
+ }
2380
+ if (original.transform) {
2381
+ const hook = original.transform;
2382
+ const handler = typeof hook === "function" ? hook : hook.handler;
2383
+ /**
2384
+ * Composes Vue's map and reloads components with explicit CSS values on template edits.
2385
+ * @param code - Vue block source passed by Vite.
2386
+ * @param id - Resolver identity passed by Vite.
2387
+ * @param args - Remaining transform-hook arguments forwarded unchanged.
2388
+ * @returns Vue's result with a composed map and reloads for components with explicit CSS values.
2389
+ * @throws If the original hook or map composition fails.
2390
+ */
2391
+ const wrapped = async function(code, id, ...args) {
2392
+ const result = compose(await handler.call(this, code, id, ...args), id, this.environment);
2393
+ const file = cleanModuleId(id);
2394
+ if (id !== file || !file.endsWith(".vue") || !result) return result;
2395
+ if (!(this.environment ? project.forConfig(this.environment.getTopLevelConfig()) : project).inputs(this.environment?.name).get(file)?.hasModuleCssImport) return result;
2396
+ const javascript = (typeof result === "string" ? result : result.code)?.toString();
2397
+ if (!javascript) return result;
2398
+ const declaration = javascript.indexOf("export const _rerender_only =");
2399
+ if (declaration < 0) return result;
2400
+ const start = declaration + 7;
2401
+ const updated = javascript.slice(0, start) + "let " + javascript.slice(start + 5) + "\n_rerender_only = false;\n";
2402
+ return typeof result === "string" ? {
2403
+ code: updated,
2404
+ map: null
2405
+ } : {
2406
+ ...result,
2407
+ code: updated
2408
+ };
2409
+ };
2410
+ plugin.transform = typeof hook === "function" ? wrapped : {
2411
+ ...hook,
2412
+ handler: wrapped
2413
+ };
2414
+ }
2415
+ }
2416
+ }
2417
+ // src/vite/plugin.ts
2418
+ /**
2419
+ * Creates Vite plugins that share compiler state across development and production.
2420
+ *
2421
+ * @param config - File discovery, project selection, compiler overrides, and CSS emission mode.
2422
+ * @returns Plugins for compilation, development CSS delivery, and production emission. Use the
2423
+ * array as `plugins: [stillwind()]` to use the project's configuration file.
2424
+ */
2425
+ function stillwind(config = {}) {
2426
+ return createVitePlugins(createViteProject(config));
2427
+ }
2428
+ /**
2429
+ * Creates the compiler, development, and build plugins around an existing project.
2430
+ *
2431
+ * @param project - Project shared by all returned plugins. Its settings are initialized by the
2432
+ * compiler plugin.
2433
+ * @param transform - Ordering and source selection required by a framework's transforms.
2434
+ * @returns Plugins in compiler, development, and build order. Development and build plugins apply
2435
+ * only to their matching Vite command.
2436
+ */
2437
+ function createVitePlugins(project, transform = {}) {
2438
+ const servers = /* @__PURE__ */ new Map();
2439
+ return [
2440
+ {
2441
+ name: "stillwind:compiler",
2442
+ enforce: "pre",
2443
+ /**
2444
+ * Initializes the project owned by this configuration and composes Vue source maps.
2445
+ * @param config - Resolved Vite configuration whose plugin chain includes Stillwind.
2446
+ * @returns Completion of project configuration.
2447
+ * @throws If configuration discovery or evaluation fails.
2448
+ */
2449
+ async configResolved(config) {
2450
+ await project.forConfig(config).configure(config);
2451
+ attachVueHooks(config.plugins, project);
2452
+ },
2453
+ /**
2454
+ * Defers watch registration until the server's plugin setup succeeds.
2455
+ * @param server - Server whose configuration owns the project.
2456
+ * @returns A post hook that attaches watches and records the server's environments.
2457
+ */
2458
+ configureServer(server) {
2459
+ const generation = project.forConfig(server.config);
2460
+ return () => {
2461
+ generation.attachServer(server);
2462
+ servers.set(generation, new Set(Object.values(server.environments)));
2463
+ server.httpServer?.once("close", generation.closeTypeFacts);
2464
+ };
2465
+ },
2466
+ /**
2467
+ * Creates compiler hooks while Vite resolves plugins for an environment.
2468
+ * @param environment - Descriptor supplied during plugin resolution. Runtime hooks receive
2469
+ * their owning instance as this.environment.
2470
+ * @returns Hooks that initialize and close the compiler state owned by this.environment.
2471
+ */
2472
+ applyToEnvironment(environment) {
2473
+ const generation = project.forConfig(environment.getTopLevelConfig());
2474
+ return compilerPlugin(generation, transform, (owner) => {
2475
+ servers.get(generation)?.delete(owner);
2476
+ });
2477
+ },
2478
+ /** Releases projects after all environments owned by their server have closed. */
2479
+ closeServer() {
2480
+ for (const [generation, remaining] of servers) if (remaining.size === 0) {
2481
+ generation.close();
2482
+ servers.delete(generation);
2483
+ }
2484
+ }
2485
+ },
2486
+ {
2487
+ name: "stillwind:development",
2488
+ enforce: "pre",
2489
+ apply: "serve",
2490
+ configureServer(server) {
2491
+ const hook = developmentHooks(project.forConfig(server.config)).configureServer;
2492
+ if (typeof hook === "function") return hook.call(this, server);
2493
+ },
2494
+ applyToEnvironment(environment) {
2495
+ const { hotUpdate } = developmentHooks(project.forConfig(environment.getTopLevelConfig()));
2496
+ return {
2497
+ name: "stillwind:development",
2498
+ hotUpdate: transform.originalSource && typeof hotUpdate === "function" ? {
2499
+ order: "pre",
2500
+ handler: hotUpdate
2501
+ } : hotUpdate
2502
+ };
2503
+ }
2504
+ },
2505
+ {
2506
+ name: "stillwind:build",
2507
+ enforce: "pre",
2508
+ apply: "build",
2509
+ applyToEnvironment(environment) {
2510
+ return {
2511
+ name: "stillwind:build",
2512
+ ...buildHooks(project.forConfig(environment.getTopLevelConfig()))
2513
+ };
2514
+ }
2515
+ }
2516
+ ];
2517
+ }
2518
+ /**
2519
+ * Creates the plugin that owns project configuration, source compilation, and compiler lifetime.
2520
+ *
2521
+ * @param project - Project whose environments are initialized at build start and closed at bundle
2522
+ * close.
2523
+ * @param closed - Records which Vite instance has released its state.
2524
+ * @returns A plugin with `enforce: "pre"` that installs virtual modules and source transforms.
2525
+ */
2526
+ function compilerPlugin(project, transform, closed) {
2527
+ const virtualModules = virtualModuleHooks(project);
2528
+ return {
2529
+ name: "stillwind:compiler",
2530
+ enforce: "pre",
2531
+ perEnvironmentStartEndDuringDev: true,
2532
+ perEnvironmentWatchChangeDuringDev: true,
2533
+ /**
2534
+ * Delegates generated-reference resolution using the current environment's hook context.
2535
+ * @param id - Requested module identity.
2536
+ * @param importer - Importing resolver identity, when available.
2537
+ * @param options - Vite resolution options forwarded unchanged.
2538
+ * @returns The virtual resolver's result, or undefined if it has no callable hook.
2539
+ */
2540
+ resolveId(id, importer, options) {
2541
+ if (typeof virtualModules.resolveId === "function") return virtualModules.resolveId.call(this, id, importer, options);
2542
+ },
2543
+ /**
2544
+ * Delegates generated-module loading through the current environment's registry.
2545
+ * @param id - Resolved module identity.
2546
+ * @param options - Vite load options forwarded unchanged.
2547
+ * @returns The virtual loader's result, or undefined when no callable hook is available.
2548
+ */
2549
+ load(id, options) {
2550
+ if (typeof virtualModules.load === "function") return virtualModules.load.call(this, id, options);
2551
+ },
2552
+ ...transformHooks(project, virtualModules, transform),
2553
+ /**
2554
+ * Refreshes configuration, registers its watches, and starts the current compiler environment.
2555
+ * @returns Completion of configuration refresh and environment initialization.
2556
+ * @throws If refresh or environment startup fails.
2557
+ */
2558
+ async buildStart() {
2559
+ await project.refreshConfiguration();
2560
+ for (const file of project.configurationFiles) this.addWatchFile(file);
2561
+ await project.environment(this.environment).start(this);
2562
+ },
2563
+ /** Releases this environment's state when its plugin container closes. */
2564
+ closeBundle() {
2565
+ project.closeEnvironment(this.environment);
2566
+ closed(this.environment);
2567
+ }
2568
+ };
2569
+ }
2570
+ export { renderChunkStyles as i, stillwind as n, createViteProject as r, createVitePlugins as t };
2571
+
2572
+ //# sourceMappingURL=plugin-C_ZFfzo2.js.map