@gustcss/vite 0.9.2 → 0.10.1

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.
package/dist/index.mjs CHANGED
@@ -3,6 +3,7 @@ import { spawn, spawnSync } from "child_process";
3
3
  import path from "path";
4
4
  import fs from "fs";
5
5
  import { randomBytes } from "crypto";
6
+ import { pathToFileURL } from "node:url";
6
7
  //#region \0rolldown/runtime.js
7
8
  var __create = Object.create;
8
9
  var __defProp = Object.defineProperty;
@@ -21,13 +22,13 @@ var __copyProps = (to, from, except, desc) => {
21
22
  }
22
23
  return to;
23
24
  };
24
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
25
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule || !__hasOwnProp.call(mod, "default") ? __defProp(target, "default", {
25
26
  value: mod,
26
27
  enumerable: true
27
28
  }) : target, mod));
28
29
  var __require = /* #__PURE__ */ (() => createRequire(import.meta.url))();
29
30
  //#endregion
30
- //#region src/index.js
31
+ //#region src/mangle.js
31
32
  var import_runner = /* @__PURE__ */ __toESM((/* @__PURE__ */ __commonJSMin(((exports, module) => {
32
33
  /**
33
34
  * gustcss shared runner — helpers for the @gustcss/postcss and @gustcss/vite
@@ -87,6 +88,24 @@ var import_runner = /* @__PURE__ */ __toESM((/* @__PURE__ */ __commonJSMin(((exp
87
88
  return null;
88
89
  }
89
90
  /**
91
+ * Report whether a resolved gustcss.config.json turns on class-name mangling.
92
+ *
93
+ * Callers that cannot rewrite source (dev server, PostCSS) use this to decide
94
+ * whether they must pass `--mangle-class-names=false`. Only passing the flag
95
+ * when needed keeps older CLI binaries that predate the flag working.
96
+ *
97
+ * @param {{ configPath: string|null, fs?: { readFileSync: Function } }} options
98
+ * @returns {boolean}
99
+ */
100
+ function configEnablesMangling({ configPath, fs = __require("fs") }) {
101
+ if (!configPath) return false;
102
+ try {
103
+ return JSON.parse(fs.readFileSync(configPath, "utf-8"))?.mangleClassNames === true;
104
+ } catch {
105
+ return false;
106
+ }
107
+ }
108
+ /**
90
109
  * Write a temporary config file ({ content }) at <cwd>/<prefix>.<random8hex>.tmp.json,
91
110
  * invoke `fn` with the temp file path, and always clean the file up afterwards.
92
111
  *
@@ -118,25 +137,1023 @@ var import_runner = /* @__PURE__ */ __toESM((/* @__PURE__ */ __commonJSMin(((exp
118
137
  * @param {string} [options.output] output path (required for 'output' mode)
119
138
  * @param {boolean} [options.cssLayers] append --css-layers when truthy
120
139
  * @param {boolean} [options.watch] append --watch when truthy
140
+ * @param {boolean} [options.mangleClassNames] explicitly enable or disable mangling
141
+ * @param {string} [options.mangleMap] class-name manifest output path
142
+ * @param {string[]} [options.mangleExclude] class names to preserve
121
143
  * @param {string|null} [options.configPath] append --config <path> when present
122
144
  * @returns {string[]}
123
145
  */
124
- function buildArgs({ mode, output, cssLayers, configPath, watch }) {
146
+ function buildArgs({ mode, output, cssLayers, configPath, watch, mangleClassNames, mangleMap, mangleExclude }) {
125
147
  const args = ["build"];
126
148
  if (watch) args.push("--watch");
127
149
  if (mode === "stdout") args.push("--stdout");
128
150
  else args.push("-o", output);
129
151
  if (cssLayers) args.push("--css-layers");
152
+ if (mangleClassNames !== void 0) args.push(`--mangle-class-names=${mangleClassNames}`);
153
+ if (mangleMap) args.push("--mangle-map", mangleMap);
154
+ if (mangleExclude?.length) args.push("--mangle-exclude", mangleExclude.join(","));
130
155
  if (configPath) args.push("--config", configPath);
131
156
  return args;
132
157
  }
133
158
  module.exports = {
134
159
  resolveBinary,
135
160
  resolveConfig,
161
+ configEnablesMangling,
136
162
  withTempConfig,
137
163
  buildArgs
138
164
  };
139
165
  })))(), 1);
166
+ const SUPPORTED_SOURCE = /\.(?:[cm]?[jt]sx?|html)(?:$|\?)/;
167
+ const HTML_SOURCE = /\.html(?:$|\?)/;
168
+ const UNSUPPORTED_FRAMEWORK_SOURCE = /\.(?:vue|svelte)(?:$|\?)/;
169
+ const DEPENDENCY_SOURCE = /(?:^|[\\/])node_modules[\\/]/;
170
+ function hasOwn(classes, token) {
171
+ return Object.hasOwn(classes, token);
172
+ }
173
+ function collectClassListEdits(value, classes, baseOffset, edits) {
174
+ for (const match of value.matchAll(/\S+/g)) {
175
+ const replacement = classes[match[0]];
176
+ if (hasOwn(classes, match[0]) && replacement !== match[0]) edits.push({
177
+ start: baseOffset + match.index,
178
+ end: baseOffset + match.index + match[0].length,
179
+ replacement
180
+ });
181
+ }
182
+ }
183
+ function maskRange(chars, code, start, end) {
184
+ for (let index = start; index < end; index += 1) if (code[index] !== "\n" && code[index] !== "\r") chars[index] = " ";
185
+ }
186
+ function copyRange(chars, code, start, end) {
187
+ for (let index = start; index < end; index += 1) chars[index] = code[index];
188
+ }
189
+ function findHtmlTagEnd(code, start) {
190
+ let quote = null;
191
+ for (let index = start + 1; index < code.length; index += 1) {
192
+ const char = code[index];
193
+ if (quote !== null) {
194
+ if (char === quote) quote = null;
195
+ } else if (char === "\"" || char === "'") quote = char;
196
+ else if (char === ">") return index + 1;
197
+ }
198
+ return -1;
199
+ }
200
+ function findRawTextClosing(code, tagName, start) {
201
+ const lower = code.toLowerCase();
202
+ const needle = `</${tagName}`;
203
+ let index = lower.indexOf(needle, start);
204
+ while (index >= 0) {
205
+ const after = lower[index + needle.length];
206
+ if (after === void 0 || /[\s>]/.test(after)) return index;
207
+ index = lower.indexOf(needle, index + 1);
208
+ }
209
+ return -1;
210
+ }
211
+ function analyzeHtml(code, id) {
212
+ const markup = new Array(code.length).fill(" ");
213
+ const scriptRanges = [];
214
+ const commentRanges = [];
215
+ const exampleStack = [];
216
+ let index = 0;
217
+ while (index < code.length) {
218
+ const open = code.indexOf("<", index);
219
+ if (open < 0) break;
220
+ if (code.startsWith("<!--", open)) {
221
+ const commentEnd = code.indexOf("-->", open + 4);
222
+ const end = commentEnd < 0 ? code.length : commentEnd + 3;
223
+ commentRanges.push({
224
+ start: open,
225
+ end
226
+ });
227
+ index = end;
228
+ continue;
229
+ }
230
+ const tagEnd = findHtmlTagEnd(code, open);
231
+ if (tagEnd < 0) break;
232
+ const tag = code.slice(open, tagEnd);
233
+ const closingMatch = tag.match(/^<\s*\/\s*([A-Za-z][\w:-]*)/);
234
+ const openingMatch = closingMatch ? null : tag.match(/^<\s*([A-Za-z][\w:-]*)/);
235
+ const tagName = (closingMatch?.[1] ?? openingMatch?.[1] ?? "").toLowerCase();
236
+ if (!tagName) {
237
+ index = tagEnd;
238
+ continue;
239
+ }
240
+ const isClosing = closingMatch !== null;
241
+ const selfClosing = !isClosing && /\/\s*>$/.test(tag);
242
+ const isExampleTag = tagName === "code" || tagName === "pre";
243
+ if (exampleStack.length === 0 || isExampleTag) copyRange(markup, code, open, tagEnd);
244
+ if (isClosing && isExampleTag) {
245
+ if (exampleStack.at(-1) !== tagName) throw new Error(`[gustcss] mismatched </${tagName}> in ${id}`);
246
+ exampleStack.pop();
247
+ } else if (!isClosing && isExampleTag && !selfClosing) exampleStack.push(tagName);
248
+ if (!isClosing && !selfClosing && exampleStack.length === 0 && (tagName === "script" || tagName === "style")) {
249
+ const rawEnd = findRawTextClosing(code, tagName, tagEnd);
250
+ const contentEnd = rawEnd < 0 ? code.length : rawEnd;
251
+ if (tagName === "script") scriptRanges.push({
252
+ start: tagEnd,
253
+ end: contentEnd
254
+ });
255
+ index = contentEnd;
256
+ continue;
257
+ }
258
+ index = tagEnd;
259
+ }
260
+ if (exampleStack.length > 0) throw new Error(`[gustcss] unclosed <${exampleStack.at(-1)}> in ${id}`);
261
+ return {
262
+ markup: markup.join(""),
263
+ scriptRanges,
264
+ commentRanges
265
+ };
266
+ }
267
+ function canStartRegex(code, index, previous) {
268
+ if (previous === void 0 || /[({[,:;=!?&|+\-*%^~<>]/.test(previous)) return true;
269
+ return /\b(?:return|throw|case|delete|void|typeof|instanceof|in|of|yield|await)\s*$/.test(code.slice(Math.max(0, index - 24), index));
270
+ }
271
+ function isJsxAttributeAt(structure, index) {
272
+ const before = structure.slice(0, index);
273
+ const open = before.lastIndexOf("<");
274
+ if (open < 0 || open < before.lastIndexOf(">")) return false;
275
+ return /^<\s*[A-Za-z][\w.$:-]*(?:\s|$)/.test(before.slice(open));
276
+ }
277
+ function createJsMasks(code) {
278
+ const structure = code.split("");
279
+ const inspection = code.split("");
280
+ let index = 0;
281
+ let previousSignificant;
282
+ while (index < code.length) {
283
+ const char = code[index];
284
+ const next = code[index + 1];
285
+ if (char === "/" && next === "/") {
286
+ const end = code.indexOf("\n", index + 2);
287
+ const stop = end < 0 ? code.length : end;
288
+ maskRange(structure, code, index, stop);
289
+ maskRange(inspection, code, index, stop);
290
+ index = stop;
291
+ continue;
292
+ }
293
+ if (char === "/" && next === "*") {
294
+ const end = code.indexOf("*/", index + 2);
295
+ const stop = end < 0 ? code.length : end + 2;
296
+ maskRange(structure, code, index, stop);
297
+ maskRange(inspection, code, index, stop);
298
+ index = stop;
299
+ continue;
300
+ }
301
+ if (char === "\"" || char === "'" || char === "`") {
302
+ const quote = char;
303
+ const start = index;
304
+ index += 1;
305
+ let escaped = false;
306
+ while (index < code.length) {
307
+ const current = code[index];
308
+ if (escaped) escaped = false;
309
+ else if (current === "\\") escaped = true;
310
+ else if (current === quote) {
311
+ index += 1;
312
+ break;
313
+ }
314
+ index += 1;
315
+ }
316
+ maskRange(structure, code, start, index);
317
+ previousSignificant = quote;
318
+ continue;
319
+ }
320
+ if (char === "/" && canStartRegex(code, index, previousSignificant)) {
321
+ const start = index;
322
+ index += 1;
323
+ let escaped = false;
324
+ let characterClass = false;
325
+ while (index < code.length) {
326
+ const current = code[index];
327
+ if (escaped) escaped = false;
328
+ else if (current === "\\") escaped = true;
329
+ else if (current === "[") characterClass = true;
330
+ else if (current === "]") characterClass = false;
331
+ else if (current === "/" && !characterClass) {
332
+ index += 1;
333
+ while (/[A-Za-z]/.test(code[index] ?? "")) index += 1;
334
+ break;
335
+ } else if (current === "\n" || current === "\r") break;
336
+ index += 1;
337
+ }
338
+ maskRange(structure, code, start, index);
339
+ maskRange(inspection, code, start, index);
340
+ previousSignificant = "/";
341
+ continue;
342
+ }
343
+ if (!/\s/.test(char)) previousSignificant = char;
344
+ index += 1;
345
+ }
346
+ return {
347
+ structure: structure.join(""),
348
+ inspection: inspection.join("")
349
+ };
350
+ }
351
+ const classNameTrieCache = /* @__PURE__ */ new WeakMap();
352
+ function classNameTrie(classes) {
353
+ let root = classNameTrieCache.get(classes);
354
+ if (root) return root;
355
+ root = /* @__PURE__ */ new Map();
356
+ for (const className of Object.keys(classes)) {
357
+ let node = root;
358
+ for (const char of className) {
359
+ if (!node.has(char)) node.set(char, /* @__PURE__ */ new Map());
360
+ node = node.get(char);
361
+ }
362
+ node.className = className;
363
+ }
364
+ classNameTrieCache.set(classes, root);
365
+ return root;
366
+ }
367
+ function isBeforeBoundary(char) {
368
+ return char === void 0 || !/[A-Za-z0-9_@:/-]/.test(char);
369
+ }
370
+ function isAfterBoundary(char, before, beforeBefore) {
371
+ if (char === void 0 || char === ":") return true;
372
+ if (char === ".") return before === "." && (beforeBefore === void 0 || !/[A-Za-z0-9_/\\.]/.test(beforeBefore));
373
+ return !/[A-Za-z0-9_@/-]/.test(char);
374
+ }
375
+ function findMappedToken(value, classes) {
376
+ const trie = classNameTrie(classes);
377
+ let found = null;
378
+ for (let start = 0; start < value.length; start += 1) {
379
+ const before = start === 0 ? void 0 : value[start - 1];
380
+ if (!isBeforeBoundary(before)) continue;
381
+ const beforeBefore = start < 2 ? void 0 : value[start - 2];
382
+ let node = trie;
383
+ for (let end = start; end < value.length; end += 1) {
384
+ node = node.get(value[end]);
385
+ if (!node) break;
386
+ if (!node.className) continue;
387
+ const afterIndex = end + 1;
388
+ if (!isAfterBoundary(afterIndex === value.length ? void 0 : value[afterIndex], before, beforeBefore)) continue;
389
+ if (found === null || node.className.length > found.length || node.className.length === found.length && node.className.localeCompare(found) < 0) found = node.className;
390
+ }
391
+ }
392
+ return found;
393
+ }
394
+ function scanQuotedSegments(value, visitor) {
395
+ let index = 0;
396
+ while (index < value.length) {
397
+ const quote = value[index];
398
+ if (quote !== "\"" && quote !== "'" && quote !== "`") {
399
+ index += 1;
400
+ continue;
401
+ }
402
+ const start = index;
403
+ index += 1;
404
+ let escaped = false;
405
+ while (index < value.length) {
406
+ const char = value[index];
407
+ if (escaped) escaped = false;
408
+ else if (char === "\\") escaped = true;
409
+ else if (char === quote) {
410
+ index += 1;
411
+ visitor({
412
+ start,
413
+ end: index,
414
+ quote,
415
+ contents: value.slice(start + 1, index - 1)
416
+ });
417
+ break;
418
+ }
419
+ index += 1;
420
+ }
421
+ }
422
+ }
423
+ function findMappedInQuotedSegments(value, classes) {
424
+ let found = null;
425
+ scanQuotedSegments(value, ({ contents }) => {
426
+ if (found === null) found = findMappedToken(contents, classes);
427
+ });
428
+ return found;
429
+ }
430
+ function stripQuotedSegments(value) {
431
+ let output = "";
432
+ let cursor = 0;
433
+ scanQuotedSegments(value, ({ start, end }) => {
434
+ output += value.slice(cursor, start);
435
+ output += " ".repeat(end - start);
436
+ cursor = end;
437
+ });
438
+ return output + value.slice(cursor);
439
+ }
440
+ function collectTemplateBodyEdits(body, classes, baseOffset, edits) {
441
+ let staticStart = 0;
442
+ let index = 0;
443
+ while (index < body.length) {
444
+ if (body[index] !== "$" || body[index + 1] !== "{") {
445
+ index += 1;
446
+ continue;
447
+ }
448
+ collectClassListEdits(body.slice(staticStart, index), classes, baseOffset + staticStart, edits);
449
+ index += 2;
450
+ let depth = 1;
451
+ let quote = null;
452
+ let escaped = false;
453
+ while (index < body.length && depth > 0) {
454
+ const char = body[index];
455
+ if (quote !== null) {
456
+ if (escaped) escaped = false;
457
+ else if (char === "\\") escaped = true;
458
+ else if (char === quote) quote = null;
459
+ } else if (char === "\"" || char === "'" || char === "`") quote = char;
460
+ else if (char === "{") depth += 1;
461
+ else if (char === "}") depth -= 1;
462
+ index += 1;
463
+ }
464
+ staticStart = index;
465
+ }
466
+ collectClassListEdits(body.slice(staticStart), classes, baseOffset + staticStart, edits);
467
+ }
468
+ function findBalancedEnd(code, open, opening, closing) {
469
+ let index = open + 1;
470
+ let depth = 1;
471
+ let quote = null;
472
+ let escaped = false;
473
+ while (index < code.length && depth > 0) {
474
+ const char = code[index];
475
+ if (quote !== null) {
476
+ if (escaped) escaped = false;
477
+ else if (char === "\\") escaped = true;
478
+ else if (char === quote) quote = null;
479
+ } else if (char === "\"" || char === "'" || char === "`") quote = char;
480
+ else if (char === opening) depth += 1;
481
+ else if (char === closing) depth -= 1;
482
+ index += 1;
483
+ }
484
+ return depth === 0 ? index : -1;
485
+ }
486
+ function rejectAmbiguousClassExpressions(code, structure, classes, id) {
487
+ const pattern = /(?<![:\w-])class(?:Name)?\s*=\s*\{/g;
488
+ let match;
489
+ while ((match = pattern.exec(structure)) !== null) {
490
+ const open = code.indexOf("{", match.index);
491
+ const end = findBalancedEnd(code, open, "{", "}");
492
+ if (end < 0) throw new Error(`[gustcss] incomplete class/className expression in ${id}. Ensure the expression is properly closed.`);
493
+ const ambiguous = findMappedToken(code.slice(open + 1, end - 1), classes);
494
+ if (ambiguous) throw new Error(`[gustcss] mapped class "${ambiguous}" remains in an ambiguous class expression in ${id}. Use a static class attribute/template segment, or add it to mangleExclude.`);
495
+ pattern.lastIndex = end;
496
+ }
497
+ }
498
+ function collectClassListCallEdits(code, structure, classes, id, edits) {
499
+ const pattern = /\.classList\.(?:add|remove|toggle|contains|replace)\s*\(/g;
500
+ let match;
501
+ while ((match = pattern.exec(structure)) !== null) {
502
+ const open = code.indexOf("(", match.index);
503
+ const end = findBalancedEnd(code, open, "(", ")");
504
+ if (end < 0) break;
505
+ const args = code.slice(open + 1, end - 1);
506
+ const withoutStrings = stripQuotedSegments(args);
507
+ const dynamic = findMappedToken(withoutStrings, classes);
508
+ if (dynamic) throw new Error(`[gustcss] mapped class "${dynamic}" remains in a dynamic classList argument in ${id}. Pass it as a direct string argument, or add it to mangleExclude.`);
509
+ if (withoutStrings.includes("(")) {
510
+ const ambiguous = findMappedInQuotedSegments(args, classes);
511
+ if (ambiguous) throw new Error(`[gustcss] mapped class "${ambiguous}" is nested in a classList call in ${id}. Pass it as a direct string argument, or add it to mangleExclude.`);
512
+ }
513
+ scanQuotedSegments(args, ({ start, contents }) => {
514
+ collectClassListEdits(contents, classes, open + 1 + start + 1, edits);
515
+ });
516
+ pattern.lastIndex = end;
517
+ }
518
+ }
519
+ function rejectDynamicSetAttributeCalls(code, structure, classes, id) {
520
+ const pattern = /\.setAttribute\s*\(/g;
521
+ let match;
522
+ while ((match = pattern.exec(structure)) !== null) {
523
+ const open = code.indexOf("(", match.index);
524
+ const end = findBalancedEnd(code, open, "(", ")");
525
+ if (end < 0) break;
526
+ const args = code.slice(open + 1, end - 1);
527
+ if (!/^\s*(["'])class\1\s*,/.test(args)) {
528
+ pattern.lastIndex = end;
529
+ continue;
530
+ }
531
+ const withoutStrings = stripQuotedSegments(args);
532
+ const dynamic = findMappedToken(withoutStrings, classes);
533
+ const nested = withoutStrings.includes("(") ? findMappedInQuotedSegments(args, classes) : null;
534
+ const ambiguous = dynamic ?? nested;
535
+ if (ambiguous) throw new Error(`[gustcss] mapped class "${ambiguous}" remains in a dynamic setAttribute in ${id}. Pass a direct class string, or add it to mangleExclude.`);
536
+ pattern.lastIndex = end;
537
+ }
538
+ }
539
+ function rejectDynamicClassNameAssignments(code, structure, classes, id) {
540
+ const pattern = /\.className\s*=(?!=)\s*/g;
541
+ while (pattern.exec(structure) !== null) {
542
+ const start = pattern.lastIndex;
543
+ const candidates = [code.indexOf(";", start), code.indexOf("\n", start)].filter((index) => index >= 0);
544
+ const end = candidates.length > 0 ? Math.min(...candidates) : code.length;
545
+ const ambiguous = findMappedToken(code.slice(start, end), classes);
546
+ if (ambiguous) throw new Error(`[gustcss] mapped class "${ambiguous}" remains in a dynamic className assignment in ${id}. Assign a direct class string, or add it to mangleExclude.`);
547
+ pattern.lastIndex = end;
548
+ }
549
+ }
550
+ function applyEdits(code, edits) {
551
+ const sorted = [...edits].sort((a, b) => a.start - b.start || a.end - b.end);
552
+ let output = "";
553
+ let cursor = 0;
554
+ const origins = [];
555
+ for (const edit of sorted) {
556
+ if (edit.start < cursor) throw new Error("[gustcss] overlapping class-name rewrites");
557
+ output += code.slice(cursor, edit.start);
558
+ for (let index = cursor; index < edit.start; index += 1) origins.push(index);
559
+ const sourceLength = Math.max(1, edit.end - edit.start);
560
+ if (edit.replacement.length > sourceLength) throw new Error("[gustcss] class-name replacement must not exceed its source length");
561
+ output += edit.replacement;
562
+ for (let index = 0; index < edit.replacement.length; index += 1) origins.push(edit.start + Math.min(index, sourceLength - 1));
563
+ cursor = edit.end;
564
+ }
565
+ output += code.slice(cursor);
566
+ for (let index = cursor; index < code.length; index += 1) origins.push(index);
567
+ return {
568
+ code: output,
569
+ origins
570
+ };
571
+ }
572
+ function sourcesForFile(code, id) {
573
+ if (!HTML_SOURCE.test(id)) {
574
+ const js = createJsMasks(code);
575
+ return {
576
+ attributes: code,
577
+ structure: js.structure,
578
+ inspection: js.inspection
579
+ };
580
+ }
581
+ const html = analyzeHtml(code, id);
582
+ const structure = new Array(code.length).fill(" ");
583
+ const inspection = new Array(code.length).fill(" ");
584
+ for (const range of html.scriptRanges) {
585
+ const script = code.slice(range.start, range.end);
586
+ const jsScript = createJsMasks(script);
587
+ for (let offset = 0; offset < script.length; offset += 1) {
588
+ structure[range.start + offset] = jsScript.structure[offset];
589
+ inspection[range.start + offset] = jsScript.inspection[offset];
590
+ }
591
+ }
592
+ for (const range of html.commentRanges) for (let offset = range.start; offset < range.end; offset += 1) inspection[offset] = " ";
593
+ return {
594
+ attributes: html.markup,
595
+ structure: structure.join(""),
596
+ inspection: inspection.join("")
597
+ };
598
+ }
599
+ function collectEdits(code, classes, id) {
600
+ const edits = [];
601
+ const sources = sourcesForFile(code, id);
602
+ const commentRanges = [];
603
+ let commentIndex = 0;
604
+ while ((commentIndex = code.indexOf("<!--", commentIndex)) >= 0) {
605
+ const commentEnd = code.indexOf("-->", commentIndex + 4);
606
+ if (commentEnd < 0) {
607
+ commentRanges.push({
608
+ start: commentIndex,
609
+ end: code.length
610
+ });
611
+ break;
612
+ }
613
+ commentRanges.push({
614
+ start: commentIndex,
615
+ end: commentEnd + 3
616
+ });
617
+ commentIndex = commentEnd + 3;
618
+ }
619
+ function isInComment(pos) {
620
+ return commentRanges.some((range) => pos >= range.start && pos < range.end);
621
+ }
622
+ const attributePattern = /((?<![:\w-])class(?:Name)?\s*=\s*)(?:(["'])([\s\S]*?)(\2)|(\{\s*)(["'])([\s\S]*?)(\6)(\s*\}))/g;
623
+ let match;
624
+ while ((match = attributePattern.exec(sources.attributes)) !== null) {
625
+ if (isInComment(match.index)) continue;
626
+ if (!HTML_SOURCE.test(id) && !isJsxAttributeAt(sources.structure, match.index)) continue;
627
+ if (match[2] !== void 0) collectClassListEdits(match[3], classes, match.index + match[1].length + 1, edits);
628
+ else collectClassListEdits(match[7], classes, match.index + match[1].length + match[5].length + 1, edits);
629
+ }
630
+ const templatePattern = /((?<![:\w-])class(?:Name)?\s*=\s*\{\s*`)([\s\S]*?)(`\s*\})/g;
631
+ while ((match = templatePattern.exec(sources.attributes)) !== null) {
632
+ if (isInComment(match.index)) continue;
633
+ if (!HTML_SOURCE.test(id) && !isJsxAttributeAt(sources.structure, match.index)) continue;
634
+ collectTemplateBodyEdits(match[2], classes, match.index + match[1].length, edits);
635
+ }
636
+ collectClassListCallEdits(code, sources.structure, classes, id, edits);
637
+ const setAttributePattern = /(\.setAttribute\(\s*["']class["']\s*,\s*)(["'])([\s\S]*?)(\2)(\s*\))/g;
638
+ while ((match = setAttributePattern.exec(code)) !== null) {
639
+ if (sources.structure[match.index] === " ") continue;
640
+ collectClassListEdits(match[3], classes, match.index + match[1].length + 1, edits);
641
+ }
642
+ return edits;
643
+ }
644
+ function collectRecognizedContextEdits(code, classes, id) {
645
+ return applyEdits(code, collectEdits(code, classes, id));
646
+ }
647
+ /**
648
+ * Collect the rewrites for a source fragment (TypeScript frontmatter, an inline
649
+ * `<script>` body, …) and run the same fail-closed checks as `transformSource`,
650
+ * but return the edits instead of the rewritten code so the caller can place
651
+ * them inside a larger document.
652
+ */
653
+ function collectFragmentEdits(code, classes, id) {
654
+ const edits = collectEdits(code, classes, id);
655
+ const rewritten = applyEdits(code, edits).code;
656
+ const sources = sourcesForFile(rewritten, id);
657
+ rejectDynamicSetAttributeCalls(rewritten, sources.structure, classes, id);
658
+ rejectDynamicClassNameAssignments(rewritten, sources.structure, classes, id);
659
+ rejectAmbiguousClassExpressions(rewritten, sources.structure, classes, id);
660
+ const ambiguous = findMappedInQuotedSegments(sources.inspection, classes);
661
+ if (ambiguous) throw new Error(`[gustcss] mapped class "${ambiguous}" remains in an ambiguous string in ${id}. Move it to a static class/className or classList context, or add it to mangleExclude.`);
662
+ return edits;
663
+ }
664
+ const BASE64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
665
+ function encodeVLQ(value) {
666
+ let encoded = "";
667
+ let vlq = Math.abs(value) * 2 + (value < 0 ? 1 : 0);
668
+ do {
669
+ let digit = vlq % 32;
670
+ vlq = Math.floor(vlq / 32);
671
+ if (vlq > 0) digit += 32;
672
+ encoded += BASE64[digit];
673
+ } while (vlq > 0);
674
+ return encoded;
675
+ }
676
+ function createSourceMap(original, generated, origins, id) {
677
+ const originalPositions = new Array(original.length);
678
+ let originalLine = 0;
679
+ let originalColumn = 0;
680
+ for (let index = 0; index < original.length; index += 1) {
681
+ originalPositions[index] = {
682
+ line: originalLine,
683
+ column: originalColumn
684
+ };
685
+ if (original[index] === "\n") {
686
+ originalLine += 1;
687
+ originalColumn = 0;
688
+ } else originalColumn += 1;
689
+ }
690
+ const lines = [""];
691
+ let generatedLine = 0;
692
+ let generatedColumn = 0;
693
+ let previousGeneratedColumn = 0;
694
+ let previousSource = 0;
695
+ let previousOriginalLine = 0;
696
+ let previousOriginalColumn = 0;
697
+ for (let index = 0; index < generated.length; index += 1) {
698
+ if (generated[index] === "\n") {
699
+ generatedLine += 1;
700
+ generatedColumn = 0;
701
+ previousGeneratedColumn = 0;
702
+ lines.push("");
703
+ continue;
704
+ }
705
+ const originalPosition = originalPositions[origins[index]];
706
+ if (!originalPosition) {
707
+ generatedColumn += 1;
708
+ continue;
709
+ }
710
+ const segment = encodeVLQ(generatedColumn - previousGeneratedColumn) + encodeVLQ(0 - previousSource) + encodeVLQ(originalPosition.line - previousOriginalLine) + encodeVLQ(originalPosition.column - previousOriginalColumn);
711
+ lines[generatedLine] += `${lines[generatedLine] ? "," : ""}${segment}`;
712
+ previousGeneratedColumn = generatedColumn;
713
+ previousSource = 0;
714
+ previousOriginalLine = originalPosition.line;
715
+ previousOriginalColumn = originalPosition.column;
716
+ generatedColumn += 1;
717
+ }
718
+ return {
719
+ version: 3,
720
+ sources: [id],
721
+ sourcesContent: [original],
722
+ names: [],
723
+ mappings: lines.join(";")
724
+ };
725
+ }
726
+ function transformSource(code, classes, id) {
727
+ const transformed = collectRecognizedContextEdits(code, classes, id);
728
+ const rewritten = transformed.code;
729
+ const sources = sourcesForFile(rewritten, id);
730
+ rejectDynamicSetAttributeCalls(rewritten, sources.structure, classes, id);
731
+ rejectDynamicClassNameAssignments(rewritten, sources.structure, classes, id);
732
+ rejectAmbiguousClassExpressions(rewritten, sources.structure, classes, id);
733
+ return {
734
+ code: rewritten,
735
+ map: createSourceMap(code, rewritten, transformed.origins, id),
736
+ inspection: sources.inspection
737
+ };
738
+ }
739
+ function findAmbiguousMappedClass(code, classes) {
740
+ return findMappedInQuotedSegments(code, classes);
741
+ }
742
+ /**
743
+ * Create a fail-closed source transformer for a GustCSS class manifest.
744
+ * Only unambiguous class-name contexts are rewritten automatically.
745
+ */
746
+ function createClassNameTransformer(classes) {
747
+ const transformWithSourceMap = (code, id) => {
748
+ if (UNSUPPORTED_FRAMEWORK_SOURCE.test(id)) {
749
+ const referenced = findMappedToken(code, classes);
750
+ if (referenced) throw new Error(`[gustcss] class-name mangling does not support Vue or Svelte templates yet (${id}). Add "${referenced}" to mangleExclude or disable mangleClassNames.`);
751
+ return {
752
+ code,
753
+ map: null
754
+ };
755
+ }
756
+ if (DEPENDENCY_SOURCE.test(id) || !SUPPORTED_SOURCE.test(id)) return {
757
+ code,
758
+ map: null
759
+ };
760
+ const result = transformSource(code, classes, id);
761
+ const ambiguous = findAmbiguousMappedClass(result.inspection, classes, id);
762
+ if (ambiguous) throw new Error(`[gustcss] mapped class "${ambiguous}" remains in an ambiguous string in ${id}. Move it to a static class/className or classList context, or add it to mangleExclude.`);
763
+ return {
764
+ code: result.code,
765
+ map: result.map
766
+ };
767
+ };
768
+ const transform = (code, id) => transformWithSourceMap(code, id).code;
769
+ transform.withSourceMap = transformWithSourceMap;
770
+ transform.classes = classes;
771
+ return transform;
772
+ }
773
+ //#endregion
774
+ //#region src/astro.js
775
+ /**
776
+ * Class-name mangling for `.astro` sources, driven by the AST that
777
+ * `@astrojs/compiler`'s `parse()` returns.
778
+ *
779
+ * Only unambiguous class contexts are rewritten; any other place where a
780
+ * mapped class name shows up fails the build (fail-closed), because a class
781
+ * that reaches the DOM unrenamed would no longer match the mangled CSS.
782
+ */
783
+ const CLASS_VALUED_BEFORE = /* @__PURE__ */ new Set([
784
+ "[",
785
+ ",",
786
+ "&&",
787
+ "||"
788
+ ]);
789
+ const CLASS_VALUED_AFTER = /* @__PURE__ */ new Set([
790
+ ",",
791
+ "]",
792
+ "&&",
793
+ "||"
794
+ ]);
795
+ const OPERATORS = [
796
+ "===",
797
+ "!==",
798
+ "&&",
799
+ "||",
800
+ "??",
801
+ "=>",
802
+ "==",
803
+ "!=",
804
+ "?.",
805
+ "<=",
806
+ ">="
807
+ ];
808
+ const PUNCTUATION = "[]{}(),:?.!+-*/%<>=&|~^;";
809
+ /** Map UTF-8 byte offsets (what the compiler reports) to string indexes. */
810
+ function byteToIndexMap(code) {
811
+ const map = [];
812
+ let byte = 0;
813
+ for (let index = 0; index < code.length; index += 1) {
814
+ const point = code.codePointAt(index);
815
+ const width = point < 128 ? 1 : point < 2048 ? 2 : point < 65536 ? 3 : 4;
816
+ for (let i = 0; i < width; i += 1) map[byte + i] = index;
817
+ byte += width;
818
+ if (point > 65535) index += 1;
819
+ }
820
+ map[byte] = code.length;
821
+ return map;
822
+ }
823
+ /**
824
+ * Tokenize a JavaScript expression just far enough to know, for every string
825
+ * literal and identifier, what surrounds it. Template literals are reported
826
+ * as strings with quote "`" and are never rewritten. Returns null when the
827
+ * expression cannot be tokenized (unterminated string, unknown character).
828
+ */
829
+ function tokenizeExpression(source) {
830
+ const tokens = [];
831
+ let index = 0;
832
+ while (index < source.length) {
833
+ const char = source[index];
834
+ if (/\s/.test(char)) {
835
+ index += 1;
836
+ continue;
837
+ }
838
+ if (source.startsWith("//", index)) {
839
+ const newline = source.indexOf("\n", index);
840
+ index = newline < 0 ? source.length : newline + 1;
841
+ continue;
842
+ }
843
+ if (source.startsWith("/*", index)) {
844
+ const close = source.indexOf("*/", index + 2);
845
+ if (close < 0) return null;
846
+ index = close + 2;
847
+ continue;
848
+ }
849
+ if (char === "\"" || char === "'" || char === "`") {
850
+ const start = index;
851
+ index += 1;
852
+ while (index < source.length && source[index] !== char) {
853
+ if (source[index] === "\\") index += 1;
854
+ index += 1;
855
+ }
856
+ if (index >= source.length) return null;
857
+ tokens.push({
858
+ type: "string",
859
+ quote: char,
860
+ start,
861
+ end: index + 1,
862
+ value: source.slice(start + 1, index)
863
+ });
864
+ index += 1;
865
+ continue;
866
+ }
867
+ if (/[A-Za-z_$]/.test(char)) {
868
+ const start = index;
869
+ while (index < source.length && /[\w$]/.test(source[index])) index += 1;
870
+ tokens.push({
871
+ type: "identifier",
872
+ start,
873
+ end: index,
874
+ value: source.slice(start, index)
875
+ });
876
+ continue;
877
+ }
878
+ if (/[0-9]/.test(char)) {
879
+ const start = index;
880
+ while (index < source.length && /[\w.]/.test(source[index])) index += 1;
881
+ tokens.push({
882
+ type: "number",
883
+ start,
884
+ end: index,
885
+ value: source.slice(start, index)
886
+ });
887
+ continue;
888
+ }
889
+ const operator = OPERATORS.find((candidate) => source.startsWith(candidate, index));
890
+ if (operator) {
891
+ tokens.push({
892
+ type: "operator",
893
+ start: index,
894
+ end: index + operator.length,
895
+ value: operator
896
+ });
897
+ index += operator.length;
898
+ continue;
899
+ }
900
+ if (PUNCTUATION.includes(char)) {
901
+ tokens.push({
902
+ type: "operator",
903
+ start: index,
904
+ end: index + 1,
905
+ value: char
906
+ });
907
+ index += 1;
908
+ continue;
909
+ }
910
+ return null;
911
+ }
912
+ return tokens;
913
+ }
914
+ /**
915
+ * Rewrite the class-valued string literals of a `class:list` expression.
916
+ * Accepted shapes are array literals, object literals and their nesting.
917
+ * Inside them only array elements (also as the right operand of `&&` / `||`)
918
+ * and quoted object keys are class-valued; every other occurrence of a mapped
919
+ * class name fails closed.
920
+ */
921
+ function collectClassListExpressionEdits(source, classes, baseOffset, edits, id) {
922
+ const fail = (token, reason) => {
923
+ throw new Error(`[gustcss] mapped class "${token}" ${reason} in class:list of ${id}. Use an array/object literal with quoted entries, or add it to mangleExclude.`);
924
+ };
925
+ const tokens = tokenizeExpression(source);
926
+ const first = tokens && tokens[0];
927
+ const last = tokens && tokens[tokens.length - 1];
928
+ if (!(tokens && tokens.length >= 2 && (first.value === "[" && last.value === "]" || first.value === "{" && last.value === "}"))) {
929
+ const mapped = findMappedToken(source, classes);
930
+ if (mapped) fail(mapped, "remains in an expression that is not an array or object literal");
931
+ return;
932
+ }
933
+ const stack = [];
934
+ for (let i = 0; i < tokens.length; i += 1) {
935
+ const token = tokens[i];
936
+ const previous = tokens[i - 1];
937
+ const next = tokens[i + 1];
938
+ const context = stack[stack.length - 1];
939
+ if (token.type === "operator") {
940
+ if (token.value === "[") {
941
+ const subscript = previous && (previous.type === "identifier" || previous.type === "string" || previous.value === ")" || previous.value === "]");
942
+ stack.push(subscript ? "subscript" : "array");
943
+ } else if (token.value === "{") stack.push("object");
944
+ else if (token.value === "(") stack.push("call");
945
+ else if (token.value === "]" || token.value === "}" || token.value === ")") {
946
+ if (stack.length === 0) fail(findMappedToken(source, classes) || "?", "appears in an unbalanced");
947
+ stack.pop();
948
+ }
949
+ continue;
950
+ }
951
+ if (token.type === "identifier") {
952
+ if (!hasOwn(classes, token.value)) continue;
953
+ if (context === "object" && previous && (previous.value === "{" || previous.value === ",") && next && (next.value === ":" || next.value === "," || next.value === "}")) fail(token.value, `is an unquoted object key (write it as "${token.value}")`);
954
+ fail(token.value, "is referenced as an identifier");
955
+ }
956
+ if (token.type !== "string") continue;
957
+ const mapped = findMappedToken(token.value, classes);
958
+ if (token.quote === "`") {
959
+ if (mapped) fail(mapped, "remains in a template literal");
960
+ continue;
961
+ }
962
+ const arrayElement = context === "array" && previous && CLASS_VALUED_BEFORE.has(previous.value) && next && CLASS_VALUED_AFTER.has(next.value);
963
+ const objectKey = context === "object" && previous && (previous.value === "{" || previous.value === ",") && next && next.value === ":";
964
+ if (arrayElement || objectKey) collectClassListEdits(token.value, classes, baseOffset + token.start + 1, edits);
965
+ else if (mapped) fail(mapped, "remains in a position that is not an array element or object key");
966
+ }
967
+ if (stack.length !== 0) fail(findMappedToken(source, classes) || "?", "appears in an unbalanced");
968
+ }
969
+ /**
970
+ * Find a mapped class referenced by a stylesheet selector, including at-rule
971
+ * preludes (`@scope (.flex)`) and attribute selectors (`[class~="flex"]`).
972
+ * Declarations and comments are ignored.
973
+ */
974
+ function findMappedClassInStylesheet(css, classes) {
975
+ const source = css.replace(/\/\*[\s\S]*?\*\//g, " ");
976
+ let prelude = "";
977
+ let quote = null;
978
+ for (let i = 0; i < source.length; i += 1) {
979
+ const char = source[i];
980
+ if (quote) {
981
+ prelude += char;
982
+ if (char === "\\") {
983
+ prelude += source[i + 1] || "";
984
+ i += 1;
985
+ } else if (char === quote) quote = null;
986
+ continue;
987
+ }
988
+ if (char === "\"" || char === "'") {
989
+ quote = char;
990
+ prelude += char;
991
+ continue;
992
+ }
993
+ if (char === "{") {
994
+ const found = findMappedClassInSelector(prelude.trim(), classes);
995
+ if (found) return found;
996
+ prelude = "";
997
+ } else if (char === "}" || char === ";") prelude = "";
998
+ else prelude += char;
999
+ }
1000
+ return null;
1001
+ }
1002
+ function findMappedClassInSelector(selector, classes) {
1003
+ const classPattern = /\.((?:\\.|[A-Za-z0-9_-])+)/g;
1004
+ let match;
1005
+ while ((match = classPattern.exec(selector)) !== null) {
1006
+ const name = match[1].replace(/\\(.)/g, "$1");
1007
+ if (hasOwn(classes, name)) return name;
1008
+ }
1009
+ const attributePattern = /\[\s*class\s*[~|^$*]?=\s*(["']?)([^\]"']+)\1\s*[is]?\s*\]/g;
1010
+ while ((match = attributePattern.exec(selector)) !== null) {
1011
+ const mapped = findMappedToken(match[2], classes);
1012
+ if (mapped) return mapped;
1013
+ }
1014
+ return null;
1015
+ }
1016
+ /**
1017
+ * Locate the value of an attribute from its start offset (the attribute
1018
+ * name). Returns the index range of the value and its delimiter.
1019
+ */
1020
+ function locateAttributeValue(code, attribute, start) {
1021
+ let index = start + attribute.name.length;
1022
+ while (index < code.length && /\s/.test(code[index])) index += 1;
1023
+ if (code[index] !== "=") return null;
1024
+ index += 1;
1025
+ while (index < code.length && /\s/.test(code[index])) index += 1;
1026
+ const delimiter = code[index];
1027
+ if (delimiter === "\"" || delimiter === "'" || delimiter === "`") {
1028
+ const end = code.indexOf(delimiter, index + 1);
1029
+ return end < 0 ? null : {
1030
+ start: index + 1,
1031
+ end,
1032
+ delimiter
1033
+ };
1034
+ }
1035
+ if (delimiter === "{") {
1036
+ const end = findBalancedEnd(code, index, "{", "}");
1037
+ return end < 0 ? null : {
1038
+ start: index + 1,
1039
+ end: end - 1,
1040
+ delimiter
1041
+ };
1042
+ }
1043
+ return null;
1044
+ }
1045
+ const STRING_LITERAL = /^\s*(["'])((?:\\.|(?!\1)[^\\])*)\1\s*$/;
1046
+ /**
1047
+ * Create the `.astro` transformer. `parse` is `@astrojs/compiler`'s parse
1048
+ * function, injected so the plugin and the tests can supply their own copy.
1049
+ */
1050
+ function createAstroTransformer({ parse, classes }) {
1051
+ return async function transformAstro(code, id) {
1052
+ const { ast } = await parse(code, { position: true });
1053
+ const toIndex = byteToIndexMap(code);
1054
+ const edits = [];
1055
+ const offsetOf = (node) => toIndex[node.position.start.offset];
1056
+ const stop = (mapped, where) => {
1057
+ throw new Error(`[gustcss] mapped class "${mapped}" remains in ${where} in ${id}. Move it to a static class attribute or class:list literal, or add it to mangleExclude.`);
1058
+ };
1059
+ const fragmentEdits = (text, start, kind) => {
1060
+ for (const edit of collectFragmentEdits(text, classes, `${id}#${kind}.ts`)) edits.push({
1061
+ start: start + edit.start,
1062
+ end: start + edit.end,
1063
+ replacement: edit.replacement
1064
+ });
1065
+ };
1066
+ const visitAttribute = (attribute, node) => {
1067
+ const start = offsetOf(attribute);
1068
+ const isComponent = node.type === "component";
1069
+ const value = attribute.value || "";
1070
+ if (attribute.name === "class") {
1071
+ const location = locateAttributeValue(code, attribute, start);
1072
+ if (location && attribute.kind === "quoted") {
1073
+ collectClassListEdits(code.slice(location.start, location.end), classes, location.start, edits);
1074
+ return;
1075
+ }
1076
+ if (location && attribute.kind === "expression") {
1077
+ const expression = code.slice(location.start, location.end);
1078
+ const literal = STRING_LITERAL.exec(expression);
1079
+ if (literal) {
1080
+ const inner = expression.indexOf(literal[1]) + 1;
1081
+ collectClassListEdits(literal[2], classes, location.start + inner, edits);
1082
+ return;
1083
+ }
1084
+ }
1085
+ const mapped = findMappedToken(value, classes);
1086
+ if (mapped) stop(mapped, `a dynamic class attribute (${attribute.kind})`);
1087
+ return;
1088
+ }
1089
+ if (attribute.name === "class:list") {
1090
+ const location = locateAttributeValue(code, attribute, start);
1091
+ if (!location || attribute.kind !== "expression") {
1092
+ const mapped = findMappedToken(value, classes);
1093
+ if (mapped) stop(mapped, `a class:list attribute of kind ${attribute.kind}`);
1094
+ return;
1095
+ }
1096
+ collectClassListExpressionEdits(code.slice(location.start, location.end), classes, location.start, edits, id);
1097
+ return;
1098
+ }
1099
+ if (attribute.kind === "spread") {
1100
+ const mapped = findMappedToken(`${attribute.name} ${value}`, classes);
1101
+ if (mapped) stop(mapped, `a spread attribute on <${node.name}>`);
1102
+ return;
1103
+ }
1104
+ if (attribute.name === "set:html" || attribute.name === "set:text" || isComponent) {
1105
+ const mapped = findMappedToken(value, classes);
1106
+ if (mapped) stop(mapped, isComponent ? `the "${attribute.name}" prop of <${node.name}>` : `a ${attribute.name} value`);
1107
+ }
1108
+ };
1109
+ const visit = (node) => {
1110
+ switch (node.type) {
1111
+ case "frontmatter": {
1112
+ const start = code.indexOf(node.value, offsetOf(node));
1113
+ if (start >= 0) fragmentEdits(node.value, start, "frontmatter");
1114
+ return;
1115
+ }
1116
+ case "comment":
1117
+ case "text":
1118
+ case "doctype": return;
1119
+ case "expression":
1120
+ for (const child of node.children) if (child.type === "text") {
1121
+ const mapped = findMappedToken(child.value, classes);
1122
+ if (mapped && /["'`]/.test(child.value)) stop(mapped, "a template expression");
1123
+ } else visit(child);
1124
+ return;
1125
+ case "element":
1126
+ case "component":
1127
+ case "custom-element":
1128
+ case "fragment":
1129
+ for (const attribute of node.attributes) visitAttribute(attribute, node);
1130
+ if (node.type === "element" && node.name === "style") {
1131
+ for (const child of node.children) {
1132
+ if (child.type !== "text") continue;
1133
+ const mapped = findMappedClassInStylesheet(child.value, classes);
1134
+ if (mapped) stop(mapped, "a <style> selector");
1135
+ }
1136
+ return;
1137
+ }
1138
+ if (node.type === "element" && node.name === "script") {
1139
+ for (const child of node.children) if (child.type === "text") fragmentEdits(child.value, offsetOf(child), "script");
1140
+ return;
1141
+ }
1142
+ for (const child of node.children) visit(child);
1143
+ return;
1144
+ default: for (const child of node.children || []) visit(child);
1145
+ }
1146
+ };
1147
+ visit(ast);
1148
+ const applied = applyEdits(code, edits);
1149
+ return {
1150
+ code: applied.code,
1151
+ map: createSourceMap(code, applied.code, applied.origins, id)
1152
+ };
1153
+ };
1154
+ }
1155
+ //#endregion
1156
+ //#region src/index.js
140
1157
  /**
141
1158
  * @gustcss/vite - Vite plugin for CSS Utility Generator
142
1159
  *
@@ -150,12 +1167,38 @@ var import_runner = /* @__PURE__ */ __toESM((/* @__PURE__ */ __commonJSMin(((exp
150
1167
  * are provided by the developer in their build configuration. This plugin is
151
1168
  * designed for build-time use only and should not process untrusted input.
152
1169
  */
1170
+ const ASTRO_SOURCE = /\.astro(?:$|\?)/;
1171
+ const ASTRO_MODULE = /^[^\0?]*\.astro$/;
1172
+ /**
1173
+ * Resolve @astrojs/compiler parse function from the project.
1174
+ */
1175
+ async function resolveAstroCompiler(root) {
1176
+ const projectRequire = createRequire(path.join(root, "package.json"));
1177
+ const attempts = [
1178
+ () => projectRequire.resolve("@astrojs/compiler"),
1179
+ () => createRequire(projectRequire.resolve("astro/package.json")).resolve("@astrojs/compiler"),
1180
+ () => createRequire(import.meta.url).resolve("@astrojs/compiler")
1181
+ ];
1182
+ for (const attempt of attempts) try {
1183
+ const mod = await import(pathToFileURL(attempt()).href);
1184
+ if (typeof mod.parse === "function") return mod.parse;
1185
+ } catch {}
1186
+ return null;
1187
+ }
153
1188
  function cssUtility(opts = {}) {
154
1189
  const output = opts.output || "src/styles/utility.css";
155
1190
  const content = opts.content || ["./src/**/*.{js,ts,jsx,tsx,astro,vue}"];
156
1191
  const configPath = opts.config;
157
1192
  const outputToCssLayers = opts.outputToCssLayers;
1193
+ const mangleClassNames = opts.mangleClassNames === true;
1194
+ const mangleMap = opts.mangleMap || `${output}.classes.json`;
1195
+ const mangleExclude = opts.mangleExclude || [];
1196
+ let classNameTransformer = null;
1197
+ let rollbackContext = null;
1198
+ let manifestSnapshot = null;
158
1199
  let watchProcess = null;
1200
+ const loadedAstroModules = /* @__PURE__ */ new Set();
1201
+ let astroTransformer = null;
159
1202
  function findBinary(cwd) {
160
1203
  return import_runner.default.resolveBinary({
161
1204
  cwd,
@@ -169,14 +1212,21 @@ function cssUtility(opts = {}) {
169
1212
  fs
170
1213
  });
171
1214
  }
172
- function buildCSS(cwd, binaryPath) {
1215
+ function buildCSS(cwd, binaryPath, enableMangle) {
173
1216
  const resolvedConfigPath = findConfigFile(cwd);
174
1217
  const run = (cfgPath) => {
1218
+ const disableConfigMangle = !enableMangle && import_runner.default.configEnablesMangling({
1219
+ configPath: cfgPath,
1220
+ fs
1221
+ });
175
1222
  const args = import_runner.default.buildArgs({
176
1223
  mode: "output",
177
1224
  output,
178
1225
  cssLayers: outputToCssLayers,
179
- configPath: cfgPath
1226
+ configPath: cfgPath,
1227
+ mangleClassNames: enableMangle ? true : disableConfigMangle ? false : void 0,
1228
+ mangleMap: enableMangle ? mangleMap : void 0,
1229
+ mangleExclude: enableMangle ? mangleExclude : void 0
180
1230
  });
181
1231
  try {
182
1232
  const result = spawnSync(binaryPath, args, {
@@ -190,6 +1240,24 @@ function cssUtility(opts = {}) {
190
1240
  });
191
1241
  if (result.status !== 0) throw new Error(`gustcss build failed: ${result.stderr}`);
192
1242
  if (result.stderr) process.stderr.write(result.stderr);
1243
+ if (enableMangle) {
1244
+ const manifestPath = path.resolve(cwd, mangleMap);
1245
+ const manifestText = fs.readFileSync(manifestPath, "utf-8");
1246
+ const manifest = JSON.parse(manifestText);
1247
+ const classes = manifest?.classes;
1248
+ const entries = classes && !Array.isArray(classes) ? Object.entries(classes) : [];
1249
+ const shortNames = entries.map(([, short]) => short);
1250
+ const validEntries = entries.every(([original, short]) => original.length > 0 && typeof short === "string" && /^[A-Za-z]+$/.test(short));
1251
+ if (manifest?.version !== 1 || !classes || Array.isArray(classes) || !validEntries || new Set(shortNames).size !== shortNames.length) throw new Error(`invalid class-name manifest: ${manifestPath}`);
1252
+ classNameTransformer = createClassNameTransformer(manifest.classes);
1253
+ manifestSnapshot = {
1254
+ path: manifestPath,
1255
+ text: manifestText
1256
+ };
1257
+ } else {
1258
+ classNameTransformer = null;
1259
+ manifestSnapshot = null;
1260
+ }
193
1261
  } catch (error) {
194
1262
  throw new Error(`gustcss build failed: ${error.message}`);
195
1263
  }
@@ -202,25 +1270,66 @@ function cssUtility(opts = {}) {
202
1270
  fs
203
1271
  }, (tempConfigPath) => run(tempConfigPath));
204
1272
  }
1273
+ let viteConfig = null;
205
1274
  return {
206
1275
  name: "gustcss",
1276
+ ...mangleClassNames ? { enforce: "pre" } : {},
207
1277
  configResolved(config) {
1278
+ viteConfig = config;
208
1279
  const cwd = config.root || process.cwd();
209
1280
  const binaryPath = findBinary(cwd);
210
1281
  try {
211
- buildCSS(cwd, binaryPath);
1282
+ const enableMangle = mangleClassNames && config.command === "build";
1283
+ buildCSS(cwd, binaryPath, enableMangle);
1284
+ loadedAstroModules.clear();
1285
+ astroTransformer = null;
1286
+ rollbackContext = enableMangle ? {
1287
+ cwd,
1288
+ binaryPath
1289
+ } : null;
212
1290
  } catch (error) {
213
1291
  console.error(`[gustcss] Failed to build CSS: ${error.message}`);
214
1292
  throw error;
215
1293
  }
216
1294
  },
1295
+ async load(id) {
1296
+ if (!classNameTransformer || !ASTRO_MODULE.test(id)) return null;
1297
+ const filePath = id.startsWith("/@fs/") ? id.slice(4) : id;
1298
+ if (!fs.existsSync(filePath)) throw new Error(`[gustcss] cannot read ${id} to rewrite its class names for mangling. Disable mangleClassNames or exclude its classes with mangleExclude.`);
1299
+ const code = fs.readFileSync(filePath, "utf-8");
1300
+ loadedAstroModules.add(id);
1301
+ if (!astroTransformer) {
1302
+ const parse = await resolveAstroCompiler(viteConfig?.root || process.cwd());
1303
+ if (!parse) throw new Error(`[gustcss] @astrojs/compiler could not be resolved from the project, so ${id} cannot be mangled. Install astro, or disable mangleClassNames.`);
1304
+ astroTransformer = createAstroTransformer({
1305
+ parse,
1306
+ classes: classNameTransformer.classes
1307
+ });
1308
+ }
1309
+ const result = await astroTransformer(code, filePath);
1310
+ return result.code === code ? null : result;
1311
+ },
1312
+ transform(code, id) {
1313
+ if (!classNameTransformer) return null;
1314
+ if (ASTRO_MODULE.test(id)) {
1315
+ if (!loadedAstroModules.has(id)) throw new Error(`[gustcss] ${id} was compiled without passing through the gustcss load hook, so its class names cannot be mangled safely. Disable mangleClassNames or move the plugin so it loads .astro sources first.`);
1316
+ return null;
1317
+ }
1318
+ if (ASTRO_SOURCE.test(id)) return null;
1319
+ const transformed = classNameTransformer.withSourceMap(code, id);
1320
+ return transformed.code === code ? null : transformed;
1321
+ },
1322
+ transformIndexHtml(html, context) {
1323
+ if (!classNameTransformer) return html;
1324
+ return classNameTransformer(html, context?.filename || "index.html");
1325
+ },
217
1326
  configureServer(server) {
218
1327
  const cwd = server.config.root || process.cwd();
219
1328
  const binaryPath = findBinary(cwd);
220
1329
  const resolvedConfigPath = findConfigFile(cwd);
221
1330
  const outputPath = path.resolve(cwd, output);
222
1331
  try {
223
- buildCSS(cwd, binaryPath);
1332
+ buildCSS(cwd, binaryPath, false);
224
1333
  } catch (error) {
225
1334
  console.error(`[gustcss] Failed to build CSS: ${error.message}`);
226
1335
  }
@@ -232,13 +1341,18 @@ function cssUtility(opts = {}) {
232
1341
  fs.writeFileSync(tempConfigPath, JSON.stringify({ content }), { flag: "wx" });
233
1342
  watchConfigPath = tempConfigPath;
234
1343
  }
235
- watchProcess = spawn(binaryPath, import_runner.default.buildArgs({
1344
+ const watchArgs = import_runner.default.buildArgs({
236
1345
  mode: "output",
237
1346
  output,
238
1347
  cssLayers: outputToCssLayers,
239
1348
  configPath: watchConfigPath,
240
- watch: true
241
- }), {
1349
+ watch: true,
1350
+ mangleClassNames: import_runner.default.configEnablesMangling({
1351
+ configPath: watchConfigPath,
1352
+ fs
1353
+ }) ? false : void 0
1354
+ });
1355
+ watchProcess = spawn(binaryPath, watchArgs, {
242
1356
  cwd,
243
1357
  stdio: [
244
1358
  "pipe",
@@ -268,15 +1382,39 @@ function cssUtility(opts = {}) {
268
1382
  }
269
1383
  if (tempConfigPath && fs.existsSync(tempConfigPath)) fs.unlinkSync(tempConfigPath);
270
1384
  };
1385
+ const close = server.close.bind(server);
1386
+ server.close = async () => {
1387
+ cleanup();
1388
+ return close();
1389
+ };
271
1390
  server.httpServer?.on("close", cleanup);
272
1391
  process.once("SIGINT", cleanup);
273
1392
  process.once("SIGTERM", cleanup);
1393
+ process.once("exit", cleanup);
1394
+ },
1395
+ writeBundle() {
1396
+ if (!manifestSnapshot || fs.existsSync(manifestSnapshot.path)) return;
1397
+ fs.mkdirSync(path.dirname(manifestSnapshot.path), { recursive: true });
1398
+ fs.writeFileSync(manifestSnapshot.path, manifestSnapshot.text);
274
1399
  },
275
- buildEnd() {
1400
+ buildEnd(error) {
276
1401
  if (watchProcess) {
277
1402
  watchProcess.kill();
278
1403
  watchProcess = null;
279
1404
  }
1405
+ if (error && rollbackContext) {
1406
+ const { cwd, binaryPath } = rollbackContext;
1407
+ rollbackContext = null;
1408
+ classNameTransformer = null;
1409
+ manifestSnapshot = null;
1410
+ try {
1411
+ buildCSS(cwd, binaryPath, false);
1412
+ const manifestPath = path.resolve(cwd, mangleMap);
1413
+ if (fs.existsSync(manifestPath)) fs.unlinkSync(manifestPath);
1414
+ } catch (rollbackError) {
1415
+ console.error(`[gustcss] Failed to restore readable CSS: ${rollbackError.message}`);
1416
+ }
1417
+ } else rollbackContext = null;
280
1418
  }
281
1419
  };
282
1420
  }