tailwind-styled-v4 5.0.11 → 5.0.12

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 (107) hide show
  1. package/dist/{analyzeWorkspace-DDOQdzzI.d.ts → analyzeWorkspace-CopJNGmi.d.ts} +2 -0
  2. package/dist/{analyzeWorkspace-BS5O4rhC.d.mts → analyzeWorkspace-DpVPccjz.d.mts} +2 -0
  3. package/dist/analyzer.d.mts +4 -4
  4. package/dist/analyzer.d.ts +4 -4
  5. package/dist/analyzer.js +34 -69
  6. package/dist/analyzer.js.map +1 -1
  7. package/dist/analyzer.mjs +33 -68
  8. package/dist/analyzer.mjs.map +1 -1
  9. package/dist/animate.js +11 -11
  10. package/dist/animate.js.map +1 -1
  11. package/dist/animate.mjs +11 -11
  12. package/dist/animate.mjs.map +1 -1
  13. package/dist/atomic.js +16 -7
  14. package/dist/atomic.js.map +1 -1
  15. package/dist/atomic.mjs +16 -7
  16. package/dist/atomic.mjs.map +1 -1
  17. package/dist/cli.js +262 -190
  18. package/dist/cli.js.map +1 -1
  19. package/dist/cli.mjs +259 -187
  20. package/dist/cli.mjs.map +1 -1
  21. package/dist/compiler.d.mts +2543 -109
  22. package/dist/compiler.d.ts +2543 -109
  23. package/dist/compiler.js +1962 -435
  24. package/dist/compiler.js.map +1 -1
  25. package/dist/compiler.mjs +1816 -382
  26. package/dist/compiler.mjs.map +1 -1
  27. package/dist/devtools.js +17 -4
  28. package/dist/devtools.js.map +1 -1
  29. package/dist/devtools.mjs +17 -4
  30. package/dist/devtools.mjs.map +1 -1
  31. package/dist/engine.d.mts +11 -470
  32. package/dist/engine.d.ts +11 -470
  33. package/dist/engine.js +1442 -417
  34. package/dist/engine.js.map +1 -1
  35. package/dist/engine.mjs +1442 -417
  36. package/dist/engine.mjs.map +1 -1
  37. package/dist/index-BDQw13kn.d.ts +464 -0
  38. package/dist/index-DJv28Uzq.d.mts +464 -0
  39. package/dist/index.browser.mjs +143 -255
  40. package/dist/index.browser.mjs.map +1 -1
  41. package/dist/index.d.mts +23 -39
  42. package/dist/index.d.ts +23 -39
  43. package/dist/index.js +6000 -1463
  44. package/dist/index.js.map +1 -1
  45. package/dist/index.mjs +5995 -1458
  46. package/dist/index.mjs.map +1 -1
  47. package/dist/next.d.mts +44 -1
  48. package/dist/next.d.ts +44 -1
  49. package/dist/next.js +3197 -1128
  50. package/dist/next.js.map +1 -1
  51. package/dist/next.mjs +3196 -1129
  52. package/dist/next.mjs.map +1 -1
  53. package/dist/rspack.d.mts +9 -0
  54. package/dist/rspack.d.ts +9 -0
  55. package/dist/rspack.js +99 -61
  56. package/dist/rspack.js.map +1 -1
  57. package/dist/rspack.mjs +99 -61
  58. package/dist/rspack.mjs.map +1 -1
  59. package/dist/runtime-css.d.mts +8 -0
  60. package/dist/runtime-css.d.ts +8 -0
  61. package/dist/runtime-css.js +23 -7
  62. package/dist/runtime-css.js.map +1 -1
  63. package/dist/runtime-css.mjs +23 -7
  64. package/dist/runtime-css.mjs.map +1 -1
  65. package/dist/scanner.js +16 -37
  66. package/dist/scanner.js.map +1 -1
  67. package/dist/scanner.mjs +15 -36
  68. package/dist/scanner.mjs.map +1 -1
  69. package/dist/shared.d.mts +107 -1
  70. package/dist/shared.d.ts +107 -1
  71. package/dist/shared.js +1627 -376
  72. package/dist/shared.js.map +1 -1
  73. package/dist/shared.mjs +1620 -354
  74. package/dist/shared.mjs.map +1 -1
  75. package/dist/svelte.js +39 -35
  76. package/dist/svelte.js.map +1 -1
  77. package/dist/svelte.mjs +38 -34
  78. package/dist/svelte.mjs.map +1 -1
  79. package/dist/theme.js +85 -76
  80. package/dist/theme.js.map +1 -1
  81. package/dist/theme.mjs +83 -74
  82. package/dist/theme.mjs.map +1 -1
  83. package/dist/turbopackLoader.js +943 -76
  84. package/dist/turbopackLoader.js.map +1 -1
  85. package/dist/turbopackLoader.mjs +943 -76
  86. package/dist/turbopackLoader.mjs.map +1 -1
  87. package/dist/tw.js +262 -190
  88. package/dist/tw.js.map +1 -1
  89. package/dist/tw.mjs +259 -187
  90. package/dist/tw.mjs.map +1 -1
  91. package/dist/vite.js +1336 -296
  92. package/dist/vite.js.map +1 -1
  93. package/dist/vite.mjs +1336 -296
  94. package/dist/vite.mjs.map +1 -1
  95. package/dist/vue.js +39 -35
  96. package/dist/vue.js.map +1 -1
  97. package/dist/vue.mjs +38 -34
  98. package/dist/vue.mjs.map +1 -1
  99. package/dist/webpackLoader.js +140 -34
  100. package/dist/webpackLoader.js.map +1 -1
  101. package/dist/webpackLoader.mjs +140 -34
  102. package/dist/webpackLoader.mjs.map +1 -1
  103. package/native/index.node +0 -0
  104. package/native/tailwind-styled-native.node +0 -0
  105. package/native/tailwind-styled-native.win32-x64-msvc.node +0 -0
  106. package/package.json +9 -4
  107. package/CHANGELOG.md +0 -285
package/dist/next.js CHANGED
@@ -1,8 +1,8 @@
1
1
  'use strict';
2
2
 
3
3
  var module$1 = require('module');
4
- var fs5 = require('fs');
5
- var path5 = require('path');
4
+ var fs9 = require('fs');
5
+ var path10 = require('path');
6
6
  require('crypto');
7
7
  var url = require('url');
8
8
  var zod = require('zod');
@@ -27,8 +27,8 @@ function _interopNamespace(e) {
27
27
  return Object.freeze(n);
28
28
  }
29
29
 
30
- var fs5__namespace = /*#__PURE__*/_interopNamespace(fs5);
31
- var path5__namespace = /*#__PURE__*/_interopNamespace(path5);
30
+ var fs9__namespace = /*#__PURE__*/_interopNamespace(fs9);
31
+ var path10__namespace = /*#__PURE__*/_interopNamespace(path10);
32
32
 
33
33
  /* tailwind-styled-v4 v5.0.4 | MIT | https://github.com/dictionar32/tailwind-styled-v4 */
34
34
  var __defProp = Object.defineProperty;
@@ -84,11 +84,11 @@ function resolvePath(...segments) {
84
84
  return segments.join("/").replace(/\/+/g, "/");
85
85
  }
86
86
  }
87
- function existsSync(path7) {
87
+ function existsSync(path11) {
88
88
  if (isBrowser) return false;
89
89
  try {
90
90
  const nodeFs = __require(NODE_FS);
91
- return nodeFs.existsSync(path7);
91
+ return nodeFs.existsSync(path11);
92
92
  } catch {
93
93
  return false;
94
94
  }
@@ -157,12 +157,12 @@ function resolveNativeBinary(runtimeDir) {
157
157
  if (isBrowser2) {
158
158
  return { path: null, source: "not-found", platform, tried: ["not available in browser"] };
159
159
  }
160
- if (process.env.TWS_DISABLE_NATIVE === "1") {
160
+ if (process.env.TWS_NO_NATIVE === "1" || process.env.TWS_DISABLE_NATIVE === "1") {
161
161
  return { path: null, source: "not-found", platform, tried: [] };
162
162
  }
163
163
  const envPath = process.env.TW_NATIVE_PATH?.trim();
164
164
  if (envPath) {
165
- if (fs5__namespace.existsSync(envPath)) {
165
+ if (fs9__namespace.existsSync(envPath)) {
166
166
  return { path: envPath, source: "env", platform, tried };
167
167
  }
168
168
  tried.push(`env:${envPath} (not found)`);
@@ -171,7 +171,7 @@ function resolveNativeBinary(runtimeDir) {
171
171
  for (const pkg of prebuiltPkgs) {
172
172
  try {
173
173
  const candidate = _require.resolve(`${pkg}/tailwind_styled_parser.node`);
174
- if (fs5__namespace.existsSync(candidate)) {
174
+ if (fs9__namespace.existsSync(candidate)) {
175
175
  return { path: candidate, source: "prebuilt", platform, tried };
176
176
  }
177
177
  tried.push(`prebuilt:${pkg} (resolved but missing)`);
@@ -182,13 +182,13 @@ function resolveNativeBinary(runtimeDir) {
182
182
  const napiPlatform = platform === "linux-x64" ? "linux-x64-gnu" : platform === "linux-arm64" ? "linux-arm64-gnu" : platform;
183
183
  const BINARY_NAMES_SELF = ["tailwind-styled-native", "tailwind_styled_parser"];
184
184
  if (runtimeDir) {
185
- for (const depth of ["..", path5__namespace.join("..", ".."), path5__namespace.join("..", "..", "..")]) {
186
- const pkgRoot = path5__namespace.resolve(runtimeDir, depth);
185
+ for (const depth of ["..", path10__namespace.join("..", ".."), path10__namespace.join("..", "..", "..")]) {
186
+ const pkgRoot = path10__namespace.resolve(runtimeDir, depth);
187
187
  for (const bin of BINARY_NAMES_SELF) {
188
188
  for (const suffix of ["", `.${platform}`, `.${napiPlatform}`]) {
189
- const candidate = path5__namespace.resolve(pkgRoot, "native", `${bin}${suffix}.node`);
189
+ const candidate = path10__namespace.resolve(pkgRoot, "native", `${bin}${suffix}.node`);
190
190
  tried.push(`self-bundled:${candidate}`);
191
- if (fs5__namespace.existsSync(candidate)) {
191
+ if (fs9__namespace.existsSync(candidate)) {
192
192
  return { path: candidate, source: "prebuilt", platform, tried };
193
193
  }
194
194
  }
@@ -200,29 +200,29 @@ function resolveNativeBinary(runtimeDir) {
200
200
  const BINARY_NAMES = ["tailwind-styled-native", "tailwind_styled_parser"];
201
201
  const localCandidates = [];
202
202
  for (const bin of BINARY_NAMES) {
203
- localCandidates.push(path5__namespace.resolve(base, `${bin}.node`));
204
- localCandidates.push(path5__namespace.resolve(base, "..", `${bin}.node`));
205
- localCandidates.push(path5__namespace.resolve(base, `${bin}.${platform}.node`));
206
- localCandidates.push(path5__namespace.resolve(base, `${bin}.${napiPlatform}.node`));
203
+ localCandidates.push(path10__namespace.resolve(base, `${bin}.node`));
204
+ localCandidates.push(path10__namespace.resolve(base, "..", `${bin}.node`));
205
+ localCandidates.push(path10__namespace.resolve(base, `${bin}.${platform}.node`));
206
+ localCandidates.push(path10__namespace.resolve(base, `${bin}.${napiPlatform}.node`));
207
207
  }
208
208
  for (const startDir of [cwd, base]) {
209
209
  let dir = startDir;
210
210
  for (let i = 0; i < 6; i++) {
211
- const nativeDir = path5__namespace.resolve(dir, "native");
211
+ const nativeDir = path10__namespace.resolve(dir, "native");
212
212
  for (const bin of BINARY_NAMES) {
213
- localCandidates.push(path5__namespace.resolve(nativeDir, `${bin}.node`));
214
- localCandidates.push(path5__namespace.resolve(nativeDir, `${bin}.${platform}.node`));
215
- localCandidates.push(path5__namespace.resolve(nativeDir, `${bin}.${napiPlatform}.node`));
216
- localCandidates.push(path5__namespace.resolve(nativeDir, "target", "release", `${bin}.node`));
213
+ localCandidates.push(path10__namespace.resolve(nativeDir, `${bin}.node`));
214
+ localCandidates.push(path10__namespace.resolve(nativeDir, `${bin}.${platform}.node`));
215
+ localCandidates.push(path10__namespace.resolve(nativeDir, `${bin}.${napiPlatform}.node`));
216
+ localCandidates.push(path10__namespace.resolve(nativeDir, "target", "release", `${bin}.node`));
217
217
  }
218
- const parent = path5__namespace.resolve(dir, "..");
218
+ const parent = path10__namespace.resolve(dir, "..");
219
219
  if (parent === dir) break;
220
220
  dir = parent;
221
221
  }
222
222
  }
223
223
  for (const candidate of localCandidates) {
224
224
  tried.push(`local:${candidate}`);
225
- if (fs5__namespace.existsSync(candidate)) {
225
+ if (fs9__namespace.existsSync(candidate)) {
226
226
  return { path: candidate, source: "local", platform, tried };
227
227
  }
228
228
  }
@@ -243,984 +243,2042 @@ var init_native_resolution = __esm({
243
243
  };
244
244
  }
245
245
  });
246
- function createLogger(namespace) {
247
- const prefix = `[${namespace}]`;
248
- return {
249
- warn(...args) {
250
- process.stderr.write(`${prefix} ${args.map((a) => typeof a === "string" ? a : String(a)).join(" ")}
251
- `);
252
- },
253
- debug(...args) {
254
- process.stderr.write(`${prefix} ${args.map((a) => typeof a === "string" ? a : String(a)).join(" ")}
255
- `);
256
- },
257
- error(...args) {
258
- process.stderr.write(`${prefix} ${args.map((a) => typeof a === "string" ? a : String(a)).join(" ")}
259
- `);
260
- },
261
- log(...args) {
262
- process.stderr.write(`${prefix} ${args.map((a) => typeof a === "string" ? a : String(a)).join(" ")}
263
- `);
246
+
247
+ // packages/domain/compiler/src/nativeBridge.ts
248
+ var _loadNative, log, NATIVE_UNAVAILABLE_MESSAGE, nativeBridge, bridgeLoadAttempted, bridgeLoadError, isValidNativeBridge, getNativeBridge, resetNativeBridgeCache, adaptNativeResult;
249
+ var init_nativeBridge = __esm({
250
+ "packages/domain/compiler/src/nativeBridge.ts"() {
251
+ init_src2();
252
+ _loadNative = (path11) => __require(path11);
253
+ log = (...args) => {
254
+ if (process.env.DEBUG?.includes("compiler:native")) {
255
+ console.log("[compiler:native]", ...args);
256
+ }
257
+ };
258
+ NATIVE_UNAVAILABLE_MESSAGE = "[tailwind-styled/compiler v5] Native binding is required but not available.\nThis package requires native Rust bindings. There is no JavaScript fallback.\nPlease ensure:\n 1. The native module is properly installed\n 2. You have run: npm run build:rust (or use prebuilt binary)\n\nFor help, see: https://tailwind-styled.dev/docs/install";
259
+ nativeBridge = null;
260
+ bridgeLoadAttempted = false;
261
+ bridgeLoadError = null;
262
+ isValidNativeBridge = (mod) => {
263
+ const m = mod;
264
+ return !!(typeof m.transformSource === "function" || typeof m.extractAllClasses === "function" || typeof m.hasTwUsage === "function");
265
+ };
266
+ getNativeBridge = () => {
267
+ if (nativeBridge) {
268
+ return nativeBridge;
269
+ }
270
+ if (bridgeLoadAttempted) {
271
+ if (bridgeLoadError) {
272
+ throw bridgeLoadError;
273
+ }
274
+ throw new Error(NATIVE_UNAVAILABLE_MESSAGE);
275
+ }
276
+ bridgeLoadAttempted = true;
277
+ try {
278
+ const runtimeDir = resolveRuntimeDir(void 0, (typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('next.js', document.baseURI).href)));
279
+ const result = resolveNativeBinary(runtimeDir);
280
+ if (result.path && result.path.endsWith(".node")) {
281
+ try {
282
+ const binding = _loadNative(result.path);
283
+ if (isValidNativeBridge(binding)) {
284
+ nativeBridge = binding;
285
+ log("Native bridge loaded successfully from:", result.path);
286
+ return nativeBridge;
287
+ }
288
+ } catch (e) {
289
+ log("Failed to require native binding:", e);
290
+ }
291
+ }
292
+ throw new Error(`${NATIVE_UNAVAILABLE_MESSAGE}
293
+
294
+ Tried paths: ${result.tried.join("\n")}`);
295
+ } catch (err) {
296
+ bridgeLoadError = err instanceof Error ? err : new Error(String(err));
297
+ log("Failed to load native bridge:", bridgeLoadError.message);
298
+ throw bridgeLoadError;
299
+ }
300
+ };
301
+ resetNativeBridgeCache = () => {
302
+ nativeBridge = null;
303
+ bridgeLoadAttempted = false;
304
+ bridgeLoadError = null;
305
+ log("Native bridge cache reset");
306
+ };
307
+ adaptNativeResult = (raw) => {
308
+ return {
309
+ code: raw.code ?? "",
310
+ classes: raw.classes ?? [],
311
+ changed: raw.changed ?? false,
312
+ rsc: raw.rscJson ? JSON.parse(raw.rscJson) : void 0,
313
+ metadata: raw.metadataJson ? JSON.parse(raw.metadataJson) : void 0
314
+ };
315
+ };
316
+ if (typeof process !== "undefined" && !bridgeLoadAttempted) {
317
+ try {
318
+ getNativeBridge();
319
+ } catch {
320
+ }
264
321
  }
265
- };
322
+ }
323
+ });
324
+
325
+ // packages/domain/compiler/src/tailwindEngine.ts
326
+ var tailwindEngine_exports = {};
327
+ __export(tailwindEngine_exports, {
328
+ clearCache: () => clearCache,
329
+ generateRawCss: () => generateRawCss,
330
+ getCacheStats: () => getCacheStats,
331
+ processTailwindCssWithTargets: () => processTailwindCssWithTargets,
332
+ runCssPipeline: () => runCssPipeline,
333
+ runCssPipelineSync: () => runCssPipelineSync
334
+ });
335
+ function _getCacheKey(classes, minify, cssEntry, root) {
336
+ const sorted = [...classes].sort().join(",");
337
+ const flags = `${minify ? "1" : "0"}${cssEntry ? "1" : "0"}${root ? "1" : "0"}`;
338
+ return `${sorted}|${flags}`;
266
339
  }
267
- function createDebugLogger(namespace, label) {
268
- const prefix = `[${namespace}]`;
269
- return (msg) => {
270
- if (process.env.DEBUG?.includes(namespace) || process.env.TW_DEBUG) {
271
- console.debug(prefix, msg);
340
+ function _evictOldestIfNeeded() {
341
+ if (_cssCache.size >= MAX_CACHE_SIZE) {
342
+ const firstKey = _cssCache.keys().next().value;
343
+ if (firstKey !== void 0) {
344
+ _cssCache.delete(firstKey);
272
345
  }
346
+ }
347
+ }
348
+ function getCacheStats() {
349
+ const total = _cacheHits + _cacheMisses;
350
+ return {
351
+ hits: _cacheHits,
352
+ misses: _cacheMisses,
353
+ hitRate: total > 0 ? _cacheHits / total : 0,
354
+ size: _cssCache.size,
355
+ maxSize: MAX_CACHE_SIZE
273
356
  };
274
357
  }
275
- function formatIssuePath(path7) {
276
- if (!path7 || path7.length === 0) return "(root)";
277
- return path7.map(
278
- (segment) => typeof segment === "symbol" ? segment.description ?? segment.toString() : String(segment)
279
- ).join(".");
358
+ function clearCache() {
359
+ _cssCache.clear();
360
+ _cacheHits = 0;
361
+ _cacheMisses = 0;
280
362
  }
281
- function loadNativeBinding(options) {
282
- const { runtimeDir, candidates, isValid } = options;
283
- const loadErrors = [];
284
- for (const candidate of candidates) {
285
- const candidatePath = path5__namespace.default.resolve(runtimeDir, candidate);
363
+ function loadTailwindEngine() {
364
+ if (_twEngine) return _twEngine;
365
+ if (_twEngineError) throw _twEngineError;
366
+ try {
367
+ const tw = require2("tailwindcss");
368
+ if (typeof tw.compile !== "function") {
369
+ throw new Error("tailwindcss v4 not found \u2014 compile() API missing. Check tailwindcss version >= 4.");
370
+ }
371
+ _twEngine = tw;
372
+ return _twEngine;
373
+ } catch (e) {
374
+ _twEngineError = e instanceof Error ? e : new Error(String(e));
375
+ throw _twEngineError;
376
+ }
377
+ }
378
+ async function generateRawCss(classes, cssEntryContent, root) {
379
+ if (classes.length === 0) return "";
380
+ const tw = loadTailwindEngine();
381
+ const input = cssEntryContent ?? "@import 'tailwindcss';";
382
+ const { readFileSync, existsSync: existsSync3 } = await import('fs');
383
+ const { dirname, resolve: resolve2 } = await import('path');
384
+ const projectRoot = root ?? process.cwd();
385
+ const req = module$1.createRequire(resolve2(projectRoot, "package.json"));
386
+ const loadStylesheet = async (id, base) => {
286
387
  try {
287
- if (!fs5__namespace.default.existsSync(candidatePath) && !fs5__namespace.default.existsSync(candidatePath + ".node")) {
288
- continue;
388
+ const cssId = id === "tailwindcss" ? "tailwindcss/index.css" : id === "tailwindcss/preflight" ? "tailwindcss/preflight.css" : id === "tailwindcss/utilities" ? "tailwindcss/utilities.css" : id === "tailwindcss/theme" ? "tailwindcss/theme.css" : id;
389
+ const pkgPath = req.resolve(cssId);
390
+ return { content: readFileSync(pkgPath, "utf-8"), base: dirname(pkgPath) };
391
+ } catch {
392
+ try {
393
+ const absPath = resolve2(base, id);
394
+ if (existsSync3(absPath)) {
395
+ return { content: readFileSync(absPath, "utf-8"), base: dirname(absPath) };
396
+ }
397
+ } catch {
289
398
  }
290
- const mod = requireNativeModule(candidatePath);
291
- if (mod && isValid(mod)) {
292
- return { binding: mod, loadErrors, loadedPath: candidatePath };
399
+ return { content: "", base };
400
+ }
401
+ };
402
+ const compiler = await Promise.resolve(tw.compile(input, { loadStylesheet }));
403
+ return compiler.build(classes);
404
+ }
405
+ function getThemeConfig() {
406
+ return {
407
+ colors: {
408
+ slate: {
409
+ "50": "#f8fafc",
410
+ "100": "#f1f5f9",
411
+ "200": "#e2e8f0",
412
+ "300": "#cbd5e1",
413
+ "400": "#94a3b8",
414
+ "500": "#64748b",
415
+ "600": "#475569",
416
+ "700": "#334155",
417
+ "800": "#1e293b",
418
+ "900": "#0f172a"
419
+ },
420
+ gray: {
421
+ "50": "#f9fafb",
422
+ "100": "#f3f4f6",
423
+ "200": "#e5e7eb",
424
+ "300": "#d1d5db",
425
+ "400": "#9ca3af",
426
+ "500": "#6b7280",
427
+ "600": "#4b5563",
428
+ "700": "#374151",
429
+ "800": "#1f2937",
430
+ "900": "#111827"
431
+ },
432
+ white: "#ffffff",
433
+ black: "#000000",
434
+ red: {
435
+ "500": "#ef4444",
436
+ "600": "#dc2626"
437
+ },
438
+ blue: {
439
+ "500": "#3b82f6",
440
+ "600": "#1e40af"
293
441
  }
294
- loadErrors.push({ path: candidatePath, message: options.invalidExportMessage });
295
- } catch (e) {
296
- loadErrors.push({ path: candidatePath, message: e instanceof Error ? e.message : String(e) });
442
+ },
443
+ spacing: {
444
+ "0": "0px",
445
+ "1": "0.25rem",
446
+ "2": "0.5rem",
447
+ "3": "0.75rem",
448
+ "4": "1rem",
449
+ "5": "1.25rem",
450
+ "6": "1.5rem",
451
+ "8": "2rem",
452
+ "10": "2.5rem",
453
+ "12": "3rem",
454
+ "16": "4rem",
455
+ "20": "5rem",
456
+ "24": "6rem"
457
+ },
458
+ breakpoints: {
459
+ "sm": "640px",
460
+ "md": "768px",
461
+ "lg": "1024px",
462
+ "xl": "1280px",
463
+ "2xl": "1536px"
297
464
  }
465
+ };
466
+ }
467
+ function postProcessWithLightning(rawCss) {
468
+ if (!rawCss) return "";
469
+ const native = getNativeBridge();
470
+ if (!native?.processTailwindCssLightning) {
471
+ throw new Error("FATAL: Native binding 'processTailwindCssLightning' is required but not available.");
298
472
  }
299
- return { binding: null, loadErrors };
473
+ const result = native.processTailwindCssLightning(rawCss);
474
+ if (!result?.css) {
475
+ throw new Error("FATAL: processTailwindCssLightning returned null");
476
+ }
477
+ return result.css;
300
478
  }
301
- function requireNativeModule(p) {
302
- return _require2(p);
479
+ async function runCssPipeline(classes, cssEntryContent, root, minify = true) {
480
+ const filtered = classes.filter(Boolean);
481
+ const uniqueMap = /* @__PURE__ */ new Map();
482
+ filtered.forEach((cls) => uniqueMap.set(cls, cls));
483
+ const unique = Array.from(uniqueMap.values());
484
+ if (unique.length === 0) {
485
+ return { css: "", classes: [], sizeBytes: 0, optimized: false };
486
+ }
487
+ const cacheKey = _getCacheKey(unique, minify, cssEntryContent, root);
488
+ const cached = _cssCache.get(cacheKey);
489
+ if (cached) {
490
+ _cacheHits++;
491
+ if (process.env.DEBUG?.includes("compiler")) {
492
+ console.log(
493
+ `[Compiler] Cache HIT: ${unique.length} classes (hit rate: ${(getCacheStats().hitRate * 100).toFixed(1)}%)`
494
+ );
495
+ }
496
+ return cached;
497
+ }
498
+ _cacheMisses++;
499
+ let rawCss;
500
+ let usedRustCompiler = false;
501
+ try {
502
+ const theme = getThemeConfig();
503
+ rawCss = await generateCssNative(unique, {
504
+ theme,
505
+ fallbackToJs: true,
506
+ logFallback: process.env.DEBUG?.includes("compiler") === true
507
+ });
508
+ usedRustCompiler = true;
509
+ } catch (error) {
510
+ if (process.env.DEBUG?.includes("compiler")) {
511
+ console.warn("[Compiler] Rust compiler failed, using JavaScript Tailwind:", error);
512
+ }
513
+ rawCss = await generateRawCss(unique, cssEntryContent, root);
514
+ }
515
+ const finalCss = minify ? postProcessWithLightning(rawCss) : rawCss;
516
+ if (process.env.DEBUG?.includes("compiler")) {
517
+ console.log(
518
+ `[Compiler] Generated CSS from ${unique.length} classes (${usedRustCompiler ? "Rust" : "JavaScript"})`,
519
+ `Size: ${finalCss.length} bytes`
520
+ );
521
+ }
522
+ const result = {
523
+ css: finalCss,
524
+ classes: unique,
525
+ sizeBytes: finalCss.length,
526
+ optimized: minify
527
+ };
528
+ _evictOldestIfNeeded();
529
+ _cssCache.set(cacheKey, result);
530
+ return result;
303
531
  }
304
- function resolveNativeBindingCandidates(options) {
532
+ function runCssPipelineSync(_classes) {
533
+ return { css: "", classes: [], sizeBytes: 0, optimized: false };
534
+ }
535
+ function processTailwindCssWithTargets(css, targets) {
536
+ const native = getNativeBridge();
537
+ if (!native?.processTailwindCssWithTargets) {
538
+ throw new Error("FATAL: Native binding 'processTailwindCssWithTargets' is required but not available.");
539
+ }
540
+ const result = native.processTailwindCssWithTargets(css, targets ?? null);
541
+ if (!result?.css) {
542
+ throw new Error("FATAL: processTailwindCssWithTargets returned null");
543
+ }
544
+ return result.css;
545
+ }
546
+ var require2, _cssCache, _cacheHits, _cacheMisses, MAX_CACHE_SIZE, _twEngine, _twEngineError;
547
+ var init_tailwindEngine = __esm({
548
+ "packages/domain/compiler/src/tailwindEngine.ts"() {
549
+ init_nativeBridge();
550
+ init_cssGeneratorNative();
551
+ require2 = module$1.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('next.js', document.baseURI).href)));
552
+ _cssCache = /* @__PURE__ */ new Map();
553
+ _cacheHits = 0;
554
+ _cacheMisses = 0;
555
+ MAX_CACHE_SIZE = 100;
556
+ _twEngine = null;
557
+ _twEngineError = null;
558
+ }
559
+ });
560
+
561
+ // packages/domain/compiler/src/cssGeneratorNative.ts
562
+ async function generateCssNative(classes, options) {
305
563
  const {
306
- envVarNames = ["TW_NATIVE_PATH", "TWS_NATIVE_PATH"],
307
- includeDefaultCandidates = true,
308
- enforceNodeExtensionForEnvPath = false
564
+ theme,
565
+ fallbackToJs = true,
566
+ logFallback = false
309
567
  } = options;
310
- const runtimeDir = options.runtimeDir || process.cwd();
311
- const candidates = [];
312
- for (const envVar of envVarNames) {
313
- const envPath = process.env[envVar];
314
- if (envPath) {
315
- candidates.push(enforceNodeExtensionForEnvPath && !envPath.endsWith(".node") ? envPath + ".node" : envPath);
568
+ try {
569
+ const native = getNativeBridge();
570
+ if (!native?.generateCssNative) {
571
+ throw new Error("generateCssNative not available in native binding");
316
572
  }
317
- }
318
- if (!includeDefaultCandidates) return candidates;
319
- if (fs5__namespace.default.existsSync(runtimeDir)) {
320
- try {
321
- for (const entry of fs5__namespace.default.readdirSync(runtimeDir)) {
322
- if (entry.endsWith(".node")) candidates.push(entry);
323
- }
324
- } catch {
573
+ const themeJson = JSON.stringify(theme);
574
+ const css = native.generateCssNative(classes, themeJson);
575
+ return css;
576
+ } catch (error) {
577
+ if (!fallbackToJs) {
578
+ throw error;
325
579
  }
580
+ if (logFallback) {
581
+ console.warn(
582
+ "[CSS Compiler] Rust CSS generator unavailable, falling back to JavaScript Tailwind",
583
+ error instanceof Error ? error.message : String(error)
584
+ );
585
+ }
586
+ return generateRawCss(classes);
326
587
  }
327
- const BINARY_NAMES = ["tailwind-styled-native", "tailwind_styled_parser"];
328
- const napiPlatform = process.platform === "linux" && process.arch === "x64" ? "linux-x64-gnu" : process.platform === "linux" && process.arch === "arm64" ? "linux-arm64-gnu" : `${process.platform}-${process.arch}`;
329
- for (const bin of BINARY_NAMES) {
330
- candidates.push(path5__namespace.default.resolve(runtimeDir, `${bin}.node`));
331
- candidates.push(path5__namespace.default.resolve(runtimeDir, `${bin}.${napiPlatform}.node`));
332
- candidates.push(path5__namespace.default.resolve(runtimeDir, "..", "native", `${bin}.node`));
333
- candidates.push(path5__namespace.default.resolve(runtimeDir, "..", "native", `${bin}.${napiPlatform}.node`));
334
- candidates.push(path5__namespace.default.resolve(process.cwd(), "native", `${bin}.node`));
335
- candidates.push(path5__namespace.default.resolve(process.cwd(), "native", `${bin}.${napiPlatform}.node`));
336
- candidates.push(path5__namespace.default.resolve(runtimeDir, "..", "..", "..", "..", "native", `${bin}.node`));
337
- candidates.push(path5__namespace.default.resolve(runtimeDir, "..", "..", "..", "..", "native", `${bin}.${napiPlatform}.node`));
338
- candidates.push(path5__namespace.default.resolve(runtimeDir, "..", "..", "..", "native", `${bin}.node`));
588
+ }
589
+ function getCacheStats2() {
590
+ try {
591
+ const native = getNativeBridge();
592
+ if (!native?.getCacheStats) {
593
+ return null;
594
+ }
595
+ const [hits, misses] = native.getCacheStats();
596
+ return { hits, misses };
597
+ } catch {
598
+ return null;
339
599
  }
340
- return Array.from(new Set(candidates));
341
600
  }
342
- function resolveRuntimeDir(dir, importMetaUrl) {
601
+ function clearThemeCache() {
343
602
  try {
344
- return path5__namespace.default.dirname(url.fileURLToPath(importMetaUrl));
603
+ const native = getNativeBridge();
604
+ if (!native?.clearThemeCache) {
605
+ return;
606
+ }
607
+ native.clearThemeCache();
345
608
  } catch {
346
- return process.cwd();
347
609
  }
348
610
  }
349
- var TwError, _require2;
350
- var init_src = __esm({
351
- "packages/domain/shared/src/index.ts"() {
352
- init_workerResolver();
353
- init_native_resolution();
354
- TwError = class _TwError extends Error {
355
- /** @deprecated Gunakan source */
356
- domain;
357
- source;
358
- code;
359
- originalCause;
360
- constructor(domainOrSource, code, message, cause) {
361
- super(message);
362
- this.name = "TwError";
363
- this.domain = domainOrSource;
364
- this.source = domainOrSource;
365
- this.code = code;
366
- this.originalCause = cause;
367
- if (Error.captureStackTrace) Error.captureStackTrace(this, _TwError);
368
- }
369
- static fromIo(code, message) {
370
- return new _TwError("io", code, message);
371
- }
372
- static fromCompile(code, message) {
373
- return new _TwError("compile", code, message);
374
- }
375
- static fromRust(err) {
376
- if (err instanceof _TwError) return err;
377
- if (err instanceof Error) return new _TwError("rust", "RUST_ERROR", err.message, err);
378
- if (err && typeof err === "object") {
379
- const e = err;
380
- return new _TwError("rust", e.code ?? "RUST_ERROR", e.message ?? String(err), err);
381
- }
382
- return new _TwError("rust", "RUST_ERROR", String(err), err);
383
- }
384
- /** Buat TwError dari ZodError — dukung shape Zod v3 (`errors`) dan v4 (`issues`). */
385
- static fromZod(err) {
386
- const first = err.issues?.[0] ?? err.errors?.[0];
387
- const path7 = formatIssuePath(first?.path);
388
- const message = first ? `${path7}: ${first.message}` : "Schema validation failed";
389
- return new _TwError("validation", "SCHEMA_VALIDATION_FAILED", message, err);
390
- }
391
- static wrap(source, code, err) {
392
- if (err instanceof _TwError) return err;
393
- if (err instanceof Error) return new _TwError(source, code, err.message, err);
394
- return new _TwError(source, code, String(err), err);
395
- }
396
- toString() {
397
- return `TwError [${this.source}:${this.code}] ${this.message}`;
398
- }
399
- toJSON() {
400
- return { name: this.name, source: this.source, code: this.code, message: this.message };
401
- }
402
- toCliMessage() {
403
- return `[${this.source.toUpperCase()}:${this.code}] ${this.message}`;
404
- }
405
- };
406
- _require2 = module$1.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('next.js', document.baseURI).href)));
611
+ var init_cssGeneratorNative = __esm({
612
+ "packages/domain/compiler/src/cssGeneratorNative.ts"() {
613
+ init_nativeBridge();
614
+ init_tailwindEngine();
407
615
  }
408
616
  });
409
617
 
410
- // packages/domain/scanner/src/native-bridge.ts
411
- var native_bridge_exports = {};
412
- __export(native_bridge_exports, {
413
- batchExtractClassesNative: () => batchExtractClassesNative,
414
- cachePriorityNative: () => cachePriorityNative,
415
- cacheReadNative: () => cacheReadNative,
416
- cacheWriteNative: () => cacheWriteNative,
417
- collectFilesNative: () => collectFilesNative,
418
- computeCacheStatsNative: () => computeCacheStatsNative,
419
- extractClassesNative: () => extractClassesNative,
420
- generateSubComponentTypesNative: () => generateSubComponentTypesNative,
421
- hasNativeScannerBinding: () => hasNativeScannerBinding,
422
- hasNativeWatchBinding: () => hasNativeWatchBinding,
423
- hashContentNative: () => hashContentNative,
424
- isRustCacheAvailable: () => isRustCacheAvailable,
425
- pollWatchEventsNative: () => pollWatchEventsNative,
426
- pruneStaleEntriesNative: () => pruneStaleEntriesNative,
427
- rebuildWorkspaceResultNative: () => rebuildWorkspaceResultNative,
428
- resetScannerBridgeCache: () => resetScannerBridgeCache,
429
- scanCacheGet: () => scanCacheGet,
430
- scanCacheInvalidate: () => scanCacheInvalidate,
431
- scanCachePut: () => scanCachePut,
432
- scanCacheStats: () => scanCacheStats,
433
- scanFileNative: () => scanFileNative,
434
- scanFilesBatchNative: () => scanFilesBatchNative,
435
- scanWorkspaceNative: () => scanWorkspaceNative,
436
- startWatchNative: () => startWatchNative,
437
- stopWatchNative: () => stopWatchNative
438
- });
439
- function getDirname() {
440
- if (typeof __dirname !== "undefined") {
441
- return __dirname;
442
- }
443
- if (typeof ({ url: (typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('next.js', document.baseURI).href)) }) !== "undefined" && (typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('next.js', document.baseURI).href))) {
444
- return path5__namespace.default.dirname(url.fileURLToPath((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('next.js', document.baseURI).href))));
445
- }
446
- return process.cwd();
618
+ // packages/domain/compiler/src/scannerNative.ts
619
+ function scanWorkspace(root, extensions) {
620
+ const native = getNativeBridge();
621
+ if (!native?.scan_workspace) throw new Error("scan_workspace not available");
622
+ return native.scan_workspace(root, extensions);
447
623
  }
448
- function scanWorkspaceNative(root, extensions) {
449
- return scannerGetBinding().scanWorkspace(root, extensions ?? null);
624
+ function extractClassesFromSourceNative(source) {
625
+ const native = getNativeBridge();
626
+ if (!native?.extract_classes_from_source) throw new Error("extract_classes_from_source not available");
627
+ return native.extract_classes_from_source(source);
450
628
  }
451
- function extractClassesNative(source) {
452
- const result = scannerGetBinding().extractClassesFromSource?.(source);
453
- if (result === null || result === void 0) {
454
- throw new TwError(
455
- "rust",
456
- "SCANNER_EXTRACT_FAILED",
457
- "Native extractClassesFromSource returned null/undefined"
458
- );
459
- }
460
- return result;
629
+ function batchExtractClassesNative(filePaths) {
630
+ const native = getNativeBridge();
631
+ if (!native?.batch_extract_classes) throw new Error("batch_extract_classes not available");
632
+ return native.batch_extract_classes(filePaths);
461
633
  }
462
- function hashContentNative(content) {
463
- const result = scannerGetBinding().hashFileContent?.(content);
464
- if (result === null || result === void 0) {
465
- throw new TwError(
466
- "rust",
467
- "SCANNER_HASH_FAILED",
468
- "Native hashFileContent returned null/undefined"
469
- );
470
- }
471
- return result;
634
+ function checkAgainstSafelistNative(classes, safelist) {
635
+ const native = getNativeBridge();
636
+ if (!native?.check_against_safelist) throw new Error("check_against_safelist not available");
637
+ return native.check_against_safelist(classes, safelist);
472
638
  }
473
- function isRustCacheAvailable() {
474
- return true;
639
+ function scanFile(filePath) {
640
+ const native = getNativeBridge();
641
+ if (!native?.scan_file) throw new Error("scan_file not available");
642
+ return native.scan_file(filePath);
475
643
  }
476
- function hasNativeScannerBinding() {
477
- try {
478
- scannerBridgeLoader.get();
479
- return true;
480
- } catch {
481
- return false;
482
- }
644
+ function collectFiles(root, extensions) {
645
+ const native = getNativeBridge();
646
+ if (!native?.collect_files) throw new Error("collect_files not available");
647
+ return native.collect_files(root, extensions);
483
648
  }
484
- function cacheReadNative(cachePath) {
485
- const result = scannerGetBinding().cacheRead?.(cachePath);
486
- if (result === null || result === void 0) {
487
- throw new TwError(
488
- "rust",
489
- "SCANNER_CACHE_READ_FAILED",
490
- "Native cacheRead returned null/undefined"
491
- );
492
- }
493
- return result;
649
+ function walkAndPrefilterSourceFiles(root, extensions, _parallel) {
650
+ const native = getNativeBridge();
651
+ if (!native?.walk_and_prefilter_source_files) throw new Error("walk_and_prefilter_source_files not available");
652
+ return native.walk_and_prefilter_source_files(root, extensions);
494
653
  }
495
- function cacheWriteNative(cachePath, entries) {
496
- const result = scannerGetBinding().cacheWrite?.(cachePath, entries);
497
- if (result === null || result === void 0) {
498
- throw new TwError(
499
- "rust",
500
- "SCANNER_CACHE_WRITE_FAILED",
501
- "Native cacheWrite returned null/undefined"
502
- );
503
- }
504
- return result;
654
+ function generateSubComponentTypes(root, outputPath) {
655
+ const native = getNativeBridge();
656
+ if (!native?.generate_sub_component_types) throw new Error("generate_sub_component_types not available");
657
+ return native.generate_sub_component_types(root, outputPath);
505
658
  }
506
- function cachePriorityNative(mtimeMs, size, cachedMtimeMs, cachedSize, cachedHitCount, cachedLastSeenMs, nowMs = Date.now()) {
507
- const result = scannerGetBinding().cachePriority?.(
508
- mtimeMs,
509
- size,
510
- cachedMtimeMs,
511
- cachedSize,
512
- cachedHitCount,
513
- cachedLastSeenMs,
514
- nowMs
515
- );
516
- if (result === null || result === void 0) {
517
- throw new TwError(
518
- "rust",
519
- "SCANNER_CACHE_PRIORITY_FAILED",
520
- "Native cachePriority returned null/undefined"
521
- );
659
+ var init_scannerNative = __esm({
660
+ "packages/domain/compiler/src/scannerNative.ts"() {
661
+ init_nativeBridge();
522
662
  }
523
- return result;
663
+ });
664
+
665
+ // packages/domain/compiler/src/analyzerNative.ts
666
+ function detectDeadCode(scanResultJson, css) {
667
+ const native = getNativeBridge();
668
+ if (!native?.detectDeadCode) throw new Error("detectDeadCode not available");
669
+ return native.detectDeadCode(scanResultJson, css);
524
670
  }
525
- function batchExtractClassesNative(filePaths) {
526
- const binding = scannerGetBinding();
527
- if (!binding.batchExtractClasses) {
528
- throw new Error("FATAL: Native binding 'batchExtractClasses' is required but not available.");
529
- }
530
- return binding.batchExtractClasses(filePaths) ?? [];
671
+ function analyzeClassUsageNative(classes, scanResultJson, css) {
672
+ const native = getNativeBridge();
673
+ if (!native?.analyzeClassUsage) throw new Error("analyzeClassUsage not available");
674
+ return native.analyzeClassUsage(classes, scanResultJson, css);
531
675
  }
532
- function scanCacheGet(filePath, contentHash) {
533
- const binding = scannerGetBinding();
534
- if (!binding.scanCacheGet) {
535
- throw new Error("FATAL: Native binding 'scanCacheGet' is required but not available.");
536
- }
537
- return binding.scanCacheGet(filePath, contentHash) ?? null;
676
+ function analyzeClassesNative(filesJson, cwd, flags) {
677
+ const native = getNativeBridge();
678
+ if (!native?.analyzeClasses) throw new Error("analyzeClasses not available");
679
+ return native.analyzeClasses(filesJson, cwd, flags ?? 0);
538
680
  }
539
- function scanCachePut(filePath, contentHash, classes, mtimeMs, size) {
540
- const binding = scannerGetBinding();
541
- if (!binding.scanCachePut) {
542
- throw new Error("FATAL: Native binding 'scanCachePut' is required but not available.");
543
- }
544
- binding.scanCachePut(filePath, contentHash, classes, mtimeMs, size);
681
+ function analyzeRscNative(source, filename) {
682
+ const native = getNativeBridge();
683
+ if (!native?.analyzeRsc) throw new Error("analyzeRsc not available");
684
+ return native.analyzeRsc(source, filename);
545
685
  }
546
- function scanCacheInvalidate(filePath) {
547
- const binding = scannerGetBinding();
548
- if (!binding.scanCacheInvalidate) {
549
- throw new Error("FATAL: Native binding 'scanCacheInvalidate' is required but not available.");
550
- }
551
- binding.scanCacheInvalidate(filePath);
686
+ function optimizeCssNative(css) {
687
+ const native = getNativeBridge();
688
+ if (!native?.processTailwindCssLightning) throw new Error("processTailwindCssLightning not available");
689
+ const result = native.processTailwindCssLightning(css);
690
+ return {
691
+ css: result.css,
692
+ originalSize: css.length,
693
+ optimizedSize: result.size_bytes,
694
+ reductionPercentage: (css.length - result.size_bytes) / css.length * 100
695
+ };
552
696
  }
553
- function scanCacheStats() {
554
- const binding = scannerGetBinding();
555
- if (!binding.scanCacheStats) {
556
- throw new Error("FATAL: Native binding 'scanCacheStats' is required but not available.");
557
- }
558
- return binding.scanCacheStats();
697
+ function processTailwindCssLightning(css) {
698
+ const native = getNativeBridge();
699
+ if (!native?.processTailwindCssLightning) throw new Error("processTailwindCssLightning not available");
700
+ return native.processTailwindCssLightning(css);
559
701
  }
560
- function scanFileNative(filePath) {
561
- const binding = scannerGetBinding();
562
- if (!binding.scanFile) {
563
- throw new Error("FATAL: Native binding 'scanFile' is required but not available.");
564
- }
565
- return binding.scanFile(filePath);
702
+ function eliminateDeadCssNative(css, deadClasses) {
703
+ const native = getNativeBridge();
704
+ if (!native?.eliminateDeadCss) throw new Error("eliminateDeadCss not available");
705
+ return native.eliminateDeadCss(css, deadClasses);
566
706
  }
567
- function collectFilesNative(root, extensions, ignoreDirs) {
568
- const binding = scannerGetBinding();
569
- if (!binding.collectFiles) return null;
570
- return binding.collectFiles(root, extensions, ignoreDirs);
707
+ function hoistComponentsNative(source) {
708
+ const native = getNativeBridge();
709
+ if (!native?.hoistComponents) throw new Error("hoistComponents not available");
710
+ return native.hoistComponents(source);
571
711
  }
572
- function scanFilesBatchNative(filePaths) {
573
- const binding = scannerGetBinding();
574
- if (!binding.scanFilesBatch) {
575
- return filePaths.map((fp) => {
576
- try {
577
- const r = binding.scanFile?.(fp);
578
- return r ? { file: r.file, classes: r.classes, hash: r.hash ?? "" } : { file: fp, classes: [], hash: "" };
579
- } catch {
580
- return { file: fp, classes: [], hash: "" };
581
- }
582
- });
583
- }
584
- return binding.scanFilesBatch(filePaths);
712
+ function compileVariantTableNative(configJson) {
713
+ const native = getNativeBridge();
714
+ if (!native?.compileVariantTable) throw new Error("compileVariantTable not available");
715
+ return native.compileVariantTable(configJson);
585
716
  }
586
- function generateSubComponentTypesNative(root, outputPath) {
587
- const binding = scannerGetBinding();
588
- if (!binding.generateSubComponentTypes) return null;
589
- return binding.generateSubComponentTypes(root, outputPath ?? null);
717
+ function classifyAndSortClassesNative(classes) {
718
+ const native = getNativeBridge();
719
+ if (!native?.classifyAndSortClasses) throw new Error("classifyAndSortClasses not available");
720
+ return native.classifyAndSortClasses(classes);
590
721
  }
591
- function pruneStaleEntriesNative(entries, maxAgeMs, checkExists) {
592
- const binding = scannerGetBinding();
593
- if (!binding.pruneStaleEntries) return null;
594
- return binding.pruneStaleEntries(
595
- entries.map((e) => ({ file: e.file, lastSeenMs: e.lastSeenMs ?? 0 })),
596
- maxAgeMs ?? null,
597
- checkExists ?? null
598
- );
722
+ function mergeCssDeclarationsNative(cssChunks) {
723
+ const native = getNativeBridge();
724
+ if (!native?.mergeCssDeclarations) throw new Error("mergeCssDeclarations not available");
725
+ return native.mergeCssDeclarations(cssChunks);
599
726
  }
600
- function rebuildWorkspaceResultNative(files) {
601
- const binding = scannerBridgeLoader.get();
602
- if (!binding?.rebuildWorkspaceResult) return null;
603
- try {
604
- return binding.rebuildWorkspaceResult(files);
605
- } catch {
606
- return null;
727
+ var init_analyzerNative = __esm({
728
+ "packages/domain/compiler/src/analyzerNative.ts"() {
729
+ init_nativeBridge();
607
730
  }
731
+ });
732
+
733
+ // packages/domain/compiler/src/compilationNative.ts
734
+ function compileCssNative2(classes, prefix) {
735
+ const native = getNativeBridge();
736
+ if (!native?.compileCss) throw new Error("compileCss not available");
737
+ return native.compileCss(classes, prefix);
608
738
  }
609
- function computeCacheStatsNative(filesClasses, sizes, top) {
610
- const binding = scannerGetBinding();
611
- if (!binding.computeCacheStats) return null;
612
- return binding.computeCacheStats(filesClasses, sizes, top ?? null);
739
+ function compileCssLightning(classes) {
740
+ const native = getNativeBridge();
741
+ if (!native?.compileCssLightning) throw new Error("compileCssLightning not available");
742
+ return native.compileCssLightning(classes);
613
743
  }
614
- function startWatchNative(rootDir) {
615
- try {
616
- const binding = scannerGetBinding();
617
- if (!binding.startWatch) return null;
618
- return binding.startWatch(rootDir);
744
+ function extractTwStateConfigsNative(source, filename) {
745
+ const native = getNativeBridge();
746
+ if (!native?.extractTwStateConfigs) throw new Error("extractTwStateConfigs not available");
747
+ return native.extractTwStateConfigs(source, filename);
748
+ }
749
+ function generateStaticStateCssNative(inputs, resolvedCss) {
750
+ const native = getNativeBridge();
751
+ if (!native?.generateStaticStateCss) throw new Error("generateStaticStateCss not available");
752
+ return native.generateStaticStateCss(inputs, resolvedCss ?? null);
753
+ }
754
+ function extractAndGenerateStateCssNative(source, filename) {
755
+ const native = getNativeBridge();
756
+ if (!native?.extractAndGenerateStateCss) throw new Error("extractAndGenerateStateCss not available");
757
+ return native.extractAndGenerateStateCss(source, filename);
758
+ }
759
+ function layoutClassesToCss(classes) {
760
+ const native = getNativeBridge();
761
+ if (!native?.layoutClassesToCss) throw new Error("layoutClassesToCss not available");
762
+ return native.layoutClassesToCss(classes);
763
+ }
764
+ function hashContent(input, algorithm = "sha256", length = 8) {
765
+ const native = getNativeBridge();
766
+ if (!native?.hashContent) throw new Error("hashContent not available");
767
+ return native.hashContent(input, algorithm, length);
768
+ }
769
+ function extractTwContainerConfigs(source) {
770
+ const native = getNativeBridge();
771
+ if (!native?.extractTwContainerConfigs) throw new Error("extractTwContainerConfigs not available");
772
+ return native.extractTwContainerConfigs(source);
773
+ }
774
+ function parseAtomicClass(twClass) {
775
+ const native = getNativeBridge();
776
+ if (!native?.parseAtomicClass) throw new Error("parseAtomicClass not available");
777
+ return native.parseAtomicClass(twClass);
778
+ }
779
+ function generateAtomicCss(rulesJson) {
780
+ const native = getNativeBridge();
781
+ if (!native?.generateAtomicCss) throw new Error("generateAtomicCss not available");
782
+ return native.generateAtomicCss(rulesJson);
783
+ }
784
+ function toAtomicClasses(twClasses) {
785
+ const native = getNativeBridge();
786
+ if (!native?.toAtomicClasses) throw new Error("toAtomicClasses not available");
787
+ return native.toAtomicClasses(twClasses);
788
+ }
789
+ function clearAtomicRegistry() {
790
+ const native = getNativeBridge();
791
+ if (!native?.clearAtomicRegistry) return;
792
+ native.clearAtomicRegistry();
793
+ }
794
+ function atomicRegistrySize() {
795
+ const native = getNativeBridge();
796
+ if (!native?.atomicRegistrySize) return 0;
797
+ return native.atomicRegistrySize();
798
+ }
799
+ var init_compilationNative = __esm({
800
+ "packages/domain/compiler/src/compilationNative.ts"() {
801
+ init_nativeBridge();
802
+ }
803
+ });
804
+
805
+ // packages/domain/compiler/src/cacheNative.ts
806
+ function getCacheStatistics() {
807
+ const native = getNativeBridge();
808
+ if (!native?.get_cache_statistics) throw new Error("get_cache_statistics not available");
809
+ const statsJson = native.get_cache_statistics();
810
+ try {
811
+ return JSON.parse(statsJson);
619
812
  } catch {
620
- return null;
813
+ return {
814
+ parse_cache: { hits: 0, misses: 0, size: 0 },
815
+ resolve_cache: { hits: 0, misses: 0, size: 0 },
816
+ compile_cache: { hits: 0, misses: 0, size: 0 },
817
+ css_gen_cache: { hits: 0, misses: 0, size: 0 },
818
+ overall_hit_rate: 0,
819
+ total_memory_bytes: 0
820
+ };
621
821
  }
622
822
  }
623
- function pollWatchEventsNative(handleId) {
823
+ function clearAllCaches() {
824
+ const native = getNativeBridge();
825
+ if (!native?.clear_all_caches) return;
624
826
  try {
625
- const binding = scannerGetBinding();
626
- if (!binding.pollWatchEvents) return [];
627
- return binding.pollWatchEvents(handleId);
827
+ native.clear_all_caches();
628
828
  } catch {
629
- return [];
630
829
  }
631
830
  }
632
- function stopWatchNative(handleId) {
831
+ function clearParseCache() {
832
+ const native = getNativeBridge();
833
+ if (!native?.clear_parse_cache) return;
633
834
  try {
634
- const binding = scannerGetBinding();
635
- if (!binding.stopWatch) return false;
636
- return binding.stopWatch(handleId);
835
+ native.clear_parse_cache();
637
836
  } catch {
638
- return false;
639
837
  }
640
838
  }
641
- function hasNativeWatchBinding() {
839
+ function clearResolveCache() {
840
+ const native = getNativeBridge();
841
+ if (!native?.clear_resolve_cache) return;
642
842
  try {
643
- const binding = scannerGetBinding();
644
- return !!(binding.startWatch && binding.pollWatchEvents && binding.stopWatch);
843
+ native.clear_resolve_cache();
645
844
  } catch {
646
- return false;
647
845
  }
648
846
  }
649
- var log, isValidScannerBinding, createScannerBridgeLoader, scannerBridgeLoader, scannerGetBinding, resetScannerBridgeCache;
650
- var init_native_bridge = __esm({
651
- "packages/domain/scanner/src/native-bridge.ts"() {
652
- init_src();
653
- log = createDebugLogger("scanner:native");
654
- isValidScannerBinding = (module) => {
655
- const candidate = module;
656
- return !!(candidate && (candidate.scanWorkspace || candidate.extractClassesFromSource || candidate.hashFileContent || candidate.cacheRead || candidate.cacheWrite));
847
+ function clearCompileCache() {
848
+ const native = getNativeBridge();
849
+ if (!native?.clear_compile_cache) return;
850
+ try {
851
+ native.clear_compile_cache();
852
+ } catch {
853
+ }
854
+ }
855
+ function clearCssGenCache() {
856
+ const native = getNativeBridge();
857
+ if (!native?.clear_css_gen_cache) return;
858
+ try {
859
+ native.clear_css_gen_cache();
860
+ } catch {
861
+ }
862
+ }
863
+ function getCacheOptimizationHints(hitRatePercent, memoryUsedMb) {
864
+ const native = getNativeBridge();
865
+ if (!native?.get_cache_optimization_hints)
866
+ throw new Error("get_cache_optimization_hints not available");
867
+ const hintsJson = native.get_cache_optimization_hints(
868
+ Math.min(100, Math.max(0, hitRatePercent)),
869
+ Math.max(1, memoryUsedMb)
870
+ );
871
+ try {
872
+ return JSON.parse(hintsJson);
873
+ } catch {
874
+ return {
875
+ current_strategy: "unknown",
876
+ recommended_strategy: "increase_size",
877
+ estimated_improvement_percent: 0,
878
+ suggested_memory_mb: 256,
879
+ notes: ["Unable to analyze cache statistics"]
657
880
  };
658
- createScannerBridgeLoader = () => {
659
- const _state = {
660
- binding: void 0,
661
- loadError: null,
662
- candidatePaths: []
663
- };
664
- const throwNativeBindingError = () => {
665
- const lines = [
666
- "FATAL: Native scanner binding not found.",
667
- "",
668
- "This package requires the Rust native binding 'tailwind_styled_parser.node'.",
669
- "The binding was not found in any of these paths:",
670
- ..._state.candidatePaths.map((p) => ` - ${p}`),
671
- ""
672
- ];
673
- if (_state.loadError) {
674
- lines.push("Load error:", ` ${_state.loadError}`, "");
675
- }
676
- lines.push(
677
- "To fix this, run:",
678
- " npm run build:rust",
679
- "",
680
- "This will build the native Rust module from the 'native/' directory.",
681
- "If you're using this package in a CI/CD environment, ensure Rust toolchain is installed",
682
- "and 'npm run build:rust' is executed before running tests or building."
683
- );
684
- throw new TwError("rust", "SCANNER_NATIVE_BINDING_NOT_FOUND", lines.join("\n"));
685
- };
686
- const scannerGetBinding2 = () => {
687
- const cachedBinding = _state.binding;
688
- if (cachedBinding !== void 0) {
689
- if (cachedBinding !== null) {
690
- return cachedBinding;
691
- }
692
- return throwNativeBindingError();
693
- }
694
- const runtimeDir = getDirname();
695
- const candidates = resolveNativeBindingCandidates({
696
- runtimeDir,
697
- includeDefaultCandidates: true
698
- });
699
- _state.candidatePaths = candidates;
700
- const { binding, loadErrors } = loadNativeBinding({
701
- runtimeDir,
702
- candidates,
703
- isValid: isValidScannerBinding,
704
- invalidExportMessage: "Module loaded but missing expected scanner binding functions"
705
- });
706
- if (binding) {
707
- log(`scanner native binding loaded successfully`);
708
- _state.binding = binding;
709
- return _state.binding;
710
- }
711
- if (loadErrors.length > 0) {
712
- _state.loadError = loadErrors.map((e) => `${e.path}: ${e.message}`).join("; ");
713
- }
714
- _state.binding = null;
715
- return throwNativeBindingError();
716
- };
717
- return {
718
- get: scannerGetBinding2,
719
- scannerGetBinding: scannerGetBinding2,
720
- reset: () => {
721
- _state.binding = void 0;
722
- _state.loadError = null;
723
- _state.candidatePaths = [];
724
- }
725
- };
881
+ }
882
+ }
883
+ function estimateOptimalCacheConfig(totalBudgetMb, workloadType) {
884
+ const native = getNativeBridge();
885
+ if (!native?.estimate_optimal_cache_config_native)
886
+ throw new Error("estimate_optimal_cache_config_native not available");
887
+ const configJson = native.estimate_optimal_cache_config_native(
888
+ Math.max(64, totalBudgetMb),
889
+ workloadType
890
+ );
891
+ try {
892
+ return JSON.parse(configJson);
893
+ } catch {
894
+ return {
895
+ parse_cache_size: 128,
896
+ resolve_cache_size: 64,
897
+ compile_cache_size: 256,
898
+ css_gen_cache_size: 128,
899
+ recommended_eviction_policy: "lru",
900
+ ttl_seconds: 3600,
901
+ expected_hit_rate_percent: 75
726
902
  };
727
- scannerBridgeLoader = createScannerBridgeLoader();
728
- scannerGetBinding = scannerBridgeLoader.get;
729
- resetScannerBridgeCache = scannerBridgeLoader.reset;
903
+ }
904
+ }
905
+ function cacheRead(cachePath) {
906
+ const native = getNativeBridge();
907
+ if (!native?.cache_read) throw new Error("cache_read not available");
908
+ const result = native.cache_read(cachePath);
909
+ try {
910
+ return JSON.parse(result.entries_json || "[]");
911
+ } catch {
912
+ return [];
913
+ }
914
+ }
915
+ function cacheWrite(cachePath, entries) {
916
+ const native = getNativeBridge();
917
+ if (!native?.cache_write) throw new Error("cache_write not available");
918
+ try {
919
+ const result = native.cache_write(
920
+ cachePath,
921
+ entries.map((e) => ({
922
+ file: e.file,
923
+ content_hash: e.contentHash,
924
+ classes: e.classes,
925
+ mtime_ms: e.mtimeMs,
926
+ size_bytes: e.sizeBytes
927
+ }))
928
+ );
929
+ return typeof result === "boolean" ? result : result === true;
930
+ } catch {
931
+ return false;
932
+ }
933
+ }
934
+ function cachePriority(mtimeMs, sizeBytes, hitCount) {
935
+ const native = getNativeBridge();
936
+ if (!native?.cache_priority) throw new Error("cache_priority not available");
937
+ return native.cache_priority(mtimeMs, sizeBytes, hitCount);
938
+ }
939
+ var init_cacheNative = __esm({
940
+ "packages/domain/compiler/src/cacheNative.ts"() {
941
+ init_nativeBridge();
730
942
  }
731
943
  });
732
944
 
733
- // packages/domain/compiler/src/nativeBridge.ts
734
- var _loadNative, log3, NATIVE_UNAVAILABLE_MESSAGE, nativeBridge, bridgeLoadAttempted, bridgeLoadError, isValidNativeBridge, getNativeBridge, resetNativeBridgeCache, adaptNativeResult;
735
- var init_nativeBridge = __esm({
736
- "packages/domain/compiler/src/nativeBridge.ts"() {
737
- init_src();
738
- _loadNative = (path7) => __require(path7);
739
- log3 = (...args) => {
740
- if (process.env.DEBUG?.includes("compiler:native")) {
741
- console.log("[compiler:native]", ...args);
742
- }
743
- };
744
- NATIVE_UNAVAILABLE_MESSAGE = "[tailwind-styled/compiler v5] Native binding is required but not available.\nThis package requires native Rust bindings. There is no JavaScript fallback.\nPlease ensure:\n 1. The native module is properly installed\n 2. You have run: npm run build:rust (or use prebuilt binary)\n\nFor help, see: https://tailwind-styled.dev/docs/install";
745
- nativeBridge = null;
746
- bridgeLoadAttempted = false;
747
- bridgeLoadError = null;
748
- isValidNativeBridge = (mod) => {
749
- const m = mod;
750
- return !!(typeof m.transformSource === "function" || typeof m.extractAllClasses === "function" || typeof m.hasTwUsage === "function");
751
- };
752
- getNativeBridge = () => {
753
- if (nativeBridge) {
754
- return nativeBridge;
755
- }
756
- if (bridgeLoadAttempted) {
757
- if (bridgeLoadError) {
758
- throw bridgeLoadError;
759
- }
760
- throw new Error(NATIVE_UNAVAILABLE_MESSAGE);
761
- }
762
- bridgeLoadAttempted = true;
763
- try {
764
- const runtimeDir = resolveRuntimeDir(void 0, (typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('next.js', document.baseURI).href)));
765
- const result = resolveNativeBinary(runtimeDir);
766
- if (result.path && result.path.endsWith(".node")) {
767
- try {
768
- const binding = _loadNative(result.path);
769
- if (isValidNativeBridge(binding)) {
770
- nativeBridge = binding;
771
- log3("Native bridge loaded successfully from:", result.path);
772
- return nativeBridge;
773
- }
774
- } catch (e) {
775
- log3("Failed to require native binding:", e);
776
- }
777
- }
778
- throw new Error(`${NATIVE_UNAVAILABLE_MESSAGE}
779
-
780
- Tried paths: ${result.tried.join("\n")}`);
781
- } catch (err) {
782
- bridgeLoadError = err instanceof Error ? err : new Error(String(err));
783
- log3("Failed to load native bridge:", bridgeLoadError.message);
784
- throw bridgeLoadError;
785
- }
945
+ // packages/domain/compiler/src/themeResolutionNative.ts
946
+ function resolveVariants(configJson) {
947
+ const native = getNativeBridge();
948
+ if (!native?.resolve_variants) throw new Error("resolve_variants not available");
949
+ const resultJson = native.resolve_variants(configJson);
950
+ try {
951
+ return JSON.parse(resultJson);
952
+ } catch {
953
+ return {
954
+ variants: [],
955
+ supported: [],
956
+ deprecated: [],
957
+ conflicting: []
786
958
  };
787
- resetNativeBridgeCache = () => {
788
- nativeBridge = null;
789
- bridgeLoadAttempted = false;
790
- bridgeLoadError = null;
791
- log3("Native bridge cache reset");
959
+ }
960
+ }
961
+ function validateThemeConfig(configJson) {
962
+ const native = getNativeBridge();
963
+ if (!native?.validate_variant_config) throw new Error("validate_variant_config not available");
964
+ const resultJson = native.validate_variant_config(configJson);
965
+ try {
966
+ return JSON.parse(resultJson);
967
+ } catch {
968
+ return {
969
+ is_valid: false,
970
+ errors: ["Unable to parse configuration"],
971
+ warnings: [],
972
+ suggestions: []
792
973
  };
793
- adaptNativeResult = (raw) => {
794
- return {
795
- code: raw.code ?? "",
796
- classes: raw.classes ?? [],
797
- changed: raw.changed ?? false,
798
- rsc: raw.rscJson ? JSON.parse(raw.rscJson) : void 0,
799
- metadata: raw.metadataJson ? JSON.parse(raw.metadataJson) : void 0
800
- };
974
+ }
975
+ }
976
+ function resolveCascade(baseThemeJson, overridesJson) {
977
+ const native = getNativeBridge();
978
+ if (!native?.resolve_cascade) throw new Error("resolve_cascade not available");
979
+ const resultJson = native.resolve_cascade(baseThemeJson, overridesJson);
980
+ try {
981
+ return JSON.parse(resultJson);
982
+ } catch {
983
+ return {
984
+ base_theme: {},
985
+ user_overrides: {},
986
+ merged_theme: {},
987
+ conflict_resolutions: []
801
988
  };
802
- if (typeof process !== "undefined" && !bridgeLoadAttempted) {
803
- try {
804
- getNativeBridge();
805
- } catch {
806
- }
807
- }
808
989
  }
809
- });
810
-
811
- // packages/domain/compiler/src/tailwindEngine.ts
812
- var tailwindEngine_exports = {};
813
- __export(tailwindEngine_exports, {
814
- generateRawCss: () => generateRawCss,
815
- processTailwindCssWithTargets: () => processTailwindCssWithTargets,
816
- runCssPipeline: () => runCssPipeline,
817
- runCssPipelineSync: () => runCssPipelineSync
818
- });
819
- function loadTailwindEngine() {
820
- if (_twEngine) return _twEngine;
821
- if (_twEngineError) throw _twEngineError;
990
+ }
991
+ function resolveClassNames(classNames, themeJson) {
992
+ const native = getNativeBridge();
993
+ if (!native?.resolve_class_names) throw new Error("resolve_class_names not available");
994
+ const resultJson = native.resolve_class_names(classNames, themeJson);
822
995
  try {
823
- const tw = require2("tailwindcss");
824
- if (typeof tw.compile !== "function") {
825
- throw new Error("tailwindcss v4 not found \u2014 compile() API missing. Check tailwindcss version >= 4.");
826
- }
827
- _twEngine = tw;
828
- return _twEngine;
829
- } catch (e) {
830
- _twEngineError = e instanceof Error ? e : new Error(String(e));
831
- throw _twEngineError;
996
+ return JSON.parse(resultJson);
997
+ } catch {
998
+ return [];
832
999
  }
833
1000
  }
834
- async function generateRawCss(classes, cssEntryContent, root) {
835
- if (classes.length === 0) return "";
836
- const tw = loadTailwindEngine();
837
- const input = cssEntryContent ?? "@import 'tailwindcss';";
838
- const { readFileSync, existsSync: existsSync3 } = await import('fs');
839
- const { dirname, resolve: resolve2 } = await import('path');
840
- const projectRoot = root ?? process.cwd();
841
- const req = module$1.createRequire(resolve2(projectRoot, "package.json"));
842
- const loadStylesheet = async (id, base) => {
843
- try {
844
- const cssId = id === "tailwindcss" ? "tailwindcss/index.css" : id === "tailwindcss/preflight" ? "tailwindcss/preflight.css" : id === "tailwindcss/utilities" ? "tailwindcss/utilities.css" : id === "tailwindcss/theme" ? "tailwindcss/theme.css" : id;
845
- const pkgPath = req.resolve(cssId);
846
- return {
847
- content: readFileSync(pkgPath, "utf-8"),
848
- base: dirname(pkgPath)
849
- };
850
- } catch {
851
- try {
852
- const absPath = resolve2(base, id);
853
- if (existsSync3(absPath)) {
854
- return { content: readFileSync(absPath, "utf-8"), base: dirname(absPath) };
855
- }
856
- } catch {
857
- }
858
- return { content: "", base };
859
- }
860
- };
861
- const compiler = await Promise.resolve(tw.compile(input, { loadStylesheet }));
862
- return compiler.build(classes);
863
- }
864
- function postProcessWithLightning(rawCss) {
865
- if (!rawCss) return "";
1001
+ function resolveConflictGroup(groupName, themeJson) {
866
1002
  const native = getNativeBridge();
867
- if (typeof native.processTailwindCssLightning !== "function") {
868
- throw new Error("FATAL: Native binding 'processTailwindCssLightning' is required but not available.");
1003
+ if (!native?.resolve_conflict_group)
1004
+ throw new Error("resolve_conflict_group not available");
1005
+ const resultJson = native.resolve_conflict_group(groupName, themeJson);
1006
+ try {
1007
+ return JSON.parse(resultJson);
1008
+ } catch {
1009
+ return {
1010
+ group_name: groupName,
1011
+ conflicting_classes: [],
1012
+ description: "",
1013
+ resolution_strategy: "last-wins"
1014
+ };
869
1015
  }
870
- const result = native.processTailwindCssLightning(rawCss);
871
- return result?.css ?? rawCss;
872
1016
  }
873
- async function runCssPipeline(classes, cssEntryContent, root, minify = true) {
874
- const unique = [...new Set(classes.filter(Boolean))];
875
- if (unique.length === 0) {
876
- return { css: "", classes: [], sizeBytes: 0, optimized: false };
877
- }
878
- const rawCss = await generateRawCss(unique, cssEntryContent, root);
1017
+ function resolveThemeValue(keyPath, themeJson) {
879
1018
  const native = getNativeBridge();
880
- const hasLightning = minify && typeof native.processTailwindCssLightning === "function";
881
- const finalCss = hasLightning ? postProcessWithLightning(rawCss) : rawCss;
882
- return {
883
- css: finalCss,
884
- classes: unique,
885
- sizeBytes: finalCss.length,
886
- optimized: hasLightning
887
- };
888
- }
889
- function runCssPipelineSync(_classes) {
890
- return { css: "", classes: [], sizeBytes: 0, optimized: false };
1019
+ if (!native?.resolve_theme_value) throw new Error("resolve_theme_value not available");
1020
+ return native.resolve_theme_value(keyPath, themeJson);
891
1021
  }
892
- function processTailwindCssWithTargets(css, targets) {
1022
+ function resolveSimpleVariants(configJson) {
893
1023
  const native = getNativeBridge();
894
- if (!native?.processTailwindCssWithTargets) {
895
- throw new Error("FATAL: Native binding 'processTailwindCssWithTargets' is required but not available.");
1024
+ if (!native?.resolve_simple_variants) throw new Error("resolve_simple_variants not available");
1025
+ const resultJson = native.resolve_simple_variants(configJson);
1026
+ try {
1027
+ return JSON.parse(resultJson);
1028
+ } catch {
1029
+ return [];
896
1030
  }
897
- const result = native.processTailwindCssWithTargets(css, targets ?? null);
898
- return (result?.css ?? css).trim();
899
1031
  }
900
- var require2, _twEngine, _twEngineError;
901
- var init_tailwindEngine = __esm({
902
- "packages/domain/compiler/src/tailwindEngine.ts"() {
1032
+ var init_themeResolutionNative = __esm({
1033
+ "packages/domain/compiler/src/themeResolutionNative.ts"() {
903
1034
  init_nativeBridge();
904
- require2 = module$1.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('next.js', document.baseURI).href)));
905
- _twEngine = null;
906
- _twEngineError = null;
907
1035
  }
908
1036
  });
909
1037
 
910
- // packages/domain/compiler/src/index.ts
911
- var src_exports = {};
912
- __export(src_exports, {
913
- BucketEngine: () => BucketEngine,
914
- IncrementalEngine: () => IncrementalEngine,
915
- adaptNativeResult: () => adaptNativeResult,
916
- analyzeClassUsage: () => analyzeClassUsage,
917
- analyzeClasses: () => analyzeClasses,
918
- analyzeFile: () => analyzeFile,
919
- analyzeRsc: () => analyzeRsc,
920
- analyzeVariantUsage: () => analyzeVariantUsage,
921
- astExtractClasses: () => astExtractClasses,
922
- batchExtractClasses: () => batchExtractClasses,
923
- bucketSort: () => bucketSort,
924
- buildStyleTag: () => buildStyleTag,
925
- checkAgainstSafelist: () => checkAgainstSafelist,
926
- classifyAndSortClasses: () => classifyAndSortClasses,
927
- classifyNode: () => classifyNode,
928
- compileCssFromClasses: () => compileCssFromClasses,
929
- compileCssNative: () => compileCssNative,
930
- compileVariantTable: () => compileVariantTable,
931
- compileVariants: () => compileVariants,
932
- detectConflicts: () => detectConflicts,
933
- diffClassLists: () => diffClassLists,
934
- eliminateDeadCss: () => eliminateDeadCss,
935
- extractAllClasses: () => extractAllClasses,
936
- extractClassesFromSource: () => extractClassesFromSource,
937
- extractComponentUsage: () => extractComponentUsage,
938
- fileToRoute: () => fileToRoute,
939
- findDeadVariants: () => findDeadVariants,
940
- generateCssForClasses: () => generateCssForClasses,
941
- generateSafelist: () => generateSafelist,
942
- getAllRoutes: () => getAllRoutes,
943
- getBucketEngine: () => getBucketEngine,
944
- getContentPaths: () => getContentPaths,
945
- getIncrementalEngine: () => getIncrementalEngine,
946
- getNativeBridge: () => getNativeBridge,
947
- getRouteClasses: () => getRouteClasses,
948
- hasTwUsage: () => hasTwUsage,
949
- hoistComponents: () => hoistComponents,
950
- injectClientDirective: () => injectClientDirective,
951
- injectServerOnlyComment: () => injectServerOnlyComment,
952
- isAlreadyTransformed: () => isAlreadyTransformed,
953
- loadSafelist: () => loadSafelist,
954
- loadTailwindConfig: () => loadTailwindConfig,
955
- mergeClassesStatic: () => mergeClassesStatic,
956
- mergeCssDeclarations: () => mergeCssDeclarations,
957
- normalizeAndDedupClasses: () => normalizeAndDedupClasses,
958
- normalizeClasses: () => normalizeClasses,
959
- optimizeCss: () => optimizeCss,
960
- parseClasses: () => parseClasses,
961
- registerFileClasses: () => registerFileClasses,
962
- registerGlobalClasses: () => registerGlobalClasses,
963
- resetBucketEngine: () => resetBucketEngine,
964
- resetIncrementalEngine: () => resetIncrementalEngine,
965
- resetNativeBridgeCache: () => resetNativeBridgeCache,
966
- runElimination: () => runElimination,
967
- runLoaderTransform: () => runLoaderTransform,
968
- scanProjectUsage: () => scanProjectUsage,
969
- shouldProcess: () => shouldProcess,
970
- shouldSkipFile: () => shouldSkipFile,
971
- transformSource: () => transformSource
972
- });
973
- var transformSource, hasTwUsage, isAlreadyTransformed, shouldProcess, compileCssFromClasses, buildStyleTag, compileCssNative, generateCssForClasses, extractAllClasses, extractClassesFromSource, astExtractClasses, parseClasses, normalizeClasses, mergeClassesStatic, normalizeAndDedupClasses, eliminateDeadCss, findDeadVariants, runElimination, optimizeCss, scanProjectUsage, extractComponentUsage, diffClassLists, batchExtractClasses, checkAgainstSafelist, hoistComponents, compileVariantTable, compileVariants, classifyAndSortClasses, mergeCssDeclarations, analyzeClassUsage, analyzeRsc, analyzeFile, analyzeVariantUsage, injectClientDirective, injectServerOnlyComment, analyzeClasses, generateSafelist, loadSafelist, loadTailwindConfig, getContentPaths, runLoaderTransform, shouldSkipFile, fileToRoute, getAllRoutes, getRouteClasses, registerFileClasses, registerGlobalClasses, _incrementalEngineInstance, getIncrementalEngine, resetIncrementalEngine, IncrementalEngine, getBucketEngine, resetBucketEngine, BucketEngine, classifyNode, detectConflicts, bucketSort;
974
- var init_src2 = __esm({
975
- "packages/domain/compiler/src/index.ts"() {
976
- init_nativeBridge();
977
- transformSource = (source, opts) => {
978
- const native = getNativeBridge();
979
- if (!native?.transformSource) {
980
- throw new Error("FATAL: Native binding 'transformSource' is required but not available.");
981
- }
982
- const result = native.transformSource(source, opts);
983
- if (!result) {
984
- throw new Error("FATAL: transformSource returned null");
985
- }
986
- return result;
1038
+ // packages/domain/compiler/src/streamingNative.ts
1039
+ function processFileChange(fileChangeJson) {
1040
+ const native = getNativeBridge();
1041
+ if (!native?.process_file_change) throw new Error("process_file_change not available");
1042
+ const resultJson = native.process_file_change(fileChangeJson);
1043
+ try {
1044
+ return JSON.parse(resultJson);
1045
+ } catch {
1046
+ return {
1047
+ file_path: "",
1048
+ status: "error",
1049
+ old_classes: [],
1050
+ new_classes: [],
1051
+ added_classes: [],
1052
+ removed_classes: [],
1053
+ changed: false,
1054
+ fingerprint: "",
1055
+ error: "Failed to parse result"
987
1056
  };
988
- hasTwUsage = (source) => {
989
- const native = getNativeBridge();
990
- if (!native?.hasTwUsage) {
991
- throw new Error("FATAL: Native binding 'hasTwUsage' is required but not available.");
992
- }
993
- return native.hasTwUsage(source);
1057
+ }
1058
+ }
1059
+ function computeIncrementalDiff(oldScanJson, newScanJson) {
1060
+ const native = getNativeBridge();
1061
+ if (!native?.compute_incremental_diff)
1062
+ throw new Error("compute_incremental_diff not available");
1063
+ const resultJson = native.compute_incremental_diff(oldScanJson, newScanJson);
1064
+ try {
1065
+ return JSON.parse(resultJson);
1066
+ } catch {
1067
+ return {
1068
+ is_changed: false,
1069
+ changes_count: 0,
1070
+ diff: {
1071
+ added_files: [],
1072
+ removed_files: [],
1073
+ modified_files: [],
1074
+ added_classes: [],
1075
+ removed_classes: [],
1076
+ total_changes: 0
1077
+ },
1078
+ processing_time_ms: 0
994
1079
  };
995
- isAlreadyTransformed = (source) => {
996
- const native = getNativeBridge();
997
- if (!native?.isAlreadyTransformed) {
998
- throw new Error("FATAL: Native binding 'isAlreadyTransformed' is required but not available.");
999
- }
1000
- return native.isAlreadyTransformed(source);
1080
+ }
1081
+ }
1082
+ function createFingerprint(filePath, fileContent) {
1083
+ const native = getNativeBridge();
1084
+ if (!native?.create_fingerprint) throw new Error("create_fingerprint not available");
1085
+ const fingerprintJson = native.create_fingerprint(filePath, fileContent);
1086
+ try {
1087
+ return JSON.parse(fingerprintJson);
1088
+ } catch {
1089
+ return {
1090
+ file_path: filePath,
1091
+ content_hash: "",
1092
+ size_bytes: fileContent.length,
1093
+ mtime_ms: Date.now(),
1094
+ class_hash: "",
1095
+ signature: ""
1001
1096
  };
1002
- shouldProcess = (source) => {
1003
- return hasTwUsage(source) && !isAlreadyTransformed(source);
1097
+ }
1098
+ }
1099
+ function injectStateHash(css, stateHash) {
1100
+ const native = getNativeBridge();
1101
+ if (!native?.inject_state_hash) throw new Error("inject_state_hash not available");
1102
+ const resultJson = native.inject_state_hash(css, stateHash);
1103
+ try {
1104
+ return JSON.parse(resultJson);
1105
+ } catch {
1106
+ return {
1107
+ injected: false,
1108
+ state_hash: stateHash,
1109
+ affected_files: 0,
1110
+ total_injected_bytes: 0
1004
1111
  };
1005
- compileCssFromClasses = (classes, prefix) => {
1006
- const native = getNativeBridge();
1007
- if (!native?.transformSource) {
1008
- throw new Error("FATAL: Native binding 'transformSource' is required but not available.");
1009
- }
1010
- const result = native.transformSource(classes.join(" "), { prefix: prefix ?? "" });
1011
- if (!result) {
1012
- throw new Error("FATAL: transformSource returned null");
1013
- }
1014
- return result;
1112
+ }
1113
+ }
1114
+ function pruneStaleCacheEntries(maxAgeSeconds, maxEntries) {
1115
+ const native = getNativeBridge();
1116
+ if (!native?.prune_stale_entries) throw new Error("prune_stale_entries not available");
1117
+ const resultJson = native.prune_stale_entries(maxAgeSeconds, maxEntries);
1118
+ try {
1119
+ return JSON.parse(resultJson);
1120
+ } catch {
1121
+ return {
1122
+ entries_before: 0,
1123
+ entries_after: 0,
1124
+ entries_removed: 0,
1125
+ freed_bytes: 0
1015
1126
  };
1016
- buildStyleTag = (classes) => {
1017
- const result = compileCssFromClasses(classes);
1018
- return result?.code ? `<style data-tailwind-styled>${result.code}</style>` : "";
1127
+ }
1128
+ }
1129
+ function rebuildWorkspaceResult(rootDir, extensions) {
1130
+ const native = getNativeBridge();
1131
+ if (!native?.rebuild_workspace_result)
1132
+ throw new Error("rebuild_workspace_result not available");
1133
+ const resultJson = native.rebuild_workspace_result(rootDir, extensions || []);
1134
+ try {
1135
+ return JSON.parse(resultJson);
1136
+ } catch {
1137
+ return {
1138
+ total_files_scanned: 0,
1139
+ total_classes_found: 0,
1140
+ unique_classes: 0,
1141
+ build_time_ms: 0,
1142
+ files_with_changes: 0
1019
1143
  };
1020
- compileCssNative = (classes, prefix = null) => {
1021
- return compileCssFromClasses(classes, prefix);
1144
+ }
1145
+ }
1146
+ function scanFileNative(filePath, fileContent) {
1147
+ const native = getNativeBridge();
1148
+ if (!native?.scan_file_native) throw new Error("scan_file_native not available");
1149
+ const resultJson = native.scan_file_native(filePath, fileContent);
1150
+ try {
1151
+ return JSON.parse(resultJson);
1152
+ } catch {
1153
+ return {
1154
+ file: filePath,
1155
+ classes: [],
1156
+ added_classes: [],
1157
+ removed_classes: [],
1158
+ changed: false
1022
1159
  };
1023
- generateCssForClasses = async (classes, _tailwindConfig, root, cssEntryContent, minify = false) => {
1024
- const { runCssPipeline: runCssPipeline2 } = await Promise.resolve().then(() => (init_tailwindEngine(), tailwindEngine_exports));
1025
- const result = await runCssPipeline2(classes, cssEntryContent, root, minify);
1026
- return result.css;
1160
+ }
1161
+ }
1162
+ function scanFilesBatchNative(filesJson) {
1163
+ const native = getNativeBridge();
1164
+ if (!native?.scan_files_batch_native)
1165
+ throw new Error("scan_files_batch_native not available");
1166
+ const resultJson = native.scan_files_batch_native(filesJson);
1167
+ try {
1168
+ return JSON.parse(resultJson);
1169
+ } catch {
1170
+ return [];
1171
+ }
1172
+ }
1173
+ var init_streamingNative = __esm({
1174
+ "packages/domain/compiler/src/streamingNative.ts"() {
1175
+ init_nativeBridge();
1176
+ }
1177
+ });
1178
+
1179
+ // packages/domain/compiler/src/cssCompilationNative.ts
1180
+ function compileClass(input) {
1181
+ const native = getNativeBridge();
1182
+ if (!native?.compile_class) throw new Error("compile_class not available");
1183
+ const resultJson = native.compile_class(input);
1184
+ try {
1185
+ return JSON.parse(resultJson);
1186
+ } catch {
1187
+ return {
1188
+ selector: "",
1189
+ declarations: "",
1190
+ properties: [],
1191
+ specificity: 0
1027
1192
  };
1028
- extractAllClasses = (source) => {
1029
- const native = getNativeBridge();
1030
- if (!native?.extractAllClasses) {
1031
- throw new Error("FATAL: Native binding 'extractAllClasses' is required but not available.");
1032
- }
1033
- return native.extractAllClasses(source) || [];
1193
+ }
1194
+ }
1195
+ function compileClasses(inputs) {
1196
+ const native = getNativeBridge();
1197
+ if (!native?.compile_classes) throw new Error("compile_classes not available");
1198
+ const resultJson = native.compile_classes(inputs);
1199
+ try {
1200
+ return JSON.parse(resultJson);
1201
+ } catch {
1202
+ return {
1203
+ css: "",
1204
+ resolved_classes: [],
1205
+ unknown_classes: [],
1206
+ size_bytes: 0,
1207
+ duration_ms: 0
1034
1208
  };
1035
- extractClassesFromSource = (source) => {
1036
- const native = getNativeBridge();
1037
- if (!native?.extractClassesFromSource) {
1038
- throw new Error("FATAL: Native binding 'extractClassesFromSource' is required but not available.");
1039
- }
1040
- const result = native.extractClassesFromSource(source);
1041
- return Array.isArray(result) ? result.join(" ") : String(result || "");
1042
- };
1043
- astExtractClasses = (source, filename) => {
1044
- const native = getNativeBridge();
1045
- if (!native?.extractClassesFromSource) {
1046
- throw new Error("FATAL: Native binding 'extractClassesFromSource' is required but not available.");
1047
- }
1048
- return native.extractClassesFromSource(source) || [];
1049
- };
1050
- parseClasses = (raw) => {
1051
- const native = getNativeBridge();
1052
- if (!native?.parseClasses) {
1053
- throw new Error("FATAL: Native binding 'parseClasses' is required but not available.");
1054
- }
1055
- return native.parseClasses(raw) || [];
1056
- };
1057
- normalizeClasses = (raw) => {
1058
- const result = normalizeAndDedupClasses(raw);
1059
- return result?.normalized || "";
1060
- };
1061
- mergeClassesStatic = (classes) => {
1062
- const result = normalizeAndDedupClasses(classes);
1063
- return result?.normalized || "";
1064
- };
1065
- normalizeAndDedupClasses = (raw) => {
1066
- const native = getNativeBridge();
1067
- if (!native?.normalizeAndDedupClasses) {
1068
- throw new Error("FATAL: Native binding 'normalizeAndDedupClasses' is required but not available.");
1069
- }
1070
- const result = native.normalizeAndDedupClasses(raw);
1071
- return result || { normalized: "", duplicatesRemoved: 0, uniqueCount: 0 };
1072
- };
1073
- eliminateDeadCss = (css, deadClasses) => {
1074
- const native = getNativeBridge();
1075
- if (!native?.processTailwindCssLightning) {
1076
- throw new Error("FATAL: Native binding 'processTailwindCssLightning' is required but not available.");
1077
- }
1078
- const deadSet = deadClasses;
1079
- const pruned = css.split(/(?<=\})\s*/).filter((rule) => {
1080
- const m = rule.match(/\.([a-zA-Z0-9_-]+)/);
1081
- return !m || !deadSet.has(m[1]);
1082
- }).join("\n");
1083
- const compiled = native.processTailwindCssLightning(pruned);
1084
- return (compiled?.css ?? pruned).trim();
1085
- };
1086
- findDeadVariants = (variantConfig, usage) => {
1087
- const unused = [];
1088
- const configs = Array.isArray(variantConfig) ? variantConfig : [{ name: "__root__", variants: variantConfig }];
1089
- for (const component of configs) {
1090
- const componentUsage = usage[component.name] ?? /* @__PURE__ */ new Set();
1091
- const variants = component.variants;
1092
- for (const [key, values] of Object.entries(variants)) {
1093
- for (const [value] of Object.entries(values)) {
1094
- if (!componentUsage.has(`${key}:${value}`)) {
1095
- unused.push(`${component.name !== "__root__" ? `${component.name}/` : ""}${key}:${value}`);
1096
- }
1097
- }
1098
- }
1099
- }
1100
- return {
1101
- unusedCount: unused.length,
1102
- unused
1103
- };
1104
- };
1105
- runElimination = (css, scanResult) => {
1106
- const native = getNativeBridge();
1107
- if (!native?.detectDeadCode) {
1108
- throw new Error("FATAL: Native binding 'detectDeadCode' is required but not available.");
1109
- }
1110
- const dead = native.detectDeadCode(
1111
- JSON.stringify(scanResult),
1112
- css
1113
- );
1114
- return eliminateDeadCss(css, new Set(dead.deadInCss ?? []));
1209
+ }
1210
+ }
1211
+ function compileToCss(input, minify) {
1212
+ const native = getNativeBridge();
1213
+ if (!native?.compile_to_css) throw new Error("compile_to_css not available");
1214
+ return native.compile_to_css(input, minify ?? false);
1215
+ }
1216
+ function compileToCssBatch(inputs, minify) {
1217
+ const native = getNativeBridge();
1218
+ if (!native?.compile_to_css_batch) throw new Error("compile_to_css_batch not available");
1219
+ return native.compile_to_css_batch(inputs, minify ?? false);
1220
+ }
1221
+ function minifyCss(css) {
1222
+ const native = getNativeBridge();
1223
+ if (!native?.minify_css) throw new Error("minify_css not available");
1224
+ return native.minify_css(css);
1225
+ }
1226
+ function compileAnimation(animationName, from, to) {
1227
+ const native = getNativeBridge();
1228
+ if (!native?.compile_animation) throw new Error("compile_animation not available");
1229
+ const resultJson = native.compile_animation(animationName, from, to);
1230
+ try {
1231
+ return JSON.parse(resultJson);
1232
+ } catch {
1233
+ return {
1234
+ animation_id: "",
1235
+ keyframes_css: "",
1236
+ animation_rule: "",
1237
+ duration_ms: 0
1115
1238
  };
1116
- optimizeCss = (css) => {
1117
- const native = getNativeBridge();
1118
- if (!native?.detectDeadCode) {
1119
- throw new Error("FATAL: Native binding 'detectDeadCode' is required but not available.");
1120
- }
1121
- const deadResult = native.detectDeadCode(
1122
- JSON.stringify({ uniqueClasses: [] }),
1123
- css
1124
- );
1125
- if (!native?.processTailwindCssLightning) {
1126
- throw new Error("FATAL: Native binding 'processTailwindCssLightning' is required but not available.");
1127
- }
1128
- const deadSet = new Set(deadResult.deadInCss ?? []);
1129
- const pruned = css.split(/(?<=\})\s*/).filter((rule) => {
1130
- const selectorMatch = rule.match(/\.([a-zA-Z0-9_-]+)/);
1131
- if (!selectorMatch) return true;
1132
- return !deadSet.has(selectorMatch[1]);
1133
- }).join("\n");
1134
- const compiled = native.processTailwindCssLightning(pruned);
1135
- return (compiled?.css ?? pruned).trim();
1239
+ }
1240
+ }
1241
+ function compileKeyframes(name, stopsJson) {
1242
+ const native = getNativeBridge();
1243
+ if (!native?.compile_keyframes) throw new Error("compile_keyframes not available");
1244
+ const resultJson = native.compile_keyframes(name, stopsJson);
1245
+ try {
1246
+ return JSON.parse(resultJson);
1247
+ } catch {
1248
+ return {
1249
+ animation_id: "",
1250
+ keyframes_css: "",
1251
+ animation_rule: "",
1252
+ duration_ms: 0
1136
1253
  };
1137
- scanProjectUsage = (dirs, cwd) => {
1138
- const path7 = __require("path");
1139
- const files = dirs.map((dir) => path7.resolve(cwd, dir));
1140
- const results = batchExtractClasses(files) || [];
1141
- const combined = {};
1142
- for (const result of results) {
1143
- if (result.ok && result.classes) {
1144
- for (const cls of result.classes) {
1145
- if (!combined[cls]) combined[cls] = {};
1146
- combined[cls][result.file] = /* @__PURE__ */ new Set([cls]);
1147
- }
1148
- }
1149
- }
1150
- return combined;
1254
+ }
1255
+ }
1256
+ function compileTheme(tokensJson, themeName, prefix) {
1257
+ const native = getNativeBridge();
1258
+ if (!native?.compile_theme) throw new Error("compile_theme not available");
1259
+ const resultJson = native.compile_theme(tokensJson, themeName, prefix);
1260
+ try {
1261
+ return JSON.parse(resultJson);
1262
+ } catch {
1263
+ return {
1264
+ selector: ":root",
1265
+ variables: [],
1266
+ variables_css: "",
1267
+ theme_name: themeName
1151
1268
  };
1152
- extractComponentUsage = (source) => {
1153
- const native = getNativeBridge();
1154
- if (!native?.extractComponentUsage) {
1155
- throw new Error("FATAL: Native binding 'extractComponentUsage' is required but not available.");
1156
- }
1157
- return native.extractComponentUsage(source) || [];
1269
+ }
1270
+ }
1271
+ function twMerge(classString) {
1272
+ const native = getNativeBridge();
1273
+ if (!native?.tw_merge) throw new Error("tw_merge not available");
1274
+ return native.tw_merge(classString);
1275
+ }
1276
+ function twMergeMany(classStrings) {
1277
+ const native = getNativeBridge();
1278
+ if (!native?.tw_merge_many) throw new Error("tw_merge_many not available");
1279
+ return native.tw_merge_many(classStrings);
1280
+ }
1281
+ function twMergeWithSeparator(classString, options) {
1282
+ const native = getNativeBridge();
1283
+ if (!native?.tw_merge_with_separator)
1284
+ throw new Error("tw_merge_with_separator not available");
1285
+ const opts = {
1286
+ separator: options.separator,
1287
+ debug: options.debug
1288
+ };
1289
+ return native.tw_merge_with_separator(classString, opts);
1290
+ }
1291
+ function twMergeManyWithSeparator(classStrings, options) {
1292
+ const native = getNativeBridge();
1293
+ if (!native?.tw_merge_many_with_separator)
1294
+ throw new Error("tw_merge_many_with_separator not available");
1295
+ const opts = {
1296
+ separator: options.separator,
1297
+ debug: options.debug
1298
+ };
1299
+ return native.tw_merge_many_with_separator(classStrings, opts);
1300
+ }
1301
+ function twMergeRaw(classLists) {
1302
+ const native = getNativeBridge();
1303
+ if (!native?.tw_merge_raw) throw new Error("tw_merge_raw not available");
1304
+ return native.tw_merge_raw(classLists);
1305
+ }
1306
+ var init_cssCompilationNative = __esm({
1307
+ "packages/domain/compiler/src/cssCompilationNative.ts"() {
1308
+ init_nativeBridge();
1309
+ }
1310
+ });
1311
+
1312
+ // packages/domain/compiler/src/idRegistryNative.ts
1313
+ function idRegistryCreate() {
1314
+ const native = getNativeBridge();
1315
+ if (!native?.id_registry_create) throw new Error("id_registry_create not available");
1316
+ return native.id_registry_create();
1317
+ }
1318
+ function idRegistryGenerate(handle, name) {
1319
+ const native = getNativeBridge();
1320
+ if (!native?.id_registry_generate) throw new Error("id_registry_generate not available");
1321
+ return native.id_registry_generate(handle, name);
1322
+ }
1323
+ function idRegistryLookup(handle, name) {
1324
+ const native = getNativeBridge();
1325
+ if (!native?.id_registry_lookup) throw new Error("id_registry_lookup not available");
1326
+ return native.id_registry_lookup(handle, name);
1327
+ }
1328
+ function idRegistryNext(handle) {
1329
+ const native = getNativeBridge();
1330
+ if (!native?.id_registry_next) throw new Error("id_registry_next not available");
1331
+ return native.id_registry_next(handle);
1332
+ }
1333
+ function idRegistryDestroy(handle) {
1334
+ const native = getNativeBridge();
1335
+ if (!native?.id_registry_destroy) return;
1336
+ native.id_registry_destroy(handle);
1337
+ }
1338
+ function idRegistryReset(handle) {
1339
+ const native = getNativeBridge();
1340
+ if (!native?.id_registry_reset) return;
1341
+ native.id_registry_reset(handle);
1342
+ }
1343
+ function idRegistrySnapshot(handle) {
1344
+ const native = getNativeBridge();
1345
+ if (!native?.id_registry_snapshot) throw new Error("id_registry_snapshot not available");
1346
+ const snapshotJson = native.id_registry_snapshot(handle);
1347
+ try {
1348
+ return JSON.parse(snapshotJson);
1349
+ } catch {
1350
+ return {
1351
+ handle,
1352
+ next_id: 0,
1353
+ entries: [],
1354
+ total_entries: 0
1158
1355
  };
1159
- diffClassLists = (previous, current) => {
1160
- const native = getNativeBridge();
1161
- if (!native?.diffClassLists) {
1162
- throw new Error("FATAL: Native binding 'diffClassLists' is required but not available.");
1163
- }
1164
- return native.diffClassLists(previous, current) || { added: [], removed: [], unchanged: [], hasChanges: false };
1356
+ }
1357
+ }
1358
+ function idRegistryActiveCount() {
1359
+ const native = getNativeBridge();
1360
+ if (!native?.id_registry_active_count) throw new Error("id_registry_active_count not available");
1361
+ return native.id_registry_active_count();
1362
+ }
1363
+ function registerPropertyName(propertyName) {
1364
+ const native = getNativeBridge();
1365
+ if (!native?.register_property_name)
1366
+ throw new Error("register_property_name not available");
1367
+ return native.register_property_name(propertyName);
1368
+ }
1369
+ function registerValueName(valueName) {
1370
+ const native = getNativeBridge();
1371
+ if (!native?.register_value_name) throw new Error("register_value_name not available");
1372
+ return native.register_value_name(valueName);
1373
+ }
1374
+ function propertyIdToString(propertyId) {
1375
+ const native = getNativeBridge();
1376
+ if (!native?.property_id_to_string) throw new Error("property_id_to_string not available");
1377
+ return native.property_id_to_string(propertyId);
1378
+ }
1379
+ function valueIdToString(valueId) {
1380
+ const native = getNativeBridge();
1381
+ if (!native?.value_id_to_string) throw new Error("value_id_to_string not available");
1382
+ return native.value_id_to_string(valueId);
1383
+ }
1384
+ function reverseLookupProperty(propertyId) {
1385
+ const native = getNativeBridge();
1386
+ if (!native?.reverse_lookup_property)
1387
+ throw new Error("reverse_lookup_property not available");
1388
+ return native.reverse_lookup_property(propertyId);
1389
+ }
1390
+ function reverseLookupValue(valueId) {
1391
+ const native = getNativeBridge();
1392
+ if (!native?.reverse_lookup_value) throw new Error("reverse_lookup_value not available");
1393
+ return native.reverse_lookup_value(valueId);
1394
+ }
1395
+ function idRegistryExport(handle) {
1396
+ const native = getNativeBridge();
1397
+ if (!native?.id_registry_export) throw new Error("id_registry_export not available");
1398
+ return native.id_registry_export(handle);
1399
+ }
1400
+ function idRegistryImport(importedData) {
1401
+ const native = getNativeBridge();
1402
+ if (!native?.id_registry_import) throw new Error("id_registry_import not available");
1403
+ return native.id_registry_import(importedData);
1404
+ }
1405
+ var init_idRegistryNative = __esm({
1406
+ "packages/domain/compiler/src/idRegistryNative.ts"() {
1407
+ init_nativeBridge();
1408
+ }
1409
+ });
1410
+
1411
+ // packages/domain/compiler/src/redisNative.ts
1412
+ function redisPing() {
1413
+ const native = getNativeBridge();
1414
+ if (!native?.redis_ping) throw new Error("redis_ping not available");
1415
+ return native.redis_ping();
1416
+ }
1417
+ function redisGet(key) {
1418
+ const native = getNativeBridge();
1419
+ if (!native?.redis_get) throw new Error("redis_get not available");
1420
+ const result = native.redis_get(key);
1421
+ return result === "nil" ? null : result;
1422
+ }
1423
+ function redisSet(key, value, ttl_seconds) {
1424
+ const native = getNativeBridge();
1425
+ if (!native?.redis_set) throw new Error("redis_set not available");
1426
+ return native.redis_set(key, value, ttl_seconds);
1427
+ }
1428
+ function redisDelete(key) {
1429
+ const native = getNativeBridge();
1430
+ if (!native?.redis_delete) throw new Error("redis_delete not available");
1431
+ return native.redis_delete(key);
1432
+ }
1433
+ function redisExists(key) {
1434
+ const native = getNativeBridge();
1435
+ if (!native?.redis_exists) throw new Error("redis_exists not available");
1436
+ return native.redis_exists(key);
1437
+ }
1438
+ function redisMget(keys) {
1439
+ const native = getNativeBridge();
1440
+ if (!native?.redis_mget) throw new Error("redis_mget not available");
1441
+ const result = native.redis_mget(keys);
1442
+ try {
1443
+ return JSON.parse(result);
1444
+ } catch {
1445
+ return keys.map(() => null);
1446
+ }
1447
+ }
1448
+ function redisMset(pairs) {
1449
+ const native = getNativeBridge();
1450
+ if (!native?.redis_mset) throw new Error("redis_mset not available");
1451
+ return native.redis_mset(pairs);
1452
+ }
1453
+ function redisFlushDb() {
1454
+ const native = getNativeBridge();
1455
+ if (!native?.redis_flush_db) throw new Error("redis_flush_db not available");
1456
+ return native.redis_flush_db();
1457
+ }
1458
+ function redisFlushAll() {
1459
+ const native = getNativeBridge();
1460
+ if (!native?.redis_flush_all) throw new Error("redis_flush_all not available");
1461
+ return native.redis_flush_all();
1462
+ }
1463
+ function redisPoolConnect(host, port, pool_size) {
1464
+ const native = getNativeBridge();
1465
+ if (!native?.redis_pool_connect) throw new Error("redis_pool_connect not available");
1466
+ return native.redis_pool_connect(host, port, pool_size);
1467
+ }
1468
+ function redisPoolStats() {
1469
+ const native = getNativeBridge();
1470
+ if (!native?.redis_pool_stats) throw new Error("redis_pool_stats not available");
1471
+ const result = native.redis_pool_stats();
1472
+ try {
1473
+ return JSON.parse(result);
1474
+ } catch {
1475
+ return {
1476
+ connected_count: 0,
1477
+ idle_count: 0,
1478
+ waiting_count: 0,
1479
+ total_requests: 0,
1480
+ total_errors: 0
1165
1481
  };
1166
- batchExtractClasses = (filePaths) => {
1167
- const native = getNativeBridge();
1168
- if (!native?.batchExtractClasses) {
1169
- throw new Error("FATAL: Native binding 'batchExtractClasses' is required but not available.");
1170
- }
1171
- return native.batchExtractClasses(filePaths) || [];
1482
+ }
1483
+ }
1484
+ function redisPoolReconnect() {
1485
+ const native = getNativeBridge();
1486
+ if (!native?.redis_pool_reconnect) throw new Error("redis_pool_reconnect not available");
1487
+ return native.redis_pool_reconnect();
1488
+ }
1489
+ function redisEnableCluster(initial_nodes) {
1490
+ const native = getNativeBridge();
1491
+ if (!native?.redis_enable_cluster) throw new Error("redis_enable_cluster not available");
1492
+ const result = native.redis_enable_cluster(initial_nodes);
1493
+ try {
1494
+ return JSON.parse(result);
1495
+ } catch {
1496
+ return {
1497
+ enabled: false,
1498
+ cluster_state: "error",
1499
+ nodes: [],
1500
+ slots_assigned: 0,
1501
+ slots_ok: 0,
1502
+ slots_fail: 0
1172
1503
  };
1173
- checkAgainstSafelist = (classes, safelist) => {
1174
- const native = getNativeBridge();
1175
- if (!native?.checkAgainstSafelist) {
1176
- throw new Error("FATAL: Native binding 'checkAgainstSafelist' is required but not available.");
1177
- }
1178
- return native.checkAgainstSafelist(classes, safelist) || { matched: [], unmatched: [], safelistSize: 0 };
1504
+ }
1505
+ }
1506
+ function redisDisableCluster() {
1507
+ const native = getNativeBridge();
1508
+ if (!native?.redis_disable_cluster) throw new Error("redis_disable_cluster not available");
1509
+ return native.redis_disable_cluster();
1510
+ }
1511
+ function redisClusterStatus() {
1512
+ const native = getNativeBridge();
1513
+ if (!native?.redis_cluster_status) throw new Error("redis_cluster_status not available");
1514
+ const result = native.redis_cluster_status();
1515
+ try {
1516
+ return JSON.parse(result);
1517
+ } catch {
1518
+ return {
1519
+ enabled: false,
1520
+ cluster_state: "unknown",
1521
+ nodes: [],
1522
+ slots_assigned: 0,
1523
+ slots_ok: 0,
1524
+ slots_fail: 0
1179
1525
  };
1180
- hoistComponents = (source) => {
1181
- const native = getNativeBridge();
1182
- if (!native?.hoistComponents) {
1183
- throw new Error("FATAL: Native binding 'hoistComponents' is required but not available.");
1184
- }
1185
- return native.hoistComponents(source) || { code: source, hoisted: [], warnings: [] };
1526
+ }
1527
+ }
1528
+ function redisSubscribe(channel) {
1529
+ const native = getNativeBridge();
1530
+ if (!native?.redis_subscribe) throw new Error("redis_subscribe not available");
1531
+ return native.redis_subscribe(channel);
1532
+ }
1533
+ function redisPublish(channel, message) {
1534
+ const native = getNativeBridge();
1535
+ if (!native?.redis_publish) throw new Error("redis_publish not available");
1536
+ return native.redis_publish(channel, message);
1537
+ }
1538
+ function redisExpirationSet(key, ttl_seconds) {
1539
+ const native = getNativeBridge();
1540
+ if (!native?.redis_expiration_set) throw new Error("redis_expiration_set not available");
1541
+ return native.redis_expiration_set(key, ttl_seconds);
1542
+ }
1543
+ function redisExpirationGet(key) {
1544
+ const native = getNativeBridge();
1545
+ if (!native?.redis_expiration_get) throw new Error("redis_expiration_get not available");
1546
+ const result = native.redis_expiration_get(key);
1547
+ try {
1548
+ return JSON.parse(result);
1549
+ } catch {
1550
+ return {
1551
+ key,
1552
+ ttl_seconds: -1,
1553
+ expiration_timestamp: 0,
1554
+ is_persistent: true
1186
1555
  };
1187
- compileVariantTable = (configJson) => {
1188
- const native = getNativeBridge();
1189
- if (!native?.compileVariantTable) {
1190
- throw new Error("FATAL: Native binding 'compileVariantTable' is required but not available.");
1556
+ }
1557
+ }
1558
+ function redisInfo() {
1559
+ const native = getNativeBridge();
1560
+ if (!native?.redis_info) throw new Error("redis_info not available");
1561
+ return native.redis_info();
1562
+ }
1563
+ function redisMonitor() {
1564
+ const native = getNativeBridge();
1565
+ if (!native?.redis_monitor) throw new Error("redis_monitor not available");
1566
+ return native.redis_monitor();
1567
+ }
1568
+ function redisCacheSize() {
1569
+ const native = getNativeBridge();
1570
+ if (!native?.redis_cache_size) throw new Error("redis_cache_size not available");
1571
+ return native.redis_cache_size();
1572
+ }
1573
+ function redisCacheKeyCount() {
1574
+ const native = getNativeBridge();
1575
+ if (!native?.redis_cache_key_count) throw new Error("redis_cache_key_count not available");
1576
+ return native.redis_cache_key_count();
1577
+ }
1578
+ function redisCacheClear() {
1579
+ const native = getNativeBridge();
1580
+ if (!native?.redis_cache_clear) throw new Error("redis_cache_clear not available");
1581
+ return native.redis_cache_clear();
1582
+ }
1583
+ function redisCacheHitRate() {
1584
+ const native = getNativeBridge();
1585
+ if (!native?.redis_cache_hit_rate) throw new Error("redis_cache_hit_rate not available");
1586
+ return native.redis_cache_hit_rate();
1587
+ }
1588
+ function redisEnablePersistence(mode) {
1589
+ const native = getNativeBridge();
1590
+ if (!native?.redis_enable_persistence) throw new Error("redis_enable_persistence not available");
1591
+ return native.redis_enable_persistence(mode);
1592
+ }
1593
+ function redisDisablePersistence() {
1594
+ const native = getNativeBridge();
1595
+ if (!native?.redis_disable_persistence) throw new Error("redis_disable_persistence not available");
1596
+ return native.redis_disable_persistence();
1597
+ }
1598
+ function redisSnapshot() {
1599
+ const native = getNativeBridge();
1600
+ if (!native?.redis_snapshot) throw new Error("redis_snapshot not available");
1601
+ return native.redis_snapshot();
1602
+ }
1603
+ function redisMemoryStats() {
1604
+ const native = getNativeBridge();
1605
+ if (!native?.redis_memory_stats) throw new Error("redis_memory_stats not available");
1606
+ return native.redis_memory_stats();
1607
+ }
1608
+ function redisOptimizeMemory() {
1609
+ const native = getNativeBridge();
1610
+ if (!native?.redis_optimize_memory) throw new Error("redis_optimize_memory not available");
1611
+ return native.redis_optimize_memory();
1612
+ }
1613
+ function redisSetEvictionPolicy(policy) {
1614
+ const native = getNativeBridge();
1615
+ if (!native?.redis_set_eviction_policy) throw new Error("redis_set_eviction_policy not available");
1616
+ return native.redis_set_eviction_policy(policy);
1617
+ }
1618
+ function redisGetEvictionPolicy() {
1619
+ const native = getNativeBridge();
1620
+ if (!native?.redis_get_eviction_policy) throw new Error("redis_get_eviction_policy not available");
1621
+ return native.redis_get_eviction_policy();
1622
+ }
1623
+ function redisReplicate(target_host, target_port) {
1624
+ const native = getNativeBridge();
1625
+ if (!native?.redis_replicate) throw new Error("redis_replicate not available");
1626
+ return native.redis_replicate(target_host, target_port);
1627
+ }
1628
+ function redisReplicationStatus() {
1629
+ const native = getNativeBridge();
1630
+ if (!native?.redis_replication_status) throw new Error("redis_replication_status not available");
1631
+ return native.redis_replication_status();
1632
+ }
1633
+ function redisCacheSync(peers) {
1634
+ const native = getNativeBridge();
1635
+ if (!native?.redis_cache_sync) throw new Error("redis_cache_sync not available");
1636
+ return native.redis_cache_sync(peers);
1637
+ }
1638
+ function redisEnableCacheWarming(key_pattern) {
1639
+ const native = getNativeBridge();
1640
+ if (!native?.redis_enable_cache_warming) throw new Error("redis_enable_cache_warming not available");
1641
+ return native.redis_enable_cache_warming(key_pattern);
1642
+ }
1643
+ function redisDisableCacheWarming() {
1644
+ const native = getNativeBridge();
1645
+ if (!native?.redis_disable_cache_warming) throw new Error("redis_disable_cache_warming not available");
1646
+ return native.redis_disable_cache_warming();
1647
+ }
1648
+ function redisDiagnose() {
1649
+ const native = getNativeBridge();
1650
+ if (!native?.redis_diagnose) throw new Error("redis_diagnose not available");
1651
+ return native.redis_diagnose();
1652
+ }
1653
+ var init_redisNative = __esm({
1654
+ "packages/domain/compiler/src/redisNative.ts"() {
1655
+ init_nativeBridge();
1656
+ }
1657
+ });
1658
+
1659
+ // packages/domain/compiler/src/watchSystemNative.ts
1660
+ function startWatch(root_path, patterns) {
1661
+ const native = getNativeBridge();
1662
+ if (!native?.start_watch) throw new Error("start_watch not available");
1663
+ return native.start_watch(root_path, patterns);
1664
+ }
1665
+ function pollWatchEvents(handle, timeout_ms) {
1666
+ const native = getNativeBridge();
1667
+ if (!native?.poll_watch_events) throw new Error("poll_watch_events not available");
1668
+ const result = native.poll_watch_events(handle, timeout_ms);
1669
+ try {
1670
+ return JSON.parse(result);
1671
+ } catch {
1672
+ return [];
1673
+ }
1674
+ }
1675
+ function stopWatch(handle) {
1676
+ const native = getNativeBridge();
1677
+ if (!native?.stop_watch) throw new Error("stop_watch not available");
1678
+ return native.stop_watch(handle);
1679
+ }
1680
+ function watchAddPattern(handle, pattern) {
1681
+ const native = getNativeBridge();
1682
+ if (!native?.watch_add_pattern) throw new Error("watch_add_pattern not available");
1683
+ return native.watch_add_pattern(handle, pattern);
1684
+ }
1685
+ function watchRemovePattern(handle, pattern) {
1686
+ const native = getNativeBridge();
1687
+ if (!native?.watch_remove_pattern) throw new Error("watch_remove_pattern not available");
1688
+ return native.watch_remove_pattern(handle, pattern);
1689
+ }
1690
+ function watchGetActiveHandles() {
1691
+ const native = getNativeBridge();
1692
+ if (!native?.watch_get_active_handles) throw new Error("watch_get_active_handles not available");
1693
+ const result = native.watch_get_active_handles();
1694
+ try {
1695
+ return JSON.parse(result);
1696
+ } catch {
1697
+ return [];
1698
+ }
1699
+ }
1700
+ function watchClearAll() {
1701
+ const native = getNativeBridge();
1702
+ if (!native?.watch_clear_all) throw new Error("watch_clear_all not available");
1703
+ return native.watch_clear_all();
1704
+ }
1705
+ function watchEventTypeToString(event_type_code) {
1706
+ const native = getNativeBridge();
1707
+ if (!native?.watch_event_type_to_string) throw new Error("watch_event_type_to_string not available");
1708
+ return native.watch_event_type_to_string(event_type_code);
1709
+ }
1710
+ function isWatchRunning(handle) {
1711
+ const native = getNativeBridge();
1712
+ if (!native?.is_watch_running) throw new Error("is_watch_running not available");
1713
+ return native.is_watch_running(handle);
1714
+ }
1715
+ function getWatchStats() {
1716
+ const native = getNativeBridge();
1717
+ if (!native?.get_watch_stats) throw new Error("get_watch_stats not available");
1718
+ const result = native.get_watch_stats();
1719
+ try {
1720
+ return JSON.parse(result);
1721
+ } catch {
1722
+ return {
1723
+ active_watchers: 0,
1724
+ total_events: 0,
1725
+ events_this_second: 0,
1726
+ average_latency_ms: 0,
1727
+ largest_batch_size: 0
1728
+ };
1729
+ }
1730
+ }
1731
+ function watchPause(handle) {
1732
+ const native = getNativeBridge();
1733
+ if (!native?.watch_pause) throw new Error("watch_pause not available");
1734
+ return native.watch_pause(handle);
1735
+ }
1736
+ function watchResume(handle) {
1737
+ const native = getNativeBridge();
1738
+ if (!native?.watch_resume) throw new Error("watch_resume not available");
1739
+ return native.watch_resume(handle);
1740
+ }
1741
+ function scanCacheOptimizations() {
1742
+ const native = getNativeBridge();
1743
+ if (!native?.scan_cache_optimizations) throw new Error("scan_cache_optimizations not available");
1744
+ return native.scan_cache_optimizations();
1745
+ }
1746
+ function getPluginHooks() {
1747
+ const native = getNativeBridge();
1748
+ if (!native?.get_plugin_hooks) throw new Error("get_plugin_hooks not available");
1749
+ const result = native.get_plugin_hooks();
1750
+ try {
1751
+ return JSON.parse(result);
1752
+ } catch {
1753
+ return [];
1754
+ }
1755
+ }
1756
+ function registerPluginHook(hook_name, handler_id) {
1757
+ const native = getNativeBridge();
1758
+ if (!native?.register_plugin_hook) throw new Error("register_plugin_hook not available");
1759
+ return native.register_plugin_hook(hook_name, handler_id);
1760
+ }
1761
+ function unregisterPluginHook(hook_name, handler_id) {
1762
+ const native = getNativeBridge();
1763
+ if (!native?.unregister_plugin_hook) throw new Error("unregister_plugin_hook not available");
1764
+ return native.unregister_plugin_hook(hook_name, handler_id);
1765
+ }
1766
+ function emitPluginHook(hook_name, data_json) {
1767
+ const native = getNativeBridge();
1768
+ if (!native?.emit_plugin_hook) throw new Error("emit_plugin_hook not available");
1769
+ return native.emit_plugin_hook(hook_name, data_json);
1770
+ }
1771
+ function getCompilationMetrics() {
1772
+ const native = getNativeBridge();
1773
+ if (!native?.get_compilation_metrics) throw new Error("get_compilation_metrics not available");
1774
+ return native.get_compilation_metrics();
1775
+ }
1776
+ function resetCompilationMetrics() {
1777
+ const native = getNativeBridge();
1778
+ if (!native?.reset_compilation_metrics) throw new Error("reset_compilation_metrics not available");
1779
+ return native.reset_compilation_metrics();
1780
+ }
1781
+ function validateCssOutput(css) {
1782
+ const native = getNativeBridge();
1783
+ if (!native?.validate_css_output) throw new Error("validate_css_output not available");
1784
+ return native.validate_css_output(css);
1785
+ }
1786
+ function getCompilerDiagnostics() {
1787
+ const native = getNativeBridge();
1788
+ if (!native?.get_compiler_diagnostics) throw new Error("get_compiler_diagnostics not available");
1789
+ return native.get_compiler_diagnostics();
1790
+ }
1791
+ var init_watchSystemNative = __esm({
1792
+ "packages/domain/compiler/src/watchSystemNative.ts"() {
1793
+ init_nativeBridge();
1794
+ }
1795
+ });
1796
+
1797
+ // packages/domain/compiler/src/index.ts
1798
+ var src_exports = {};
1799
+ __export(src_exports, {
1800
+ BucketEngine: () => BucketEngine,
1801
+ IncrementalEngine: () => IncrementalEngine,
1802
+ adaptNativeResult: () => adaptNativeResult,
1803
+ analyzeClassUsage: () => analyzeClassUsage,
1804
+ analyzeClassUsageNative: () => analyzeClassUsageNative,
1805
+ analyzeClasses: () => analyzeClasses,
1806
+ analyzeClassesNative: () => analyzeClassesNative,
1807
+ analyzeFile: () => analyzeFile,
1808
+ analyzeRsc: () => analyzeRsc,
1809
+ analyzeRscNative: () => analyzeRscNative,
1810
+ analyzeVariantUsage: () => analyzeVariantUsage,
1811
+ astExtractClasses: () => astExtractClasses,
1812
+ atomicRegistrySize: () => atomicRegistrySize,
1813
+ batchExtractClasses: () => batchExtractClasses,
1814
+ batchExtractClassesNative: () => batchExtractClassesNative,
1815
+ bucketSort: () => bucketSort,
1816
+ buildStyleTag: () => buildStyleTag,
1817
+ cachePriority: () => cachePriority,
1818
+ cacheRead: () => cacheRead,
1819
+ cacheWrite: () => cacheWrite,
1820
+ checkAgainstSafelist: () => checkAgainstSafelist,
1821
+ checkAgainstSafelistNative: () => checkAgainstSafelistNative,
1822
+ classifyAndSortClasses: () => classifyAndSortClasses,
1823
+ classifyAndSortClassesNative: () => classifyAndSortClassesNative,
1824
+ classifyNode: () => classifyNode,
1825
+ clearAllCaches: () => clearAllCaches,
1826
+ clearAtomicRegistry: () => clearAtomicRegistry,
1827
+ clearCompileCache: () => clearCompileCache,
1828
+ clearCssGenCache: () => clearCssGenCache,
1829
+ clearParseCache: () => clearParseCache,
1830
+ clearResolveCache: () => clearResolveCache,
1831
+ clearThemeCache: () => clearThemeCache,
1832
+ collectFiles: () => collectFiles,
1833
+ compileAnimation: () => compileAnimation,
1834
+ compileClass: () => compileClass,
1835
+ compileClasses: () => compileClasses,
1836
+ compileCssFromClasses: () => compileCssFromClasses,
1837
+ compileCssLightning: () => compileCssLightning,
1838
+ compileCssNative: () => compileCssNative,
1839
+ compileCssNative2: () => compileCssNative2,
1840
+ compileKeyframes: () => compileKeyframes,
1841
+ compileTheme: () => compileTheme,
1842
+ compileToCss: () => compileToCss,
1843
+ compileToCssBatch: () => compileToCssBatch,
1844
+ compileVariantTable: () => compileVariantTable,
1845
+ compileVariantTableNative: () => compileVariantTableNative,
1846
+ compileVariants: () => compileVariants,
1847
+ computeIncrementalDiff: () => computeIncrementalDiff,
1848
+ createFingerprint: () => createFingerprint,
1849
+ detectConflicts: () => detectConflicts,
1850
+ detectDeadCode: () => detectDeadCode,
1851
+ diffClassLists: () => diffClassLists,
1852
+ eliminateDeadCss: () => eliminateDeadCss,
1853
+ eliminateDeadCssNative: () => eliminateDeadCssNative,
1854
+ emitPluginHook: () => emitPluginHook,
1855
+ estimateOptimalCacheConfig: () => estimateOptimalCacheConfig,
1856
+ extractAllClasses: () => extractAllClasses,
1857
+ extractAndGenerateStateCss: () => extractAndGenerateStateCss,
1858
+ extractAndGenerateStateCssNative: () => extractAndGenerateStateCssNative,
1859
+ extractClassesFromSource: () => extractClassesFromSource,
1860
+ extractClassesFromSourceNative: () => extractClassesFromSourceNative,
1861
+ extractComponentUsage: () => extractComponentUsage,
1862
+ extractContainerCssFromSource: () => extractContainerCssFromSource,
1863
+ extractTwContainerConfigs: () => extractTwContainerConfigs,
1864
+ extractTwStateConfigs: () => extractTwStateConfigs,
1865
+ extractTwStateConfigsNative: () => extractTwStateConfigsNative,
1866
+ fileToRoute: () => fileToRoute,
1867
+ findDeadVariants: () => findDeadVariants,
1868
+ generateAtomicCss: () => generateAtomicCss,
1869
+ generateCssForClasses: () => generateCssForClasses,
1870
+ generateCssNative: () => generateCssNative,
1871
+ generateSafelist: () => generateSafelist,
1872
+ generateStaticStateCss: () => generateStaticStateCss,
1873
+ generateStaticStateCssNative: () => generateStaticStateCssNative,
1874
+ generateSubComponentTypes: () => generateSubComponentTypes,
1875
+ getAllRoutes: () => getAllRoutes,
1876
+ getBucketEngine: () => getBucketEngine,
1877
+ getCacheOptimizationHints: () => getCacheOptimizationHints,
1878
+ getCacheStatistics: () => getCacheStatistics,
1879
+ getCacheStats: () => getCacheStats2,
1880
+ getCompilationMetrics: () => getCompilationMetrics,
1881
+ getCompilerDiagnostics: () => getCompilerDiagnostics,
1882
+ getContentPaths: () => getContentPaths,
1883
+ getIncrementalEngine: () => getIncrementalEngine,
1884
+ getNativeBridge: () => getNativeBridge,
1885
+ getPluginHooks: () => getPluginHooks,
1886
+ getRouteClasses: () => getRouteClasses,
1887
+ getWatchStats: () => getWatchStats,
1888
+ hasTwUsage: () => hasTwUsage,
1889
+ hashContent: () => hashContent,
1890
+ hoistComponents: () => hoistComponents,
1891
+ hoistComponentsNative: () => hoistComponentsNative,
1892
+ idRegistryActiveCount: () => idRegistryActiveCount,
1893
+ idRegistryCreate: () => idRegistryCreate,
1894
+ idRegistryDestroy: () => idRegistryDestroy,
1895
+ idRegistryExport: () => idRegistryExport,
1896
+ idRegistryGenerate: () => idRegistryGenerate,
1897
+ idRegistryImport: () => idRegistryImport,
1898
+ idRegistryLookup: () => idRegistryLookup,
1899
+ idRegistryNext: () => idRegistryNext,
1900
+ idRegistryReset: () => idRegistryReset,
1901
+ idRegistrySnapshot: () => idRegistrySnapshot,
1902
+ injectClientDirective: () => injectClientDirective,
1903
+ injectServerOnlyComment: () => injectServerOnlyComment,
1904
+ injectStateHash: () => injectStateHash,
1905
+ isAlreadyTransformed: () => isAlreadyTransformed,
1906
+ isWatchRunning: () => isWatchRunning,
1907
+ layoutClassesToCss: () => layoutClassesToCss,
1908
+ loadSafelist: () => loadSafelist,
1909
+ loadTailwindConfig: () => loadTailwindConfig,
1910
+ mergeClassesStatic: () => mergeClassesStatic,
1911
+ mergeCssDeclarations: () => mergeCssDeclarations,
1912
+ mergeCssDeclarationsNative: () => mergeCssDeclarationsNative,
1913
+ minifyCss: () => minifyCss,
1914
+ normalizeAndDedupClasses: () => normalizeAndDedupClasses,
1915
+ normalizeClasses: () => normalizeClasses,
1916
+ optimizeCss: () => optimizeCss,
1917
+ optimizeCssNative: () => optimizeCssNative,
1918
+ parseAtomicClass: () => parseAtomicClass,
1919
+ parseClasses: () => parseClasses,
1920
+ pollWatchEvents: () => pollWatchEvents,
1921
+ processFileChange: () => processFileChange,
1922
+ processTailwindCssLightning: () => processTailwindCssLightning,
1923
+ propertyIdToString: () => propertyIdToString,
1924
+ pruneStaleCacheEntries: () => pruneStaleCacheEntries,
1925
+ rebuildWorkspaceResult: () => rebuildWorkspaceResult,
1926
+ redisCacheClear: () => redisCacheClear,
1927
+ redisCacheHitRate: () => redisCacheHitRate,
1928
+ redisCacheKeyCount: () => redisCacheKeyCount,
1929
+ redisCacheSize: () => redisCacheSize,
1930
+ redisCacheSync: () => redisCacheSync,
1931
+ redisClusterStatus: () => redisClusterStatus,
1932
+ redisDelete: () => redisDelete,
1933
+ redisDiagnose: () => redisDiagnose,
1934
+ redisDisableCacheWarming: () => redisDisableCacheWarming,
1935
+ redisDisableCluster: () => redisDisableCluster,
1936
+ redisDisablePersistence: () => redisDisablePersistence,
1937
+ redisEnableCacheWarming: () => redisEnableCacheWarming,
1938
+ redisEnableCluster: () => redisEnableCluster,
1939
+ redisEnablePersistence: () => redisEnablePersistence,
1940
+ redisExists: () => redisExists,
1941
+ redisExpirationGet: () => redisExpirationGet,
1942
+ redisExpirationSet: () => redisExpirationSet,
1943
+ redisFlushAll: () => redisFlushAll,
1944
+ redisFlushDb: () => redisFlushDb,
1945
+ redisGet: () => redisGet,
1946
+ redisGetEvictionPolicy: () => redisGetEvictionPolicy,
1947
+ redisInfo: () => redisInfo,
1948
+ redisMemoryStats: () => redisMemoryStats,
1949
+ redisMget: () => redisMget,
1950
+ redisMonitor: () => redisMonitor,
1951
+ redisMset: () => redisMset,
1952
+ redisOptimizeMemory: () => redisOptimizeMemory,
1953
+ redisPing: () => redisPing,
1954
+ redisPoolConnect: () => redisPoolConnect,
1955
+ redisPoolReconnect: () => redisPoolReconnect,
1956
+ redisPoolStats: () => redisPoolStats,
1957
+ redisPublish: () => redisPublish,
1958
+ redisReplicate: () => redisReplicate,
1959
+ redisReplicationStatus: () => redisReplicationStatus,
1960
+ redisSet: () => redisSet,
1961
+ redisSetEvictionPolicy: () => redisSetEvictionPolicy,
1962
+ redisSnapshot: () => redisSnapshot,
1963
+ redisSubscribe: () => redisSubscribe,
1964
+ registerFileClasses: () => registerFileClasses,
1965
+ registerGlobalClasses: () => registerGlobalClasses,
1966
+ registerPluginHook: () => registerPluginHook,
1967
+ registerPropertyName: () => registerPropertyName,
1968
+ registerValueName: () => registerValueName,
1969
+ resetBucketEngine: () => resetBucketEngine,
1970
+ resetCompilationMetrics: () => resetCompilationMetrics,
1971
+ resetIncrementalEngine: () => resetIncrementalEngine,
1972
+ resetNativeBridgeCache: () => resetNativeBridgeCache,
1973
+ resolveCascade: () => resolveCascade,
1974
+ resolveClassNames: () => resolveClassNames,
1975
+ resolveConflictGroup: () => resolveConflictGroup,
1976
+ resolveSimpleVariants: () => resolveSimpleVariants,
1977
+ resolveThemeValue: () => resolveThemeValue,
1978
+ resolveVariants: () => resolveVariants,
1979
+ reverseLookupProperty: () => reverseLookupProperty,
1980
+ reverseLookupValue: () => reverseLookupValue,
1981
+ runElimination: () => runElimination,
1982
+ runLoaderTransform: () => runLoaderTransform,
1983
+ scanCacheOptimizations: () => scanCacheOptimizations,
1984
+ scanFile: () => scanFile,
1985
+ scanFileNative: () => scanFileNative,
1986
+ scanFilesBatchNative: () => scanFilesBatchNative,
1987
+ scanProjectUsage: () => scanProjectUsage,
1988
+ scanWorkspace: () => scanWorkspace,
1989
+ shouldProcess: () => shouldProcess,
1990
+ shouldSkipFile: () => shouldSkipFile,
1991
+ startWatch: () => startWatch,
1992
+ stopWatch: () => stopWatch,
1993
+ toAtomicClasses: () => toAtomicClasses,
1994
+ transformSource: () => transformSource,
1995
+ twMerge: () => twMerge,
1996
+ twMergeMany: () => twMergeMany,
1997
+ twMergeManyWithSeparator: () => twMergeManyWithSeparator,
1998
+ twMergeRaw: () => twMergeRaw,
1999
+ twMergeWithSeparator: () => twMergeWithSeparator,
2000
+ unregisterPluginHook: () => unregisterPluginHook,
2001
+ validateCssOutput: () => validateCssOutput,
2002
+ validateThemeConfig: () => validateThemeConfig,
2003
+ valueIdToString: () => valueIdToString,
2004
+ walkAndPrefilterSourceFiles: () => walkAndPrefilterSourceFiles,
2005
+ watchAddPattern: () => watchAddPattern,
2006
+ watchClearAll: () => watchClearAll,
2007
+ watchEventTypeToString: () => watchEventTypeToString,
2008
+ watchGetActiveHandles: () => watchGetActiveHandles,
2009
+ watchPause: () => watchPause,
2010
+ watchRemovePattern: () => watchRemovePattern,
2011
+ watchResume: () => watchResume
2012
+ });
2013
+ function _layoutClassesToCss(classes) {
2014
+ const native = getNativeBridge();
2015
+ if (!native?.layoutClassesToCss) {
2016
+ throw new Error("FATAL: Native binding 'layoutClassesToCss' is required but not available.");
2017
+ }
2018
+ return native.layoutClassesToCss(classes);
2019
+ }
2020
+ function _hashContainer(tag, containerJson, name) {
2021
+ const sortedKey = tag + (name ?? "") + containerJson;
2022
+ const native = getNativeBridge();
2023
+ if (!native?.hashContent) {
2024
+ throw new Error("FATAL: Native binding 'hashContent' is required but not available.");
2025
+ }
2026
+ return `tw-cq-${native.hashContent(sortedKey, "fnv", 6)}`;
2027
+ }
2028
+ function extractContainerCssFromSource(source) {
2029
+ const native = getNativeBridge();
2030
+ if (!native?.extractTwContainerConfigs) {
2031
+ throw new Error("FATAL: Native binding 'extractTwContainerConfigs' is required but not available.");
2032
+ }
2033
+ const configs = native.extractTwContainerConfigs(source);
2034
+ const rules = [];
2035
+ for (const cfg of configs) {
2036
+ const id = _hashContainer(cfg.tag, cfg.containerJson, cfg.containerName);
2037
+ for (const { key, classes } of cfg.breakpoints) {
2038
+ const minWidth = _CONTAINER_BREAKPOINTS[key] ?? key;
2039
+ const css = _layoutClassesToCss(classes);
2040
+ if (!css) continue;
2041
+ const query = cfg.containerName ? `@container ${cfg.containerName} (min-width: ${minWidth})` : `@container (min-width: ${minWidth})`;
2042
+ rules.push(`${query}{.${id}{${css}}}`);
2043
+ }
2044
+ }
2045
+ return rules.join("\n");
2046
+ }
2047
+ var transformSource, hasTwUsage, isAlreadyTransformed, shouldProcess, compileCssFromClasses, buildStyleTag, compileCssNative, generateCssForClasses, extractAllClasses, extractClassesFromSource, astExtractClasses, parseClasses, normalizeClasses, mergeClassesStatic, normalizeAndDedupClasses, eliminateDeadCss, findDeadVariants, runElimination, optimizeCss, scanProjectUsage, extractComponentUsage, diffClassLists, batchExtractClasses, checkAgainstSafelist, hoistComponents, compileVariantTable, compileVariants, classifyAndSortClasses, mergeCssDeclarations, analyzeClassUsage, analyzeRsc, analyzeFile, analyzeVariantUsage, injectClientDirective, injectServerOnlyComment, analyzeClasses, generateSafelist, loadSafelist, loadTailwindConfig, getContentPaths, _CONTAINER_BREAKPOINTS, runLoaderTransform, shouldSkipFile, fileToRoute, getAllRoutes, getRouteClasses, registerFileClasses, registerGlobalClasses, _incrementalEngineInstance, getIncrementalEngine, resetIncrementalEngine, IncrementalEngine, getBucketEngine, resetBucketEngine, BucketEngine, classifyNode, detectConflicts, bucketSort, extractTwStateConfigs, generateStaticStateCss, extractAndGenerateStateCss;
2048
+ var init_src = __esm({
2049
+ "packages/domain/compiler/src/index.ts"() {
2050
+ init_nativeBridge();
2051
+ init_cssGeneratorNative();
2052
+ init_scannerNative();
2053
+ init_analyzerNative();
2054
+ init_compilationNative();
2055
+ init_cacheNative();
2056
+ init_themeResolutionNative();
2057
+ init_streamingNative();
2058
+ init_cssCompilationNative();
2059
+ init_idRegistryNative();
2060
+ init_redisNative();
2061
+ init_watchSystemNative();
2062
+ transformSource = (source, opts) => {
2063
+ const native = getNativeBridge();
2064
+ if (!native?.transformSource) {
2065
+ throw new Error("FATAL: Native binding 'transformSource' is required but not available.");
1191
2066
  }
1192
- return native.compileVariantTable(configJson) || { id: "", tableJson: "{}", keys: [], defaultKey: "", combinations: 0 };
2067
+ const result = native.transformSource(source, opts);
2068
+ if (!result) {
2069
+ throw new Error("FATAL: transformSource returned null");
2070
+ }
2071
+ return result;
1193
2072
  };
1194
- compileVariants = (componentId, config) => {
1195
- return compileVariantTable(JSON.stringify({ componentId, ...config }));
2073
+ hasTwUsage = (source) => {
2074
+ const native = getNativeBridge();
2075
+ if (!native?.hasTwUsage) {
2076
+ throw new Error("FATAL: Native binding 'hasTwUsage' is required but not available.");
2077
+ }
2078
+ return native.hasTwUsage(source);
1196
2079
  };
1197
- classifyAndSortClasses = (classes) => {
2080
+ isAlreadyTransformed = (source) => {
1198
2081
  const native = getNativeBridge();
1199
- if (!native?.classifyAndSortClasses) {
1200
- throw new Error("FATAL: Native binding 'classifyAndSortClasses' is required but not available.");
2082
+ if (!native?.isAlreadyTransformed) {
2083
+ throw new Error("FATAL: Native binding 'isAlreadyTransformed' is required but not available.");
1201
2084
  }
1202
- return native.classifyAndSortClasses(classes) || [];
2085
+ return native.isAlreadyTransformed(source);
1203
2086
  };
1204
- mergeCssDeclarations = (cssChunks) => {
2087
+ shouldProcess = (source) => {
2088
+ return hasTwUsage(source) && !isAlreadyTransformed(source);
2089
+ };
2090
+ compileCssFromClasses = (classes, prefix) => {
1205
2091
  const native = getNativeBridge();
1206
- if (!native?.mergeCssDeclarations) {
1207
- throw new Error("FATAL: Native binding 'mergeCssDeclarations' is required but not available.");
2092
+ if (!native?.transformSource) {
2093
+ throw new Error("FATAL: Native binding 'transformSource' is required but not available.");
1208
2094
  }
1209
- return native.mergeCssDeclarations(cssChunks) || { declarationsJson: "{}", declarationString: "", count: 0 };
2095
+ const result = native.transformSource(classes.join(" "), { prefix: prefix ?? "" });
2096
+ if (!result) {
2097
+ throw new Error("FATAL: transformSource returned null");
2098
+ }
2099
+ return result;
1210
2100
  };
1211
- analyzeClassUsage = (classes, scanResultJson, css) => {
2101
+ buildStyleTag = (classes) => {
2102
+ const result = compileCssFromClasses(classes);
2103
+ return result?.code ? `<style data-tailwind-styled>${result.code}</style>` : "";
2104
+ };
2105
+ compileCssNative = (classes, prefix = null) => {
2106
+ return compileCssFromClasses(classes, prefix);
2107
+ };
2108
+ generateCssForClasses = async (classes, _tailwindConfig, root, cssEntryContent, minify = false) => {
2109
+ const { runCssPipeline: runCssPipeline2 } = await Promise.resolve().then(() => (init_tailwindEngine(), tailwindEngine_exports));
2110
+ const result = await runCssPipeline2(classes, cssEntryContent, root, minify);
2111
+ return result.css;
2112
+ };
2113
+ extractAllClasses = (source) => {
1212
2114
  const native = getNativeBridge();
1213
- if (!native?.analyzeClassUsage) {
1214
- throw new Error("FATAL: Native binding 'analyzeClassUsage' is required but not available.");
2115
+ if (!native?.extractAllClasses) {
2116
+ throw new Error("FATAL: Native binding 'extractAllClasses' is required but not available.");
1215
2117
  }
1216
- return native.analyzeClassUsage(classes, scanResultJson, css) || [];
2118
+ return native.extractAllClasses(source) || [];
1217
2119
  };
1218
- analyzeRsc = (source, filename) => {
2120
+ extractClassesFromSource = (source) => {
1219
2121
  const native = getNativeBridge();
1220
- if (!native?.analyzeRsc) {
1221
- throw new Error("FATAL: Native binding 'analyzeRsc' is required but not available.");
2122
+ if (!native?.extractClassesFromSource) {
2123
+ throw new Error("FATAL: Native binding 'extractClassesFromSource' is required but not available.");
1222
2124
  }
1223
- return native.analyzeRsc(source, filename) || { isServer: true, needsClientDirective: false, clientReasons: [] };
2125
+ const result = native.extractClassesFromSource(source);
2126
+ return Array.isArray(result) ? result.join(" ") : String(result || "");
2127
+ };
2128
+ astExtractClasses = (source, _filename) => {
2129
+ const native = getNativeBridge();
2130
+ if (!native?.extractClassesFromSource) {
2131
+ throw new Error("FATAL: Native binding 'extractClassesFromSource' is required but not available.");
2132
+ }
2133
+ return native.extractClassesFromSource(source) || [];
2134
+ };
2135
+ parseClasses = (raw) => {
2136
+ const native = getNativeBridge();
2137
+ if (!native?.parseClasses) {
2138
+ throw new Error("FATAL: Native binding 'parseClasses' is required but not available.");
2139
+ }
2140
+ return native.parseClasses(raw) || [];
2141
+ };
2142
+ normalizeClasses = (raw) => {
2143
+ const result = normalizeAndDedupClasses(raw);
2144
+ return result?.normalized || "";
2145
+ };
2146
+ mergeClassesStatic = (classes) => {
2147
+ const result = normalizeAndDedupClasses(classes);
2148
+ return result?.normalized || "";
2149
+ };
2150
+ normalizeAndDedupClasses = (raw) => {
2151
+ const native = getNativeBridge();
2152
+ if (!native?.normalizeAndDedupClasses) {
2153
+ throw new Error("FATAL: Native binding 'normalizeAndDedupClasses' is required but not available.");
2154
+ }
2155
+ const result = native.normalizeAndDedupClasses(raw);
2156
+ return result || { normalized: "", duplicatesRemoved: 0, uniqueCount: 0 };
2157
+ };
2158
+ eliminateDeadCss = (css, deadClasses) => {
2159
+ const native = getNativeBridge();
2160
+ if (!native?.eliminateDeadCss) {
2161
+ throw new Error("FATAL: Native binding 'eliminateDeadCss' is required but not available.");
2162
+ }
2163
+ return native.eliminateDeadCss(css, Array.from(deadClasses));
2164
+ };
2165
+ findDeadVariants = (variantConfig, usage) => {
2166
+ const unused = [];
2167
+ const configs = Array.isArray(variantConfig) ? variantConfig : [{ name: "__root__", variants: variantConfig }];
2168
+ for (const component of configs) {
2169
+ const componentUsage = usage[component.name] ?? /* @__PURE__ */ new Set();
2170
+ const variants = component.variants;
2171
+ for (const [key, values] of Object.entries(variants)) {
2172
+ for (const [value] of Object.entries(values)) {
2173
+ if (!componentUsage.has(`${key}:${value}`)) {
2174
+ unused.push(`${component.name !== "__root__" ? `${component.name}/` : ""}${key}:${value}`);
2175
+ }
2176
+ }
2177
+ }
2178
+ }
2179
+ return { unusedCount: unused.length, unused };
2180
+ };
2181
+ runElimination = (css, scanResult) => {
2182
+ const native = getNativeBridge();
2183
+ if (!native?.detectDeadCode) {
2184
+ throw new Error("FATAL: Native binding 'detectDeadCode' is required but not available.");
2185
+ }
2186
+ const dead = native.detectDeadCode(JSON.stringify(scanResult), css);
2187
+ return eliminateDeadCss(css, new Set(dead.deadInCss ?? []));
2188
+ };
2189
+ optimizeCss = (css) => {
2190
+ const native = getNativeBridge();
2191
+ if (!native?.optimizeCss) {
2192
+ throw new Error("FATAL: Native binding 'optimizeCss' is required but not available.");
2193
+ }
2194
+ return native.optimizeCss(css);
2195
+ };
2196
+ scanProjectUsage = (dirs, cwd) => {
2197
+ const files = dirs.map((dir) => path10__namespace.default.resolve(cwd, dir));
2198
+ const results = batchExtractClasses(files) || [];
2199
+ const combined = {};
2200
+ for (const result of results) {
2201
+ if (result.ok && result.classes) {
2202
+ for (const cls of result.classes) {
2203
+ if (!combined[cls]) combined[cls] = {};
2204
+ combined[cls][result.file] = /* @__PURE__ */ new Set([cls]);
2205
+ }
2206
+ }
2207
+ }
2208
+ return combined;
2209
+ };
2210
+ extractComponentUsage = (source) => {
2211
+ const native = getNativeBridge();
2212
+ if (!native?.extractComponentUsage) {
2213
+ throw new Error("FATAL: Native binding 'extractComponentUsage' is required but not available.");
2214
+ }
2215
+ return native.extractComponentUsage(source) || [];
2216
+ };
2217
+ diffClassLists = (previous, current) => {
2218
+ const native = getNativeBridge();
2219
+ if (!native?.diffClassLists) {
2220
+ throw new Error("FATAL: Native binding 'diffClassLists' is required but not available.");
2221
+ }
2222
+ return native.diffClassLists(previous, current) || { added: [], removed: [], unchanged: [], hasChanges: false };
2223
+ };
2224
+ batchExtractClasses = (filePaths) => {
2225
+ const native = getNativeBridge();
2226
+ if (!native?.batchExtractClasses) {
2227
+ throw new Error("FATAL: Native binding 'batchExtractClasses' is required but not available.");
2228
+ }
2229
+ return native.batchExtractClasses(filePaths) || [];
2230
+ };
2231
+ checkAgainstSafelist = (classes, safelist) => {
2232
+ const native = getNativeBridge();
2233
+ if (!native?.checkAgainstSafelist) {
2234
+ throw new Error("FATAL: Native binding 'checkAgainstSafelist' is required but not available.");
2235
+ }
2236
+ return native.checkAgainstSafelist(classes, safelist) || { matched: [], unmatched: [], safelistSize: 0 };
2237
+ };
2238
+ hoistComponents = (source) => {
2239
+ const native = getNativeBridge();
2240
+ if (!native?.hoistComponents) {
2241
+ throw new Error("FATAL: Native binding 'hoistComponents' is required but not available.");
2242
+ }
2243
+ return native.hoistComponents(source) || { code: source, hoisted: [], warnings: [] };
2244
+ };
2245
+ compileVariantTable = (configJson) => {
2246
+ const native = getNativeBridge();
2247
+ if (!native?.compileVariantTable) {
2248
+ throw new Error("FATAL: Native binding 'compileVariantTable' is required but not available.");
2249
+ }
2250
+ return native.compileVariantTable(configJson) || { id: "", tableJson: "{}", keys: [], defaultKey: "", combinations: 0 };
2251
+ };
2252
+ compileVariants = (componentId, config) => {
2253
+ return compileVariantTable(JSON.stringify({ componentId, ...config }));
2254
+ };
2255
+ classifyAndSortClasses = (classes) => {
2256
+ const native = getNativeBridge();
2257
+ if (!native?.classifyAndSortClasses) {
2258
+ throw new Error("FATAL: Native binding 'classifyAndSortClasses' is required but not available.");
2259
+ }
2260
+ return native.classifyAndSortClasses(classes) || [];
2261
+ };
2262
+ mergeCssDeclarations = (cssChunks) => {
2263
+ const native = getNativeBridge();
2264
+ if (!native?.mergeCssDeclarations) {
2265
+ throw new Error("FATAL: Native binding 'mergeCssDeclarations' is required but not available.");
2266
+ }
2267
+ return native.mergeCssDeclarations(cssChunks) || { declarationsJson: "{}", declarationString: "", count: 0 };
2268
+ };
2269
+ analyzeClassUsage = (classes, scanResultJson, css) => {
2270
+ const native = getNativeBridge();
2271
+ if (!native?.analyzeClassUsage) {
2272
+ throw new Error("FATAL: Native binding 'analyzeClassUsage' is required but not available.");
2273
+ }
2274
+ return native.analyzeClassUsage(classes, scanResultJson, css) || [];
2275
+ };
2276
+ analyzeRsc = (source, filename) => {
2277
+ const native = getNativeBridge();
2278
+ if (!native?.analyzeRsc) {
2279
+ throw new Error("FATAL: Native binding 'analyzeRsc' is required but not available.");
2280
+ }
2281
+ return native.analyzeRsc(source, filename) || { isServer: true, needsClientDirective: false, clientReasons: [] };
1224
2282
  };
1225
2283
  analyzeFile = (source, filename) => {
1226
2284
  const rsc = analyzeRsc(source, filename);
@@ -1232,170 +2290,1061 @@ var init_src2 = __esm({
1232
2290
  canStaticResolveVariants: true
1233
2291
  };
1234
2292
  };
1235
- analyzeVariantUsage = (source, componentName, variantKeys) => {
1236
- analyzeRsc(source, componentName);
1237
- return {
1238
- resolved: {},
1239
- dynamic: []
2293
+ analyzeVariantUsage = (_source, _componentName, _variantKeys) => {
2294
+ return { resolved: {}, dynamic: [] };
2295
+ };
2296
+ injectClientDirective = (source) => {
2297
+ if (!source.includes('"use client"') && !source.includes("'use client'")) {
2298
+ return '"use client";\n' + source;
2299
+ }
2300
+ return source;
2301
+ };
2302
+ injectServerOnlyComment = (source) => {
2303
+ return `/* @server-only */
2304
+ ${source}`;
2305
+ };
2306
+ analyzeClasses = (filesJson, cwd, flags) => {
2307
+ const native = getNativeBridge();
2308
+ if (!native?.analyzeClasses) {
2309
+ throw new Error("FATAL: Native binding 'analyzeClasses' is required but not available.");
2310
+ }
2311
+ return native.analyzeClasses(filesJson, cwd, flags);
2312
+ };
2313
+ generateSafelist = (scanDirs, outputPath, cwd) => {
2314
+ const classes = scanProjectUsage(scanDirs, cwd || process.cwd());
2315
+ const allClasses = Object.keys(classes).sort();
2316
+ if (outputPath) {
2317
+ fs9__namespace.default.writeFileSync(outputPath, JSON.stringify(allClasses, null, 2));
2318
+ }
2319
+ return allClasses;
2320
+ };
2321
+ loadSafelist = (safelistPath) => {
2322
+ try {
2323
+ const content = fs9__namespace.default.readFileSync(safelistPath, "utf-8");
2324
+ return JSON.parse(content);
2325
+ } catch {
2326
+ return [];
2327
+ }
2328
+ };
2329
+ loadTailwindConfig = (cwd = process.cwd()) => {
2330
+ const configFiles = [
2331
+ "tailwind.config.ts",
2332
+ "tailwind.config.js",
2333
+ "tailwind.config.mjs",
2334
+ "tailwind.config.cjs"
2335
+ ];
2336
+ for (const file of configFiles) {
2337
+ const fullPath = path10__namespace.default.join(cwd, file);
2338
+ if (fs9__namespace.default.existsSync(fullPath)) {
2339
+ const mod = __require(fullPath);
2340
+ return mod.default || mod;
2341
+ }
2342
+ }
2343
+ return {};
2344
+ };
2345
+ getContentPaths = (cwd = process.cwd()) => {
2346
+ return {
2347
+ content: [
2348
+ path10__namespace.default.join(cwd, "src/**/*.{js,ts,jsx,tsx}"),
2349
+ path10__namespace.default.join(cwd, "app/**/*.{js,ts,jsx,tsx}"),
2350
+ path10__namespace.default.join(cwd, "pages/**/*.{js,ts,jsx,tsx}")
2351
+ ]
2352
+ };
2353
+ };
2354
+ _CONTAINER_BREAKPOINTS = {
2355
+ xs: "240px",
2356
+ sm: "320px",
2357
+ md: "640px",
2358
+ lg: "1024px",
2359
+ xl: "1280px",
2360
+ "2xl": "1536px"
2361
+ };
2362
+ runLoaderTransform = (ctx) => {
2363
+ const { filepath, source, options } = ctx;
2364
+ const result = transformSource(source, { filename: filepath, ...options });
2365
+ let staticCss;
2366
+ try {
2367
+ const cssChunks = [];
2368
+ const stateRules = extractAndGenerateStateCss(source, filepath);
2369
+ if (stateRules.length > 0) {
2370
+ cssChunks.push(stateRules.map((r) => r.cssRule).join("\n"));
2371
+ }
2372
+ const containerCss = extractContainerCssFromSource(source);
2373
+ if (containerCss) cssChunks.push(containerCss);
2374
+ const combined = cssChunks.join("\n").trim();
2375
+ if (combined) staticCss = combined;
2376
+ } catch {
2377
+ }
2378
+ return {
2379
+ code: result?.code || "",
2380
+ changed: result?.changed || false,
2381
+ classes: result?.classes || [],
2382
+ staticCss
2383
+ };
2384
+ };
2385
+ shouldSkipFile = (filepath) => {
2386
+ const SKIP_PATHS = ["node_modules", ".next", ".rspack-dist", ".turbo", "dist/", "out/"];
2387
+ const skipExtensions = [".css", ".json", ".md", ".txt", ".yaml", ".yml"];
2388
+ for (const p of SKIP_PATHS) {
2389
+ if (filepath.includes(p)) return true;
2390
+ }
2391
+ for (const ext of skipExtensions) {
2392
+ if (filepath.endsWith(ext)) return true;
2393
+ }
2394
+ return false;
2395
+ };
2396
+ fileToRoute = (filepath) => {
2397
+ const normalized = filepath.replace(/\\/g, "/");
2398
+ if (normalized.includes("/layout.") || normalized.includes("/loading.") || normalized.includes("/error.")) {
2399
+ return "__global";
2400
+ }
2401
+ const pageMatch = normalized.match(/\/app\/(.+?)\/page\.[tj]sx?$/);
2402
+ if (pageMatch) return `/${pageMatch[1]}`;
2403
+ const rootPage = normalized.match(/\/app\/page\.[tj]sx?$/);
2404
+ if (rootPage) return "/";
2405
+ return null;
2406
+ };
2407
+ getAllRoutes = () => {
2408
+ const native = getNativeBridge();
2409
+ if (!native?.analyzeClasses) {
2410
+ throw new Error("FATAL: Native binding 'analyzeClasses' is required but not available.");
2411
+ }
2412
+ return ["/", "__global"];
2413
+ };
2414
+ getRouteClasses = (_route) => /* @__PURE__ */ new Set();
2415
+ registerFileClasses = (_filepath, _classes) => {
2416
+ };
2417
+ registerGlobalClasses = (_classes) => {
2418
+ };
2419
+ _incrementalEngineInstance = null;
2420
+ getIncrementalEngine = () => {
2421
+ if (!_incrementalEngineInstance) {
2422
+ _incrementalEngineInstance = new IncrementalEngine();
2423
+ }
2424
+ return _incrementalEngineInstance;
2425
+ };
2426
+ resetIncrementalEngine = () => {
2427
+ _incrementalEngineInstance = null;
2428
+ };
2429
+ IncrementalEngine = class {
2430
+ compile(source) {
2431
+ return transformSource(source);
2432
+ }
2433
+ };
2434
+ getBucketEngine = () => {
2435
+ const native = getNativeBridge();
2436
+ if (!native?.classifyAndSortClasses) {
2437
+ throw new Error("FATAL: Native binding 'classifyAndSortClasses' is required but not available.");
2438
+ }
2439
+ return {
2440
+ add: (className) => className,
2441
+ get: (_bucket) => []
2442
+ };
2443
+ };
2444
+ resetBucketEngine = () => {
2445
+ };
2446
+ BucketEngine = class {
2447
+ add(className) {
2448
+ return className;
2449
+ }
2450
+ };
2451
+ classifyNode = (_node) => {
2452
+ const native = getNativeBridge();
2453
+ if (!native?.classifyAndSortClasses) {
2454
+ throw new Error("FATAL: Native binding 'classifyAndSortClasses' is required but not available.");
2455
+ }
2456
+ return "unknown";
2457
+ };
2458
+ detectConflicts = (_classes) => {
2459
+ const native = getNativeBridge();
2460
+ if (!native?.analyzeClassUsage) {
2461
+ throw new Error("FATAL: Native binding 'analyzeClassUsage' is required but not available.");
2462
+ }
2463
+ return [];
2464
+ };
2465
+ bucketSort = (classes) => {
2466
+ return classifyAndSortClasses(classes).map((c) => c.raw ?? c);
2467
+ };
2468
+ extractTwStateConfigs = (source, filename) => {
2469
+ const native = getNativeBridge();
2470
+ if (!native?.extractTwStateConfigs) {
2471
+ throw new Error("FATAL: Native binding 'extractTwStateConfigs' is required but not available.");
2472
+ }
2473
+ return native.extractTwStateConfigs(source, filename);
2474
+ };
2475
+ generateStaticStateCss = (inputs, resolvedCss = null) => {
2476
+ const native = getNativeBridge();
2477
+ if (!native?.generateStaticStateCss) {
2478
+ throw new Error("FATAL: Native binding 'generateStaticStateCss' is required but not available.");
2479
+ }
2480
+ return native.generateStaticStateCss(inputs, resolvedCss);
2481
+ };
2482
+ extractAndGenerateStateCss = (source, filename) => {
2483
+ const native = getNativeBridge();
2484
+ if (!native?.extractAndGenerateStateCss) {
2485
+ const configs = extractTwStateConfigs(source, filename);
2486
+ if (configs.length === 0) return [];
2487
+ return generateStaticStateCss(
2488
+ configs.map((c) => ({ tag: c.tag, componentName: c.componentName, statesJson: c.statesJson }))
2489
+ );
2490
+ }
2491
+ return native.extractAndGenerateStateCss(source, filename);
2492
+ };
2493
+ }
2494
+ });
2495
+
2496
+ // packages/domain/compiler/src/internal.ts
2497
+ var internal_exports = {};
2498
+ __export(internal_exports, {
2499
+ adaptNativeResult: () => adaptNativeResult,
2500
+ analyzeClassUsage: () => analyzeClassUsage,
2501
+ analyzeClasses: () => analyzeClasses,
2502
+ analyzeFile: () => analyzeFile,
2503
+ analyzeRsc: () => analyzeRsc,
2504
+ analyzeVariantUsage: () => analyzeVariantUsage,
2505
+ astExtractClasses: () => astExtractClasses,
2506
+ batchExtractClasses: () => batchExtractClasses,
2507
+ bucketSort: () => bucketSort,
2508
+ buildStyleTag: () => buildStyleTag,
2509
+ checkAgainstSafelist: () => checkAgainstSafelist,
2510
+ classifyAndSortClasses: () => classifyAndSortClasses,
2511
+ classifyNode: () => classifyNode,
2512
+ clearCache: () => clearCache,
2513
+ compileCssFromClasses: () => compileCssFromClasses,
2514
+ compileCssNative: () => compileCssNative,
2515
+ compileVariantTable: () => compileVariantTable,
2516
+ compileVariants: () => compileVariants,
2517
+ detectConflicts: () => detectConflicts,
2518
+ diffClassLists: () => diffClassLists,
2519
+ eliminateDeadCss: () => eliminateDeadCss,
2520
+ extractAllClasses: () => extractAllClasses,
2521
+ extractAndGenerateStateCss: () => extractAndGenerateStateCss,
2522
+ extractClassesFromSource: () => extractClassesFromSource,
2523
+ extractComponentUsage: () => extractComponentUsage,
2524
+ extractContainerCssFromSource: () => extractContainerCssFromSource,
2525
+ extractTwStateConfigs: () => extractTwStateConfigs,
2526
+ fileToRoute: () => fileToRoute,
2527
+ findDeadVariants: () => findDeadVariants,
2528
+ generateCssForClasses: () => generateCssForClasses,
2529
+ generateRawCss: () => generateRawCss,
2530
+ generateSafelist: () => generateSafelist,
2531
+ generateStaticStateCss: () => generateStaticStateCss,
2532
+ getAllRoutes: () => getAllRoutes,
2533
+ getBucketEngine: () => getBucketEngine,
2534
+ getCacheStats: () => getCacheStats,
2535
+ getContentPaths: () => getContentPaths,
2536
+ getIncrementalEngine: () => getIncrementalEngine,
2537
+ getNativeBridge: () => getNativeBridge,
2538
+ getRouteClasses: () => getRouteClasses,
2539
+ hasTwUsage: () => hasTwUsage,
2540
+ hoistComponents: () => hoistComponents,
2541
+ injectClientDirective: () => injectClientDirective,
2542
+ injectServerOnlyComment: () => injectServerOnlyComment,
2543
+ isAlreadyTransformed: () => isAlreadyTransformed,
2544
+ loadSafelist: () => loadSafelist,
2545
+ loadTailwindConfig: () => loadTailwindConfig,
2546
+ mergeClassesStatic: () => mergeClassesStatic,
2547
+ mergeCssDeclarations: () => mergeCssDeclarations,
2548
+ normalizeAndDedupClasses: () => normalizeAndDedupClasses,
2549
+ normalizeClasses: () => normalizeClasses,
2550
+ optimizeCss: () => optimizeCss,
2551
+ parseClasses: () => parseClasses,
2552
+ registerFileClasses: () => registerFileClasses,
2553
+ registerGlobalClasses: () => registerGlobalClasses,
2554
+ resetBucketEngine: () => resetBucketEngine,
2555
+ resetIncrementalEngine: () => resetIncrementalEngine,
2556
+ runCssPipeline: () => runCssPipeline,
2557
+ runCssPipelineSync: () => runCssPipelineSync,
2558
+ runElimination: () => runElimination,
2559
+ runLoaderTransform: () => runLoaderTransform,
2560
+ scanProjectUsage: () => scanProjectUsage,
2561
+ shouldProcess: () => shouldProcess,
2562
+ shouldSkipFile: () => shouldSkipFile,
2563
+ transformSource: () => transformSource
2564
+ });
2565
+ var init_internal = __esm({
2566
+ "packages/domain/compiler/src/internal.ts"() {
2567
+ init_src();
2568
+ init_tailwindEngine();
2569
+ }
2570
+ });
2571
+ function getNative() {
2572
+ if (_native) return _native;
2573
+ try {
2574
+ const mod = (init_internal(), __toCommonJS(internal_exports));
2575
+ if (typeof mod?.extractTwStateConfigs !== "function" || typeof mod?.generateStaticStateCss !== "function") {
2576
+ return null;
2577
+ }
2578
+ _native = {
2579
+ extractTwStateConfigs: mod.extractTwStateConfigs,
2580
+ generateStaticStateCss: mod.generateStaticStateCss,
2581
+ extractAndGenerateStateCss: mod.extractAndGenerateStateCss ?? // Fallback jika extractAndGenerateStateCss belum di-export
2582
+ ((source, filename) => {
2583
+ const configs = mod.extractTwStateConfigs(source, filename);
2584
+ if (configs.length === 0) return [];
2585
+ return mod.generateStaticStateCss(configs.map((c) => ({
2586
+ tag: c.tag,
2587
+ componentName: c.componentName,
2588
+ statesJson: c.statesJson
2589
+ })));
2590
+ })
2591
+ };
2592
+ return _native;
2593
+ } catch {
2594
+ return null;
2595
+ }
2596
+ }
2597
+ function* walkSourceFiles(dir) {
2598
+ let entries;
2599
+ try {
2600
+ entries = fs9__namespace.default.readdirSync(dir, { withFileTypes: true });
2601
+ } catch {
2602
+ return;
2603
+ }
2604
+ for (const entry of entries) {
2605
+ const fullPath = path10__namespace.default.join(dir, entry.name);
2606
+ if (entry.isDirectory()) {
2607
+ if (IGNORE_PATTERNS.some((p) => entry.name === p || entry.name.startsWith(p))) continue;
2608
+ yield* walkSourceFiles(fullPath);
2609
+ } else if (entry.isFile()) {
2610
+ const ext = path10__namespace.default.extname(entry.name);
2611
+ if (SOURCE_EXTENSIONS.has(ext)) yield fullPath;
2612
+ }
2613
+ }
2614
+ }
2615
+ function buildCssHeader(result) {
2616
+ return [
2617
+ "/* \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500",
2618
+ " * tw-state-static.css \u2014 Auto-generated by staticStateExtractor.ts",
2619
+ " * DO NOT EDIT. Re-generated on each build.",
2620
+ " *",
2621
+ ` * Files scanned: ${result.filesScanned}`,
2622
+ ` * Files with states: ${result.filesWithStates}`,
2623
+ ` * Components found: ${result.componentsFound}`,
2624
+ ` * Rules generated: ${result.rulesGenerated}`,
2625
+ ` * Rules skipped: ${result.rulesSkipped} (akan di-inject runtime sebagai fallback)`,
2626
+ " *",
2627
+ ' * Selector format: .tw-s-[hash][data-stateName="true"] { ... }',
2628
+ " * Hash identik dengan yang dibuat oleh stateEngine.ts di runtime.",
2629
+ " * \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 */",
2630
+ ""
2631
+ ].join("\n");
2632
+ }
2633
+ function extractStaticStateCss(srcDir, options = {}) {
2634
+ const { verbose = false, maxFiles = Infinity } = options;
2635
+ const native = getNative();
2636
+ if (!native) {
2637
+ if (verbose) {
2638
+ process.stderr.write(
2639
+ "[tw:static-state] native module tidak tersedia \u2014 skip static CSS pre-generation\n"
2640
+ );
2641
+ }
2642
+ return {
2643
+ filesScanned: 0,
2644
+ filesWithStates: 0,
2645
+ componentsFound: 0,
2646
+ rulesGenerated: 0,
2647
+ rulesSkipped: 0,
2648
+ generatedCss: "",
2649
+ rules: []
2650
+ };
2651
+ }
2652
+ const allConfigs = [];
2653
+ let filesScanned = 0;
2654
+ let filesWithStates = 0;
2655
+ if (native.walkAndPrefilterSourceFiles) {
2656
+ const prefiltered = native.walkAndPrefilterSourceFiles(
2657
+ srcDir,
2658
+ [".ts", ".tsx", ".js", ".jsx", ".mts", ".mjs"],
2659
+ ["node_modules", ".next", "dist", "build", ".git", "coverage", "__tests__"],
2660
+ // Required substrings — AND logic, identik dengan JS pre-filter di bawah
2661
+ ["states:", "tw."],
2662
+ maxFiles === Infinity ? null : maxFiles,
2663
+ null
2664
+ // sequential — parallel mode opsional untuk large monorepo
2665
+ );
2666
+ for (const { path: filePath, content: source } of prefiltered) {
2667
+ filesScanned++;
2668
+ const configs = native.extractTwStateConfigs(source, filePath);
2669
+ if (configs.length > 0) {
2670
+ filesWithStates++;
2671
+ allConfigs.push(...configs);
2672
+ if (verbose) {
2673
+ process.stderr.write(
2674
+ `[tw:static-state] ${path10__namespace.default.relative(srcDir, filePath)}: ${configs.length} komponen
2675
+ `
2676
+ );
2677
+ }
2678
+ }
2679
+ }
2680
+ } else {
2681
+ for (const filePath of walkSourceFiles(srcDir)) {
2682
+ if (filesScanned >= maxFiles) break;
2683
+ let source;
2684
+ try {
2685
+ source = fs9__namespace.default.readFileSync(filePath, "utf-8");
2686
+ } catch {
2687
+ continue;
2688
+ }
2689
+ filesScanned++;
2690
+ if (!source.includes("states:") && !source.includes("states :")) continue;
2691
+ if (!source.includes("tw.") && !source.includes("tailwind-styled")) continue;
2692
+ const configs = native.extractTwStateConfigs(source, filePath);
2693
+ if (configs.length > 0) {
2694
+ filesWithStates++;
2695
+ allConfigs.push(...configs);
2696
+ if (verbose) {
2697
+ process.stderr.write(
2698
+ `[tw:static-state] ${path10__namespace.default.relative(srcDir, filePath)}: ${configs.length} komponen
2699
+ `
2700
+ );
2701
+ }
2702
+ }
2703
+ }
2704
+ }
2705
+ if (allConfigs.length === 0) {
2706
+ return {
2707
+ filesScanned,
2708
+ filesWithStates: 0,
2709
+ componentsFound: 0,
2710
+ rulesGenerated: 0,
2711
+ rulesSkipped: 0,
2712
+ generatedCss: "",
2713
+ rules: []
2714
+ };
2715
+ }
2716
+ const seen = /* @__PURE__ */ new Set();
2717
+ const uniqueConfigs = [];
2718
+ for (const config of allConfigs) {
2719
+ const key = `${config.tag}::${config.statesJson}`;
2720
+ if (!seen.has(key)) {
2721
+ seen.add(key);
2722
+ uniqueConfigs.push({
2723
+ tag: config.tag,
2724
+ componentName: config.componentName,
2725
+ statesJson: config.statesJson
2726
+ });
2727
+ }
2728
+ }
2729
+ const allRules = native.generateStaticStateCss(uniqueConfigs, options.resolvedCss ?? null);
2730
+ const rulesSkipped = uniqueConfigs.reduce((total, cfg) => {
2731
+ try {
2732
+ const stateMap = JSON.parse(cfg.statesJson);
2733
+ return total + Object.keys(stateMap).length;
2734
+ } catch {
2735
+ return total;
2736
+ }
2737
+ }, 0) - allRules.length;
2738
+ const byComponent = /* @__PURE__ */ new Map();
2739
+ for (const rule of allRules) {
2740
+ const existing = byComponent.get(rule.componentName) ?? [];
2741
+ existing.push(rule);
2742
+ byComponent.set(rule.componentName, existing);
2743
+ }
2744
+ const cssBlocks = [];
2745
+ for (const [componentName, rules] of byComponent) {
2746
+ cssBlocks.push(`/* ${componentName} */`);
2747
+ for (const rule of rules) {
2748
+ cssBlocks.push(`/* state: ${rule.stateName} */`);
2749
+ cssBlocks.push(rule.cssRule);
2750
+ }
2751
+ cssBlocks.push("");
2752
+ }
2753
+ const result = {
2754
+ filesScanned,
2755
+ filesWithStates,
2756
+ componentsFound: allConfigs.length,
2757
+ rulesGenerated: allRules.length,
2758
+ rulesSkipped: Math.max(0, rulesSkipped),
2759
+ generatedCss: cssBlocks.join("\n"),
2760
+ rules: allRules
2761
+ };
2762
+ result.generatedCss = buildCssHeader(result) + result.generatedCss;
2763
+ return result;
2764
+ }
2765
+ function appendStaticStateCssToSafelist(srcDir, safelistPath, options = {}) {
2766
+ const result = extractStaticStateCss(srcDir, options);
2767
+ const twClassesDir = path10__namespace.default.join(path10__namespace.default.dirname(safelistPath), "tw-classes");
2768
+ fs9__namespace.default.mkdirSync(twClassesDir, { recursive: true });
2769
+ const stateFilePath = path10__namespace.default.join(twClassesDir, TW_STATE_STATIC_FILENAME);
2770
+ if (result.rulesGenerated === 0) {
2771
+ try {
2772
+ fs9__namespace.default.writeFileSync(
2773
+ stateFilePath,
2774
+ "/* tw-state-static.css \u2014 tidak ada state rules yang di-generate */\n",
2775
+ "utf-8"
2776
+ );
2777
+ } catch {
2778
+ }
2779
+ return `[tw:static-state] tidak ada state rules yang di-generate (${result.filesScanned} files di-scan)`;
2780
+ }
2781
+ try {
2782
+ fs9__namespace.default.writeFileSync(stateFilePath, result.generatedCss, "utf-8");
2783
+ return [
2784
+ `[tw:static-state] ${result.rulesGenerated} static state rules di-generate`,
2785
+ ` \u2192 ${result.filesScanned} files scanned, ${result.filesWithStates} dengan states`,
2786
+ ` \u2192 ${result.componentsFound} components, ${result.rulesSkipped} rules skipped (fallback ke runtime)`,
2787
+ ` \u2192 ditulis ke tw-classes/${TW_STATE_STATIC_FILENAME}`
2788
+ ].join("\n");
2789
+ } catch (writeErr) {
2790
+ const msg = writeErr instanceof Error ? writeErr.message : String(writeErr);
2791
+ return `[tw:static-state] gagal tulis state CSS: ${msg}`;
2792
+ }
2793
+ }
2794
+ var SOURCE_EXTENSIONS, IGNORE_PATTERNS, _native, TW_STATE_STATIC_FILENAME;
2795
+ var init_staticStateExtractor = __esm({
2796
+ "packages/domain/shared/src/staticStateExtractor.ts"() {
2797
+ SOURCE_EXTENSIONS = /* @__PURE__ */ new Set([".ts", ".tsx", ".js", ".jsx", ".mts", ".mjs"]);
2798
+ IGNORE_PATTERNS = ["node_modules", ".next", "dist", "build", ".git", "coverage", "__tests__"];
2799
+ _native = null;
2800
+ TW_STATE_STATIC_FILENAME = "_tw-state-static.css";
2801
+ }
2802
+ });
2803
+ function getEnvLevel() {
2804
+ const env = process.env.TWS_LOG_LEVEL?.toLowerCase();
2805
+ if (env && env in LEVELS) return env;
2806
+ return process.env.TWS_DEBUG_SCANNER === "1" ? "debug" : "info";
2807
+ }
2808
+ function setGlobalLogFile(filePath) {
2809
+ _globalLogFile = filePath;
2810
+ _logFileInitialized = false;
2811
+ try {
2812
+ fs9__namespace.default.mkdirSync(path10__namespace.default.dirname(filePath), { recursive: true });
2813
+ fs9__namespace.default.writeFileSync(
2814
+ filePath,
2815
+ `# tailwind-styled build log \u2014 ${(/* @__PURE__ */ new Date()).toISOString()}
2816
+ `,
2817
+ "utf-8"
2818
+ );
2819
+ _logFileInitialized = true;
2820
+ } catch {
2821
+ }
2822
+ }
2823
+ function writeToFile(line) {
2824
+ if (!_globalLogFile || !_logFileInitialized) return;
2825
+ try {
2826
+ fs9__namespace.default.appendFileSync(_globalLogFile, line);
2827
+ } catch {
2828
+ }
2829
+ }
2830
+ function createLogger(prefix, level) {
2831
+ const loggerState = {
2832
+ currentLevel: getEnvLevel(),
2833
+ setLevel(l) {
2834
+ this.currentLevel = l;
2835
+ }
2836
+ };
2837
+ const log4 = (msgLevel, stream, args) => {
2838
+ if (LEVELS[msgLevel] > LEVELS[loggerState.currentLevel]) return;
2839
+ const line = `[${prefix}] ${args.map(String).join(" ")}
2840
+ `;
2841
+ process[stream].write(line);
2842
+ writeToFile(line);
2843
+ };
2844
+ return {
2845
+ error: (...a) => log4("error", "stderr", a),
2846
+ warn: (...a) => log4("warn", "stderr", a),
2847
+ info: (...a) => log4("info", "stdout", a),
2848
+ debug: (...a) => log4("debug", "stderr", a),
2849
+ setLevel: loggerState.setLevel,
2850
+ setLogFile: (filePath) => setGlobalLogFile(filePath)
2851
+ };
2852
+ }
2853
+ var LEVELS, _globalLogFile, _logFileInitialized;
2854
+ var init_logger = __esm({
2855
+ "packages/domain/shared/src/logger.ts"() {
2856
+ LEVELS = { silent: 0, error: 1, warn: 2, info: 3, debug: 4 };
2857
+ _globalLogFile = null;
2858
+ _logFileInitialized = false;
2859
+ createLogger("tailwind-styled");
2860
+ }
2861
+ });
2862
+ function createLogger2(namespace) {
2863
+ const prefix = `[${namespace}]`;
2864
+ return {
2865
+ warn(...args) {
2866
+ process.stderr.write(`${prefix} ${args.map((a) => typeof a === "string" ? a : String(a)).join(" ")}
2867
+ `);
2868
+ },
2869
+ debug(...args) {
2870
+ process.stderr.write(`${prefix} ${args.map((a) => typeof a === "string" ? a : String(a)).join(" ")}
2871
+ `);
2872
+ },
2873
+ error(...args) {
2874
+ process.stderr.write(`${prefix} ${args.map((a) => typeof a === "string" ? a : String(a)).join(" ")}
2875
+ `);
2876
+ },
2877
+ log(...args) {
2878
+ process.stderr.write(`${prefix} ${args.map((a) => typeof a === "string" ? a : String(a)).join(" ")}
2879
+ `);
2880
+ }
2881
+ };
2882
+ }
2883
+ function createDebugLogger(namespace, label) {
2884
+ const prefix = `[${namespace}]`;
2885
+ return (msg) => {
2886
+ if (process.env.DEBUG?.includes(namespace) || process.env.TW_DEBUG) {
2887
+ console.debug(prefix, msg);
2888
+ }
2889
+ };
2890
+ }
2891
+ function formatIssuePath(path11) {
2892
+ if (!path11 || path11.length === 0) return "(root)";
2893
+ return path11.map(
2894
+ (segment) => typeof segment === "symbol" ? segment.description ?? segment.toString() : String(segment)
2895
+ ).join(".");
2896
+ }
2897
+ function loadNativeBinding(options) {
2898
+ const { runtimeDir, candidates, isValid } = options;
2899
+ const loadErrors = [];
2900
+ for (const candidate of candidates) {
2901
+ const candidatePath = path10__namespace.default.resolve(runtimeDir, candidate);
2902
+ try {
2903
+ if (!fs9__namespace.default.existsSync(candidatePath) && !fs9__namespace.default.existsSync(candidatePath + ".node")) {
2904
+ continue;
2905
+ }
2906
+ const mod = requireNativeModule(candidatePath);
2907
+ if (mod && isValid(mod)) {
2908
+ return { binding: mod, loadErrors, loadedPath: candidatePath };
2909
+ }
2910
+ loadErrors.push({ path: candidatePath, message: options.invalidExportMessage });
2911
+ } catch (e) {
2912
+ loadErrors.push({ path: candidatePath, message: e instanceof Error ? e.message : String(e) });
2913
+ }
2914
+ }
2915
+ return { binding: null, loadErrors };
2916
+ }
2917
+ function requireNativeModule(p) {
2918
+ return _require2(p);
2919
+ }
2920
+ function resolveNativeBindingCandidates(options) {
2921
+ const {
2922
+ envVarNames = ["TW_NATIVE_PATH", "TWS_NATIVE_PATH"],
2923
+ includeDefaultCandidates = true,
2924
+ enforceNodeExtensionForEnvPath = false
2925
+ } = options;
2926
+ const runtimeDir = options.runtimeDir || process.cwd();
2927
+ const candidates = [];
2928
+ for (const envVar of envVarNames) {
2929
+ const envPath = process.env[envVar];
2930
+ if (envPath) {
2931
+ candidates.push(enforceNodeExtensionForEnvPath && !envPath.endsWith(".node") ? envPath + ".node" : envPath);
2932
+ }
2933
+ }
2934
+ if (!includeDefaultCandidates) return candidates;
2935
+ if (fs9__namespace.default.existsSync(runtimeDir)) {
2936
+ try {
2937
+ for (const entry of fs9__namespace.default.readdirSync(runtimeDir)) {
2938
+ if (entry.endsWith(".node")) candidates.push(entry);
2939
+ }
2940
+ } catch {
2941
+ }
2942
+ }
2943
+ const BINARY_NAMES = ["tailwind-styled-native", "tailwind_styled_parser"];
2944
+ const napiPlatform = process.platform === "linux" && process.arch === "x64" ? "linux-x64-gnu" : process.platform === "linux" && process.arch === "arm64" ? "linux-arm64-gnu" : `${process.platform}-${process.arch}`;
2945
+ for (const bin of BINARY_NAMES) {
2946
+ candidates.push(path10__namespace.default.resolve(runtimeDir, `${bin}.node`));
2947
+ candidates.push(path10__namespace.default.resolve(runtimeDir, `${bin}.${napiPlatform}.node`));
2948
+ candidates.push(path10__namespace.default.resolve(runtimeDir, "..", "native", `${bin}.node`));
2949
+ candidates.push(path10__namespace.default.resolve(runtimeDir, "..", "native", `${bin}.${napiPlatform}.node`));
2950
+ candidates.push(path10__namespace.default.resolve(process.cwd(), "native", `${bin}.node`));
2951
+ candidates.push(path10__namespace.default.resolve(process.cwd(), "native", `${bin}.${napiPlatform}.node`));
2952
+ candidates.push(path10__namespace.default.resolve(runtimeDir, "..", "..", "..", "..", "native", `${bin}.node`));
2953
+ candidates.push(path10__namespace.default.resolve(runtimeDir, "..", "..", "..", "..", "native", `${bin}.${napiPlatform}.node`));
2954
+ candidates.push(path10__namespace.default.resolve(runtimeDir, "..", "..", "..", "native", `${bin}.node`));
2955
+ }
2956
+ return Array.from(new Set(candidates));
2957
+ }
2958
+ function resolveRuntimeDir(dir, importMetaUrl) {
2959
+ try {
2960
+ return path10__namespace.default.dirname(url.fileURLToPath(importMetaUrl));
2961
+ } catch {
2962
+ return process.cwd();
2963
+ }
2964
+ }
2965
+ var TwError, _require2;
2966
+ var init_src2 = __esm({
2967
+ "packages/domain/shared/src/index.ts"() {
2968
+ init_workerResolver();
2969
+ init_native_resolution();
2970
+ init_staticStateExtractor();
2971
+ init_logger();
2972
+ TwError = class _TwError extends Error {
2973
+ /** @deprecated Gunakan source */
2974
+ domain;
2975
+ source;
2976
+ code;
2977
+ originalCause;
2978
+ constructor(domainOrSource, code, message, cause) {
2979
+ super(message);
2980
+ this.name = "TwError";
2981
+ this.domain = domainOrSource;
2982
+ this.source = domainOrSource;
2983
+ this.code = code;
2984
+ this.originalCause = cause;
2985
+ if (Error.captureStackTrace) Error.captureStackTrace(this, _TwError);
2986
+ }
2987
+ static fromIo(code, message) {
2988
+ return new _TwError("io", code, message);
2989
+ }
2990
+ static fromCompile(code, message) {
2991
+ return new _TwError("compile", code, message);
2992
+ }
2993
+ static fromRust(err) {
2994
+ if (err instanceof _TwError) return err;
2995
+ if (err instanceof Error) return new _TwError("rust", "RUST_ERROR", err.message, err);
2996
+ if (err && typeof err === "object") {
2997
+ const e = err;
2998
+ return new _TwError("rust", e.code ?? "RUST_ERROR", e.message ?? String(err), err);
2999
+ }
3000
+ return new _TwError("rust", "RUST_ERROR", String(err), err);
3001
+ }
3002
+ /** Buat TwError dari ZodError — dukung shape Zod v3 (`errors`) dan v4 (`issues`). */
3003
+ static fromZod(err) {
3004
+ const first = err.issues?.[0] ?? err.errors?.[0];
3005
+ const path11 = formatIssuePath(first?.path);
3006
+ const message = first ? `${path11}: ${first.message}` : "Schema validation failed";
3007
+ return new _TwError("validation", "SCHEMA_VALIDATION_FAILED", message, err);
3008
+ }
3009
+ static wrap(source, code, err) {
3010
+ if (err instanceof _TwError) return err;
3011
+ if (err instanceof Error) return new _TwError(source, code, err.message, err);
3012
+ return new _TwError(source, code, String(err), err);
3013
+ }
3014
+ toString() {
3015
+ return `TwError [${this.source}:${this.code}] ${this.message}`;
3016
+ }
3017
+ toJSON() {
3018
+ return { name: this.name, source: this.source, code: this.code, message: this.message };
3019
+ }
3020
+ toCliMessage() {
3021
+ return `[${this.source.toUpperCase()}:${this.code}] ${this.message}`;
3022
+ }
3023
+ };
3024
+ _require2 = module$1.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('next.js', document.baseURI).href)));
3025
+ }
3026
+ });
3027
+
3028
+ // packages/domain/scanner/src/native-bridge.ts
3029
+ var native_bridge_exports = {};
3030
+ __export(native_bridge_exports, {
3031
+ batchExtractClassesNative: () => batchExtractClassesNative2,
3032
+ cachePriorityNative: () => cachePriorityNative,
3033
+ cacheReadNative: () => cacheReadNative,
3034
+ cacheWriteNative: () => cacheWriteNative,
3035
+ collectFilesNative: () => collectFilesNative,
3036
+ computeCacheStatsNative: () => computeCacheStatsNative,
3037
+ extractClassesNative: () => extractClassesNative,
3038
+ generateSubComponentTypesNative: () => generateSubComponentTypesNative,
3039
+ hasNativeScannerBinding: () => hasNativeScannerBinding,
3040
+ hasNativeWatchBinding: () => hasNativeWatchBinding,
3041
+ hashContentNative: () => hashContentNative,
3042
+ isRustCacheAvailable: () => isRustCacheAvailable,
3043
+ pollWatchEventsNative: () => pollWatchEventsNative,
3044
+ pruneStaleEntriesNative: () => pruneStaleEntriesNative,
3045
+ rebuildWorkspaceResultNative: () => rebuildWorkspaceResultNative,
3046
+ resetScannerBridgeCache: () => resetScannerBridgeCache,
3047
+ scanCacheGet: () => scanCacheGet,
3048
+ scanCacheInvalidate: () => scanCacheInvalidate,
3049
+ scanCachePut: () => scanCachePut,
3050
+ scanCacheStats: () => scanCacheStats,
3051
+ scanFileNative: () => scanFileNative2,
3052
+ scanFilesBatchNative: () => scanFilesBatchNative2,
3053
+ scanWorkspaceNative: () => scanWorkspaceNative,
3054
+ startWatchNative: () => startWatchNative,
3055
+ stopWatchNative: () => stopWatchNative
3056
+ });
3057
+ function getDirname() {
3058
+ if (typeof __dirname !== "undefined") {
3059
+ return __dirname;
3060
+ }
3061
+ if (typeof ({ url: (typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('next.js', document.baseURI).href)) }) !== "undefined" && (typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('next.js', document.baseURI).href))) {
3062
+ return path10__namespace.default.dirname(url.fileURLToPath((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('next.js', document.baseURI).href))));
3063
+ }
3064
+ return process.cwd();
3065
+ }
3066
+ function scanWorkspaceNative(root, extensions) {
3067
+ return scannerGetBinding().scanWorkspace(root, extensions ?? null);
3068
+ }
3069
+ function extractClassesNative(source) {
3070
+ const result = scannerGetBinding().extractClassesFromSource?.(source);
3071
+ if (result === null || result === void 0) {
3072
+ throw new TwError(
3073
+ "rust",
3074
+ "SCANNER_EXTRACT_FAILED",
3075
+ "Native extractClassesFromSource returned null/undefined"
3076
+ );
3077
+ }
3078
+ return result;
3079
+ }
3080
+ function hashContentNative(content) {
3081
+ const result = scannerGetBinding().hashFileContent?.(content);
3082
+ if (result === null || result === void 0) {
3083
+ throw new TwError(
3084
+ "rust",
3085
+ "SCANNER_HASH_FAILED",
3086
+ "Native hashFileContent returned null/undefined"
3087
+ );
3088
+ }
3089
+ return result;
3090
+ }
3091
+ function isRustCacheAvailable() {
3092
+ return true;
3093
+ }
3094
+ function hasNativeScannerBinding() {
3095
+ try {
3096
+ scannerBridgeLoader.get();
3097
+ return true;
3098
+ } catch {
3099
+ return false;
3100
+ }
3101
+ }
3102
+ function cacheReadNative(cachePath) {
3103
+ const result = scannerGetBinding().cacheRead?.(cachePath);
3104
+ if (result === null || result === void 0) {
3105
+ throw new TwError(
3106
+ "rust",
3107
+ "SCANNER_CACHE_READ_FAILED",
3108
+ "Native cacheRead returned null/undefined"
3109
+ );
3110
+ }
3111
+ return result;
3112
+ }
3113
+ function cacheWriteNative(cachePath, entries) {
3114
+ const result = scannerGetBinding().cacheWrite?.(cachePath, entries);
3115
+ if (result === null || result === void 0) {
3116
+ throw new TwError(
3117
+ "rust",
3118
+ "SCANNER_CACHE_WRITE_FAILED",
3119
+ "Native cacheWrite returned null/undefined"
3120
+ );
3121
+ }
3122
+ return result;
3123
+ }
3124
+ function cachePriorityNative(mtimeMs, size, cachedMtimeMs, cachedSize, cachedHitCount, cachedLastSeenMs, nowMs = Date.now()) {
3125
+ const result = scannerGetBinding().cachePriority?.(
3126
+ mtimeMs,
3127
+ size,
3128
+ cachedMtimeMs,
3129
+ cachedSize,
3130
+ cachedHitCount,
3131
+ cachedLastSeenMs,
3132
+ nowMs
3133
+ );
3134
+ if (result === null || result === void 0) {
3135
+ throw new TwError(
3136
+ "rust",
3137
+ "SCANNER_CACHE_PRIORITY_FAILED",
3138
+ "Native cachePriority returned null/undefined"
3139
+ );
3140
+ }
3141
+ return result;
3142
+ }
3143
+ function batchExtractClassesNative2(filePaths) {
3144
+ const binding = scannerGetBinding();
3145
+ if (!binding.batchExtractClasses) {
3146
+ throw new Error("FATAL: Native binding 'batchExtractClasses' is required but not available.");
3147
+ }
3148
+ return binding.batchExtractClasses(filePaths) ?? [];
3149
+ }
3150
+ function scanCacheGet(filePath, contentHash) {
3151
+ const binding = scannerGetBinding();
3152
+ if (!binding.scanCacheGet) {
3153
+ throw new Error("FATAL: Native binding 'scanCacheGet' is required but not available.");
3154
+ }
3155
+ return binding.scanCacheGet(filePath, contentHash) ?? null;
3156
+ }
3157
+ function scanCachePut(filePath, contentHash, classes, mtimeMs, size) {
3158
+ const binding = scannerGetBinding();
3159
+ if (!binding.scanCachePut) {
3160
+ throw new Error("FATAL: Native binding 'scanCachePut' is required but not available.");
3161
+ }
3162
+ binding.scanCachePut(filePath, contentHash, classes, mtimeMs, size);
3163
+ }
3164
+ function scanCacheInvalidate(filePath) {
3165
+ const binding = scannerGetBinding();
3166
+ if (!binding.scanCacheInvalidate) {
3167
+ throw new Error("FATAL: Native binding 'scanCacheInvalidate' is required but not available.");
3168
+ }
3169
+ binding.scanCacheInvalidate(filePath);
3170
+ }
3171
+ function scanCacheStats() {
3172
+ const binding = scannerGetBinding();
3173
+ if (!binding.scanCacheStats) {
3174
+ throw new Error("FATAL: Native binding 'scanCacheStats' is required but not available.");
3175
+ }
3176
+ return binding.scanCacheStats();
3177
+ }
3178
+ function scanFileNative2(filePath) {
3179
+ const binding = scannerGetBinding();
3180
+ if (!binding.scanFile) {
3181
+ throw new Error("FATAL: Native binding 'scanFile' is required but not available.");
3182
+ }
3183
+ return binding.scanFile(filePath);
3184
+ }
3185
+ function collectFilesNative(root, extensions, ignoreDirs) {
3186
+ const binding = scannerGetBinding();
3187
+ if (!binding.collectFiles) return null;
3188
+ return binding.collectFiles(root, extensions, ignoreDirs);
3189
+ }
3190
+ function scanFilesBatchNative2(filePaths) {
3191
+ const binding = scannerGetBinding();
3192
+ if (!binding.scanFilesBatch) {
3193
+ return filePaths.map((fp) => {
3194
+ try {
3195
+ const r = binding.scanFile?.(fp);
3196
+ return r ? { file: r.file, classes: r.classes, hash: r.hash ?? "" } : { file: fp, classes: [], hash: "" };
3197
+ } catch {
3198
+ return { file: fp, classes: [], hash: "" };
3199
+ }
3200
+ });
3201
+ }
3202
+ return binding.scanFilesBatch(filePaths);
3203
+ }
3204
+ function generateSubComponentTypesNative(root, outputPath) {
3205
+ const binding = scannerGetBinding();
3206
+ if (!binding.generateSubComponentTypes) return null;
3207
+ return binding.generateSubComponentTypes(root, outputPath ?? null);
3208
+ }
3209
+ function pruneStaleEntriesNative(entries, maxAgeMs, checkExists) {
3210
+ const binding = scannerGetBinding();
3211
+ if (!binding.pruneStaleEntries) return null;
3212
+ return binding.pruneStaleEntries(
3213
+ entries.map((e) => ({ file: e.file, lastSeenMs: e.lastSeenMs ?? 0 })),
3214
+ maxAgeMs ?? null,
3215
+ checkExists ?? null
3216
+ );
3217
+ }
3218
+ function rebuildWorkspaceResultNative(files) {
3219
+ const binding = scannerBridgeLoader.get();
3220
+ if (!binding?.rebuildWorkspaceResult) return null;
3221
+ try {
3222
+ return binding.rebuildWorkspaceResult(files);
3223
+ } catch {
3224
+ return null;
3225
+ }
3226
+ }
3227
+ function computeCacheStatsNative(filesClasses, sizes, top) {
3228
+ const binding = scannerGetBinding();
3229
+ if (!binding.computeCacheStats) return null;
3230
+ return binding.computeCacheStats(filesClasses, sizes, top ?? null);
3231
+ }
3232
+ function startWatchNative(rootDir) {
3233
+ try {
3234
+ const binding = scannerGetBinding();
3235
+ if (!binding.startWatch) return null;
3236
+ return binding.startWatch(rootDir);
3237
+ } catch {
3238
+ return null;
3239
+ }
3240
+ }
3241
+ function pollWatchEventsNative(handleId) {
3242
+ try {
3243
+ const binding = scannerGetBinding();
3244
+ if (!binding.pollWatchEvents) return [];
3245
+ return binding.pollWatchEvents(handleId);
3246
+ } catch {
3247
+ return [];
3248
+ }
3249
+ }
3250
+ function stopWatchNative(handleId) {
3251
+ try {
3252
+ const binding = scannerGetBinding();
3253
+ if (!binding.stopWatch) return false;
3254
+ return binding.stopWatch(handleId);
3255
+ } catch {
3256
+ return false;
3257
+ }
3258
+ }
3259
+ function hasNativeWatchBinding() {
3260
+ try {
3261
+ const binding = scannerGetBinding();
3262
+ return !!(binding.startWatch && binding.pollWatchEvents && binding.stopWatch);
3263
+ } catch {
3264
+ return false;
3265
+ }
3266
+ }
3267
+ var log2, isValidScannerBinding, createScannerBridgeLoader, scannerBridgeLoader, scannerGetBinding, resetScannerBridgeCache;
3268
+ var init_native_bridge = __esm({
3269
+ "packages/domain/scanner/src/native-bridge.ts"() {
3270
+ init_src2();
3271
+ log2 = createDebugLogger("scanner:native");
3272
+ isValidScannerBinding = (module) => {
3273
+ const candidate = module;
3274
+ return !!(candidate && (candidate.scanWorkspace || candidate.extractClassesFromSource || candidate.hashFileContent || candidate.cacheRead || candidate.cacheWrite));
3275
+ };
3276
+ createScannerBridgeLoader = () => {
3277
+ const _state = {
3278
+ binding: void 0,
3279
+ loadError: null,
3280
+ candidatePaths: []
1240
3281
  };
1241
- };
1242
- injectClientDirective = (source) => {
1243
- if (!source.includes('"use client"') && !source.includes("'use client'")) {
1244
- return '"use client";\n' + source;
1245
- }
1246
- return source;
1247
- };
1248
- injectServerOnlyComment = (source) => {
1249
- return `/* @server-only */
1250
- ${source}`;
1251
- };
1252
- analyzeClasses = (filesJson, cwd, flags) => {
1253
- const native = getNativeBridge();
1254
- if (!native?.analyzeClasses) {
1255
- throw new Error("FATAL: Native binding 'analyzeClasses' is required but not available.");
1256
- }
1257
- return native.analyzeClasses(filesJson, cwd, flags);
1258
- };
1259
- generateSafelist = (scanDirs, outputPath, cwd) => {
1260
- const classes = scanProjectUsage(scanDirs, cwd || process.cwd());
1261
- const allClasses = Object.keys(classes).sort();
1262
- if (outputPath) {
1263
- const fs6 = __require("fs");
1264
- fs6.writeFileSync(outputPath, JSON.stringify(allClasses, null, 2));
1265
- }
1266
- return allClasses;
1267
- };
1268
- loadSafelist = (safelistPath) => {
1269
- const fs6 = __require("fs");
1270
- try {
1271
- const content = fs6.readFileSync(safelistPath, "utf-8");
1272
- return JSON.parse(content);
1273
- } catch {
1274
- return [];
1275
- }
1276
- };
1277
- loadTailwindConfig = (cwd = process.cwd()) => {
1278
- const fs6 = __require("fs");
1279
- const path7 = __require("path");
1280
- const configFiles = [
1281
- "tailwind.config.ts",
1282
- "tailwind.config.js",
1283
- "tailwind.config.mjs",
1284
- "tailwind.config.cjs"
1285
- ];
1286
- for (const file of configFiles) {
1287
- const fullPath = path7.join(cwd, file);
1288
- if (fs6.existsSync(fullPath)) {
1289
- const mod = __require(fullPath);
1290
- return mod.default || mod;
3282
+ const throwNativeBindingError = () => {
3283
+ const lines = [
3284
+ "FATAL: Native scanner binding not found.",
3285
+ "",
3286
+ "This package requires the Rust native binding 'tailwind_styled_parser.node'.",
3287
+ "The binding was not found in any of these paths:",
3288
+ ..._state.candidatePaths.map((p) => ` - ${p}`),
3289
+ ""
3290
+ ];
3291
+ if (_state.loadError) {
3292
+ lines.push("Load error:", ` ${_state.loadError}`, "");
1291
3293
  }
1292
- }
1293
- return {};
1294
- };
1295
- getContentPaths = (cwd = process.cwd()) => {
1296
- const path7 = __require("path");
1297
- return {
1298
- content: [
1299
- path7.join(cwd, "src/**/*.{js,ts,jsx,tsx}"),
1300
- path7.join(cwd, "app/**/*.{js,ts,jsx,tsx}"),
1301
- path7.join(cwd, "pages/**/*.{js,ts,jsx,tsx}")
1302
- ]
3294
+ lines.push(
3295
+ "To fix this, run:",
3296
+ " npm run build:rust",
3297
+ "",
3298
+ "This will build the native Rust module from the 'native/' directory.",
3299
+ "If you're using this package in a CI/CD environment, ensure Rust toolchain is installed",
3300
+ "and 'npm run build:rust' is executed before running tests or building."
3301
+ );
3302
+ throw new TwError("rust", "SCANNER_NATIVE_BINDING_NOT_FOUND", lines.join("\n"));
1303
3303
  };
1304
- };
1305
- runLoaderTransform = (ctx) => {
1306
- const { filepath, source, options } = ctx;
1307
- const result = transformSource(source, { filename: filepath, ...options });
1308
- return {
1309
- code: result?.code || "",
1310
- changed: result?.changed || false,
1311
- classes: result?.classes || []
3304
+ const scannerGetBinding2 = () => {
3305
+ const cachedBinding = _state.binding;
3306
+ if (cachedBinding !== void 0) {
3307
+ if (cachedBinding !== null) {
3308
+ return cachedBinding;
3309
+ }
3310
+ return throwNativeBindingError();
3311
+ }
3312
+ const runtimeDir = getDirname();
3313
+ const candidates = resolveNativeBindingCandidates({
3314
+ runtimeDir,
3315
+ includeDefaultCandidates: true
3316
+ });
3317
+ _state.candidatePaths = candidates;
3318
+ const { binding, loadErrors } = loadNativeBinding({
3319
+ runtimeDir,
3320
+ candidates,
3321
+ isValid: isValidScannerBinding,
3322
+ invalidExportMessage: "Module loaded but missing expected scanner binding functions"
3323
+ });
3324
+ if (binding) {
3325
+ log2(`scanner native binding loaded successfully`);
3326
+ _state.binding = binding;
3327
+ return _state.binding;
3328
+ }
3329
+ if (loadErrors.length > 0) {
3330
+ _state.loadError = loadErrors.map((e) => `${e.path}: ${e.message}`).join("; ");
3331
+ }
3332
+ _state.binding = null;
3333
+ return throwNativeBindingError();
1312
3334
  };
1313
- };
1314
- shouldSkipFile = (filepath) => {
1315
- const SKIP_PATHS = ["node_modules", ".next", ".rspack-dist", ".turbo", "dist/", "out/"];
1316
- const skipExtensions = [".css", ".json", ".md", ".txt", ".yaml", ".yml"];
1317
- for (const p of SKIP_PATHS) {
1318
- if (filepath.includes(p)) return true;
1319
- }
1320
- for (const ext of skipExtensions) {
1321
- if (filepath.endsWith(ext)) return true;
1322
- }
1323
- return false;
1324
- };
1325
- fileToRoute = (filepath) => {
1326
- const normalized = filepath.replace(/\\/g, "/");
1327
- if (normalized.includes("/layout.") || normalized.includes("/loading.") || normalized.includes("/error.")) {
1328
- return "__global";
1329
- }
1330
- const pageMatch = normalized.match(/\/app\/(.+?)\/page\.[tj]sx?$/);
1331
- if (pageMatch) return `/${pageMatch[1]}`;
1332
- const rootPage = normalized.match(/\/app\/page\.[tj]sx?$/);
1333
- if (rootPage) return "/";
1334
- return null;
1335
- };
1336
- getAllRoutes = () => {
1337
- const native = getNativeBridge();
1338
- if (!native?.analyzeClasses) {
1339
- throw new Error("FATAL: Native binding 'analyzeClasses' is required but not available.");
1340
- }
1341
- return ["/", "__global"];
1342
- };
1343
- getRouteClasses = (_route) => {
1344
- return /* @__PURE__ */ new Set();
1345
- };
1346
- registerFileClasses = (_filepath, _classes) => {
1347
- };
1348
- registerGlobalClasses = (_classes) => {
1349
- };
1350
- _incrementalEngineInstance = null;
1351
- getIncrementalEngine = () => {
1352
- if (!_incrementalEngineInstance) {
1353
- _incrementalEngineInstance = new IncrementalEngine();
1354
- }
1355
- return _incrementalEngineInstance;
1356
- };
1357
- resetIncrementalEngine = () => {
1358
- _incrementalEngineInstance = null;
1359
- };
1360
- IncrementalEngine = class {
1361
- compile(source) {
1362
- return transformSource(source);
1363
- }
1364
- };
1365
- getBucketEngine = () => {
1366
- const native = getNativeBridge();
1367
- if (!native?.classifyAndSortClasses) {
1368
- throw new Error("FATAL: Native binding 'classifyAndSortClasses' is required but not available.");
1369
- }
1370
3335
  return {
1371
- add: (className) => className,
1372
- get: (_bucket) => []
3336
+ get: scannerGetBinding2,
3337
+ scannerGetBinding: scannerGetBinding2,
3338
+ reset: () => {
3339
+ _state.binding = void 0;
3340
+ _state.loadError = null;
3341
+ _state.candidatePaths = [];
3342
+ }
1373
3343
  };
1374
3344
  };
1375
- resetBucketEngine = () => {
1376
- };
1377
- BucketEngine = class {
1378
- add(className) {
1379
- return className;
1380
- }
1381
- };
1382
- classifyNode = (_node) => {
1383
- const native = getNativeBridge();
1384
- if (!native?.classifyAndSortClasses) {
1385
- throw new Error("FATAL: Native binding 'classifyAndSortClasses' is required but not available.");
1386
- }
1387
- return "unknown";
1388
- };
1389
- detectConflicts = (classes) => {
1390
- const native = getNativeBridge();
1391
- if (!native?.analyzeClassUsage) {
1392
- throw new Error("FATAL: Native binding 'analyzeClassUsage' is required but not available.");
1393
- }
1394
- return [];
1395
- };
1396
- bucketSort = (classes) => {
1397
- return classifyAndSortClasses(classes).map((c) => c.raw ?? c);
1398
- };
3345
+ scannerBridgeLoader = createScannerBridgeLoader();
3346
+ scannerGetBinding = scannerBridgeLoader.get;
3347
+ resetScannerBridgeCache = scannerBridgeLoader.reset;
1399
3348
  }
1400
3349
  });
1401
3350
  var formatIssues = (error) => error.issues.map((issue) => {
@@ -1421,20 +3370,20 @@ var NextAdapterOptionsSchema = zod.z.object({
1421
3370
  var parseNextAdapterOptions = (options) => parseWithSchema(NextAdapterOptionsSchema, options ?? {}, "next adapter options are invalid");
1422
3371
 
1423
3372
  // packages/presentation/next/src/withTailwindStyled.ts
1424
- init_src();
3373
+ init_src2();
1425
3374
 
1426
3375
  // packages/domain/scanner/src/index.ts
1427
- init_src();
3376
+ init_src2();
1428
3377
 
1429
3378
  // packages/domain/scanner/src/cache-native.ts
1430
3379
  init_native_bridge();
1431
3380
  function defaultCachePath(rootDir, cacheDir) {
1432
- const dir = cacheDir ? path5__namespace.default.resolve(rootDir, cacheDir) : path5__namespace.default.join(process.cwd(), ".cache", "tailwind-styled");
1433
- return path5__namespace.default.join(dir, "scanner-cache.json");
3381
+ const dir = cacheDir ? path10__namespace.default.resolve(rootDir, cacheDir) : path10__namespace.default.join(process.cwd(), ".cache", "tailwind-styled");
3382
+ return path10__namespace.default.join(dir, "scanner-cache.json");
1434
3383
  }
1435
3384
  function readCache(rootDir, cacheDir) {
1436
3385
  const cachePath = defaultCachePath(rootDir, cacheDir);
1437
- fs5__namespace.default.mkdirSync(path5__namespace.default.dirname(cachePath), { recursive: true });
3386
+ fs9__namespace.default.mkdirSync(path10__namespace.default.dirname(cachePath), { recursive: true });
1438
3387
  const result = cacheReadNative(cachePath);
1439
3388
  if (!result) return [];
1440
3389
  return result.entries.map((e) => ({
@@ -1449,7 +3398,7 @@ function readCache(rootDir, cacheDir) {
1449
3398
  }
1450
3399
  function writeCache(rootDir, entries, cacheDir) {
1451
3400
  const cachePath = defaultCachePath(rootDir, cacheDir);
1452
- fs5__namespace.default.mkdirSync(path5__namespace.default.dirname(cachePath), { recursive: true });
3401
+ fs9__namespace.default.mkdirSync(path10__namespace.default.dirname(cachePath), { recursive: true });
1453
3402
  const success = cacheWriteNative(cachePath, entries);
1454
3403
  if (!success) {
1455
3404
  throw new Error(
@@ -1473,13 +3422,13 @@ function filePriority(mtimeMs, size, cached, nowMs = Date.now()) {
1473
3422
  init_native_bridge();
1474
3423
 
1475
3424
  // packages/domain/scanner/src/schemas.ts
1476
- init_src();
1477
- var formatIssuePath2 = (path7) => path7.length > 0 ? path7.map(
3425
+ init_src2();
3426
+ var formatIssuePath2 = (path11) => path11.length > 0 ? path11.map(
1478
3427
  (segment) => typeof segment === "symbol" ? segment.description ?? segment.toString() : String(segment)
1479
3428
  ).join(".") : "<root>";
1480
3429
  var formatIssues2 = (error) => error.issues.map((issue) => {
1481
- const path7 = formatIssuePath2(issue.path);
1482
- return `${path7}: ${issue.message}`;
3430
+ const path11 = formatIssuePath2(issue.path);
3431
+ return `${path11}: ${issue.message}`;
1483
3432
  }).join("; ");
1484
3433
  var parseWithSchema2 = (schema, data, label) => {
1485
3434
  const parsed = schema.safeParse(data);
@@ -1533,13 +3482,13 @@ var parseScanWorkspaceOptions = (options) => parseWithSchema2(ScanWorkspaceOptio
1533
3482
  var parseScanWorkspaceResult = (result) => parseWithSchema2(ScanWorkspaceResultSchema, result, "scanner workspace result is invalid");
1534
3483
 
1535
3484
  // packages/domain/scanner/src/index.ts
1536
- var log2 = createLogger("scanner");
3485
+ var log3 = createLogger2("scanner");
1537
3486
  function getRuntimeDir() {
1538
3487
  if (typeof __dirname !== "undefined" && __dirname.length > 0) {
1539
3488
  return __dirname;
1540
3489
  }
1541
3490
  if (typeof ({ url: (typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('next.js', document.baseURI).href)) }) !== "undefined" && (typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('next.js', document.baseURI).href))) {
1542
- return path5__namespace.default.dirname(url.fileURLToPath((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('next.js', document.baseURI).href))));
3491
+ return path10__namespace.default.dirname(url.fileURLToPath((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('next.js', document.baseURI).href))));
1543
3492
  }
1544
3493
  return process.cwd();
1545
3494
  }
@@ -1549,12 +3498,12 @@ var createNativeParserLoader = () => {
1549
3498
  initError: null
1550
3499
  };
1551
3500
  const debugNative = (message) => {
1552
- log2.debug(`[native] ${message}`);
3501
+ log3.debug(`[native] ${message}`);
1553
3502
  };
1554
3503
  const loadNativeParserBinding = () => {
1555
3504
  if (_state.binding !== void 0) return _state.binding;
1556
3505
  const runtimeDir = getRuntimeDir();
1557
- const req = module$1.createRequire(path5__namespace.default.join(runtimeDir, "noop.cjs"));
3506
+ const req = module$1.createRequire(path10__namespace.default.join(runtimeDir, "noop.cjs"));
1558
3507
  const _platform = process.platform;
1559
3508
  const _arch = process.arch;
1560
3509
  const _platformArch = `${_platform}-${_arch}`;
@@ -1562,27 +3511,27 @@ var createNativeParserLoader = () => {
1562
3511
  const candidates = [
1563
3512
  // ── binaryName baru: tailwind-styled-native (napi-rs naming) ──
1564
3513
  // cwd = repo root saat run dari root, atau package dir saat workspaces
1565
- path5__namespace.default.resolve(process.cwd(), "native", "tailwind-styled-native.node"),
1566
- path5__namespace.default.resolve(process.cwd(), "native", `tailwind-styled-native.${_platformArch}.node`),
1567
- path5__namespace.default.resolve(process.cwd(), "native", `tailwind-styled-native.${_platformArchGnu}.node`),
3514
+ path10__namespace.default.resolve(process.cwd(), "native", "tailwind-styled-native.node"),
3515
+ path10__namespace.default.resolve(process.cwd(), "native", `tailwind-styled-native.${_platformArch}.node`),
3516
+ path10__namespace.default.resolve(process.cwd(), "native", `tailwind-styled-native.${_platformArchGnu}.node`),
1568
3517
  // runtimeDir = dist/ → naik 1 level ke package root (npm install case)
1569
3518
  // e.g. node_modules/tailwind-styled-v4/dist/ → node_modules/tailwind-styled-v4/native/
1570
- path5__namespace.default.resolve(runtimeDir, "..", "native", "tailwind-styled-native.node"),
1571
- path5__namespace.default.resolve(runtimeDir, "..", "native", `tailwind-styled-native.${_platformArch}.node`),
1572
- path5__namespace.default.resolve(runtimeDir, "..", "native", `tailwind-styled-native.${_platformArchGnu}.node`),
3519
+ path10__namespace.default.resolve(runtimeDir, "..", "native", "tailwind-styled-native.node"),
3520
+ path10__namespace.default.resolve(runtimeDir, "..", "native", `tailwind-styled-native.${_platformArch}.node`),
3521
+ path10__namespace.default.resolve(runtimeDir, "..", "native", `tailwind-styled-native.${_platformArchGnu}.node`),
1573
3522
  // runtimeDir = dist/ → naik 4 level ke repo root (monorepo dev case)
1574
- path5__namespace.default.resolve(runtimeDir, "..", "..", "..", "..", "native", "tailwind-styled-native.node"),
1575
- path5__namespace.default.resolve(runtimeDir, "..", "..", "..", "..", "native", `tailwind-styled-native.${_platformArchGnu}.node`),
3523
+ path10__namespace.default.resolve(runtimeDir, "..", "..", "..", "..", "native", "tailwind-styled-native.node"),
3524
+ path10__namespace.default.resolve(runtimeDir, "..", "..", "..", "..", "native", `tailwind-styled-native.${_platformArchGnu}.node`),
1576
3525
  // 3 level fallback (jika package di-nest lebih dangkal)
1577
- path5__namespace.default.resolve(runtimeDir, "..", "..", "..", "native", "tailwind-styled-native.node"),
1578
- path5__namespace.default.resolve(runtimeDir, "..", "..", "..", "native", `tailwind-styled-native.${_platformArchGnu}.node`),
3526
+ path10__namespace.default.resolve(runtimeDir, "..", "..", "..", "native", "tailwind-styled-native.node"),
3527
+ path10__namespace.default.resolve(runtimeDir, "..", "..", "..", "native", `tailwind-styled-native.${_platformArchGnu}.node`),
1579
3528
  // ── binaryName lama: tailwind_styled_parser (backward compat) ──
1580
- path5__namespace.default.resolve(process.cwd(), "native/tailwind_styled_parser.node"),
1581
- path5__namespace.default.resolve(process.cwd(), "native/build/Release/tailwind_styled_parser.node"),
1582
- path5__namespace.default.resolve(runtimeDir, "..", "native", "tailwind_styled_parser.node"),
1583
- path5__namespace.default.resolve(runtimeDir, "..", "..", "..", "..", "native", "tailwind_styled_parser.node"),
1584
- path5__namespace.default.resolve(runtimeDir, "..", "..", "..", "native", "tailwind_styled_parser.node"),
1585
- path5__namespace.default.resolve(
3529
+ path10__namespace.default.resolve(process.cwd(), "native/tailwind_styled_parser.node"),
3530
+ path10__namespace.default.resolve(process.cwd(), "native/build/Release/tailwind_styled_parser.node"),
3531
+ path10__namespace.default.resolve(runtimeDir, "..", "native", "tailwind_styled_parser.node"),
3532
+ path10__namespace.default.resolve(runtimeDir, "..", "..", "..", "..", "native", "tailwind_styled_parser.node"),
3533
+ path10__namespace.default.resolve(runtimeDir, "..", "..", "..", "native", "tailwind_styled_parser.node"),
3534
+ path10__namespace.default.resolve(
1586
3535
  runtimeDir,
1587
3536
  "..",
1588
3537
  "..",
@@ -1594,7 +3543,7 @@ var createNativeParserLoader = () => {
1594
3543
  )
1595
3544
  ];
1596
3545
  for (const fullPath of candidates) {
1597
- if (!fs5__namespace.default.existsSync(fullPath)) continue;
3546
+ if (!fs9__namespace.default.existsSync(fullPath)) continue;
1598
3547
  try {
1599
3548
  const required = req(fullPath);
1600
3549
  if (required && (typeof required.extractClassesFromSource === "function" || typeof required.parseClasses === "function" || typeof required.parse_classes === "function")) {
@@ -1635,19 +3584,19 @@ function collectCandidates(rootDir, ignoreDirectories, extensionSet) {
1635
3584
  if (!currentDir) continue;
1636
3585
  const entries = (() => {
1637
3586
  try {
1638
- return fs5__namespace.default.readdirSync(currentDir, { withFileTypes: true });
3587
+ return fs9__namespace.default.readdirSync(currentDir, { withFileTypes: true });
1639
3588
  } catch {
1640
3589
  return [];
1641
3590
  }
1642
3591
  })();
1643
3592
  for (const entry of entries) {
1644
- const fullPath = path5__namespace.default.join(currentDir, entry.name);
3593
+ const fullPath = path10__namespace.default.join(currentDir, entry.name);
1645
3594
  if (entry.isDirectory()) {
1646
3595
  if (!ignoreDirectories.has(entry.name)) directories.push(fullPath);
1647
3596
  continue;
1648
3597
  }
1649
3598
  if (!entry.isFile()) continue;
1650
- if (!extensionSet.has(path5__namespace.default.extname(entry.name))) continue;
3599
+ if (!extensionSet.has(path10__namespace.default.extname(entry.name))) continue;
1651
3600
  candidates.push(fullPath);
1652
3601
  }
1653
3602
  }
@@ -1673,9 +3622,9 @@ function scanSource(source) {
1673
3622
  "FATAL: Native parser binding is required but not available.\nThis package requires native Rust bindings.\n\nResolution steps:\n1. Build the native Rust module: npm run build:rust"
1674
3623
  );
1675
3624
  }
1676
- function scanFile(filePath) {
1677
- const { scanFileNative: scanFileNative2 } = (init_native_bridge(), __toCommonJS(native_bridge_exports));
1678
- const result = scanFileNative2(filePath);
3625
+ function scanFile2(filePath) {
3626
+ const { scanFileNative: scanFileNative3 } = (init_native_bridge(), __toCommonJS(native_bridge_exports));
3627
+ const result = scanFileNative3(filePath);
1679
3628
  if (!result.ok) {
1680
3629
  throw new Error(`scanFile failed for ${filePath}: ${result.error ?? "unknown error"}`);
1681
3630
  }
@@ -1685,7 +3634,7 @@ function scanFile(filePath) {
1685
3634
  ...result.hash ? { hash: result.hash } : {}
1686
3635
  };
1687
3636
  }
1688
- function scanWorkspace(rootDir, options = {}) {
3637
+ function scanWorkspace2(rootDir, options = {}) {
1689
3638
  const normalizedOptions = parseScanWorkspaceOptions(options);
1690
3639
  const includeExtensions = normalizedOptions.includeExtensions ?? DEFAULT_EXTENSIONS;
1691
3640
  const extensionSet = buildExtensionSet(includeExtensions);
@@ -1719,7 +3668,7 @@ function scanWorkspace(rootDir, options = {}) {
1719
3668
  try {
1720
3669
  return readCache(rootDir, normalizedOptions.cacheDir);
1721
3670
  } catch (error) {
1722
- log2.debug(
3671
+ log3.debug(
1723
3672
  `cache read failed, continuing without persisted cache: ${error instanceof Error ? error.message : String(error)}`
1724
3673
  );
1725
3674
  return [];
@@ -1731,7 +3680,7 @@ function scanWorkspace(rootDir, options = {}) {
1731
3680
  for (const filePath of candidates) {
1732
3681
  const stat = (() => {
1733
3682
  try {
1734
- return fs5__namespace.default.statSync(filePath);
3683
+ return fs9__namespace.default.statSync(filePath);
1735
3684
  } catch {
1736
3685
  return null;
1737
3686
  }
@@ -1757,7 +3706,7 @@ function scanWorkspace(rootDir, options = {}) {
1757
3706
  for (const { filePath, stat, size, cached } of ranked) {
1758
3707
  const content = (() => {
1759
3708
  try {
1760
- return fs5__namespace.default.readFileSync(filePath, "utf8");
3709
+ return fs9__namespace.default.readFileSync(filePath, "utf8");
1761
3710
  } catch {
1762
3711
  return null;
1763
3712
  }
@@ -1765,7 +3714,7 @@ function scanWorkspace(rootDir, options = {}) {
1765
3714
  if (!content) continue;
1766
3715
  const hash = hashContentNative(content);
1767
3716
  if (cached && cached.hash === hash && cached.mtimeMs === stat.mtimeMs && cached.size === size) {
1768
- log2.debug(`cache HIT ${filePath}`);
3717
+ log3.debug(`cache HIT ${filePath}`);
1769
3718
  processResult({ file: filePath, classes: cached.classes });
1770
3719
  updatedEntries.push({
1771
3720
  file: filePath,
@@ -1777,7 +3726,7 @@ function scanWorkspace(rootDir, options = {}) {
1777
3726
  });
1778
3727
  continue;
1779
3728
  }
1780
- log2.debug(`cache MISS ${filePath}`);
3729
+ log3.debug(`cache MISS ${filePath}`);
1781
3730
  const classes = scanSource(content);
1782
3731
  processResult({ file: filePath, classes });
1783
3732
  updatedEntries.push({
@@ -1792,7 +3741,7 @@ function scanWorkspace(rootDir, options = {}) {
1792
3741
  try {
1793
3742
  writeCache(rootDir, updatedEntries, normalizedOptions.cacheDir);
1794
3743
  } catch (error) {
1795
- log2.debug(`cache write failed: ${error instanceof Error ? error.message : String(error)}`);
3744
+ log3.debug(`cache write failed: ${error instanceof Error ? error.message : String(error)}`);
1796
3745
  }
1797
3746
  return parseScanWorkspaceResult({
1798
3747
  files,
@@ -1808,7 +3757,7 @@ function scanWorkspace(rootDir, options = {}) {
1808
3757
  }
1809
3758
  } else {
1810
3759
  for (const filePath of candidates) {
1811
- processResult(scanFile(filePath));
3760
+ processResult(scanFile2(filePath));
1812
3761
  }
1813
3762
  }
1814
3763
  return parseScanWorkspaceResult({
@@ -1818,6 +3767,60 @@ function scanWorkspace(rootDir, options = {}) {
1818
3767
  });
1819
3768
  }
1820
3769
 
3770
+ // packages/presentation/next/src/withTailwindStyled.ts
3771
+ init_src2();
3772
+ var _fileStaticCssMap = /* @__PURE__ */ new Map();
3773
+ function setFileStaticCss(filepath, css) {
3774
+ if (css && css.trim()) {
3775
+ _fileStaticCssMap.set(filepath, css.trim());
3776
+ } else {
3777
+ _fileStaticCssMap.delete(filepath);
3778
+ }
3779
+ }
3780
+ function buildContent(map) {
3781
+ const seen = /* @__PURE__ */ new Set();
3782
+ const rules = [];
3783
+ for (const css of map.values()) {
3784
+ for (const chunk of css.split(/(?<=\})\s*/)) {
3785
+ const rule = chunk.trim();
3786
+ if (rule && !seen.has(rule)) {
3787
+ seen.add(rule);
3788
+ rules.push(rule);
3789
+ }
3790
+ }
3791
+ }
3792
+ return rules.join("\n");
3793
+ }
3794
+ var HEADER = `/* _tw-state-static.css \u2014 Auto-generated by tailwind-styled-v4. DO NOT EDIT.
3795
+ * Import di globals.css: @import "./_tw-state-static.css";
3796
+ * Berisi: state CSS (.tw-s-*[data-*="true"]) + container queries (@container .tw-cq-*).
3797
+ * Di-rebuild penuh setiap webpack compilation selesai \u2014 tidak ada stale rules.
3798
+ */
3799
+
3800
+ `;
3801
+ var StaticCssWebpackPlugin = class _StaticCssWebpackPlugin {
3802
+ static PLUGIN_NAME = "TailwindStyledStaticCss";
3803
+ outPath;
3804
+ constructor(safelistPath) {
3805
+ this.outPath = path10__namespace.default.join(path10__namespace.default.dirname(safelistPath), "_tw-state-static.css");
3806
+ }
3807
+ apply(compiler) {
3808
+ compiler.hooks.done.tap(_StaticCssWebpackPlugin.PLUGIN_NAME, () => {
3809
+ try {
3810
+ const content = buildContent(_fileStaticCssMap);
3811
+ fs9__namespace.default.mkdirSync(path10__namespace.default.dirname(this.outPath), { recursive: true });
3812
+ fs9__namespace.default.writeFileSync(
3813
+ this.outPath,
3814
+ HEADER + (content || "/* no static rules yet */") + "\n",
3815
+ "utf-8"
3816
+ );
3817
+ } catch (e) {
3818
+ console.warn("[tailwind-styled] Could not write _tw-state-static.css:", e);
3819
+ }
3820
+ });
3821
+ }
3822
+ };
3823
+
1821
3824
  // packages/presentation/next/src/withTailwindStyled.ts
1822
3825
  function getDirnameFromUrl2(importMetaUrl) {
1823
3826
  if (typeof importMetaUrl !== "string") return "";
@@ -1840,12 +3843,12 @@ var resolveLoaderPath2 = (basename) => {
1840
3843
  } catch {
1841
3844
  const runtimeDir = resolveRuntimeDir2();
1842
3845
  const candidates = [
1843
- path5__namespace.default.resolve(runtimeDir, `${basename}.mjs`),
1844
- path5__namespace.default.resolve(runtimeDir, `${basename}.js`),
1845
- path5__namespace.default.resolve(runtimeDir, `${basename}.cjs`)
3846
+ path10__namespace.default.resolve(runtimeDir, `${basename}.mjs`),
3847
+ path10__namespace.default.resolve(runtimeDir, `${basename}.js`),
3848
+ path10__namespace.default.resolve(runtimeDir, `${basename}.cjs`)
1846
3849
  ];
1847
3850
  for (const candidate of candidates) {
1848
- if (fs5__namespace.default.existsSync(candidate)) {
3851
+ if (fs9__namespace.default.existsSync(candidate)) {
1849
3852
  return candidate;
1850
3853
  }
1851
3854
  }
@@ -1869,7 +3872,7 @@ function checkNextVersion() {
1869
3872
  }
1870
3873
  var DEFAULT_INCLUDE = /\.[jt]sx?$/;
1871
3874
  var DEFAULT_EXCLUDE = /node_modules/;
1872
- var NEXT_RSC_ENTRIES = /(?:^|[\\/])(?:layout|page|loading|error|not-found|template|default)\.[jt]sx?$/;
3875
+ var NEXT_RSC_ENTRIES = /(?:^|[\\\/])(?:layout|page|loading|error|not-found|template|default)\.[jt]sx?$/;
1873
3876
  var buildExcludePattern = (userExclude) => {
1874
3877
  if (!userExclude) return new RegExp(`(?:${DEFAULT_EXCLUDE.source})|(?:${NEXT_RSC_ENTRIES.source})`);
1875
3878
  return new RegExp(`(?:${userExclude.source})|(?:${NEXT_RSC_ENTRIES.source})`);
@@ -1883,7 +3886,7 @@ var createLoaderOptions = (options) => {
1883
3886
  preserveImports: true
1884
3887
  };
1885
3888
  if (options.verbose !== void 0) opts.verbose = options.verbose;
1886
- opts.safelistPath = options.safelistPath ?? path5__namespace.default.join(process.cwd(), ".next", "tailwind-styled-safelist.css");
3889
+ opts.safelistPath = options.safelistPath ?? path10__namespace.default.join(process.cwd(), ".next", "tailwind-styled-safelist.css");
1887
3890
  return Object.freeze(opts);
1888
3891
  };
1889
3892
  var buildTurbopackRules = (loaderPath, loaderOptions) => {
@@ -1896,7 +3899,7 @@ var buildTurbopackRules = (loaderPath, loaderOptions) => {
1896
3899
  ])
1897
3900
  );
1898
3901
  };
1899
- var normalizeLoaderPath = (loaderPath) => path5__namespace.default.resolve(loaderPath);
3902
+ var normalizeLoaderPath = (loaderPath) => path10__namespace.default.resolve(loaderPath);
1900
3903
  var applyWebpackRule = (config, options, loaderPath) => {
1901
3904
  const loaderOptions = createLoaderOptions(options);
1902
3905
  const rules = config.module?.rules ?? [];
@@ -1909,16 +3912,20 @@ var applyWebpackRule = (config, options, loaderPath) => {
1909
3912
  if (alreadyRegistered) return config;
1910
3913
  const tailwindStyledRule = {
1911
3914
  test: options.include ?? DEFAULT_INCLUDE,
1912
- // Selalu kecualikan Next.js RSC entry files (layout, page, dll) bahkan jika
1913
- // user menyuplai exclude pattern sendiri — lihat buildExcludePattern.
1914
3915
  exclude: buildExcludePattern(options.exclude),
1915
3916
  enforce: "pre",
1916
3917
  use: [{ loader: loaderPath, options: loaderOptions }]
1917
3918
  };
3919
+ const safelistPath = loaderOptions.safelistPath ?? path10__namespace.default.join(process.cwd(), ".next", "tailwind-styled-safelist.css");
3920
+ const pluginAlreadyRegistered = (config.plugins ?? []).some(
3921
+ (p) => p?.constructor?.name === StaticCssWebpackPlugin.PLUGIN_NAME
3922
+ );
3923
+ const plugins = pluginAlreadyRegistered ? config.plugins ?? [] : [...config.plugins ?? [], new StaticCssWebpackPlugin(safelistPath)];
1918
3924
  config.module = {
1919
3925
  ...config.module ?? {},
1920
3926
  rules: [...rules, tailwindStyledRule]
1921
3927
  };
3928
+ config.plugins = plugins;
1922
3929
  const externalPackages = [
1923
3930
  "tailwind-styled-v4",
1924
3931
  "@tailwind-styled/shared",
@@ -2009,36 +4016,85 @@ function withTailwindStyled(options = {}) {
2009
4016
  return fullCss.slice(startIdx, endIdx + 1);
2010
4017
  };
2011
4018
  var extractUtilitiesLayer = extractUtilitiesLayer2;
2012
- const twClassesDir = path5__namespace.default.join(path5__namespace.default.dirname(safelistPath), "tw-classes");
2013
- fs5__namespace.default.mkdirSync(twClassesDir, { recursive: true });
2014
- fs5__namespace.default.writeFileSync(
2015
- path5__namespace.default.join(twClassesDir, "_start.txt"),
4019
+ const twClassesDir = path10__namespace.default.join(path10__namespace.default.dirname(safelistPath), "tw-classes");
4020
+ fs9__namespace.default.mkdirSync(twClassesDir, { recursive: true });
4021
+ setGlobalLogFile(path10__namespace.default.join(twClassesDir, "_tw-build.log"));
4022
+ fs9__namespace.default.writeFileSync(
4023
+ path10__namespace.default.join(twClassesDir, "_start.txt"),
2016
4024
  String(Date.now()),
2017
4025
  "utf-8"
2018
4026
  );
4027
+ const stateStaticPath = path10__namespace.default.join(twClassesDir, TW_STATE_STATIC_FILENAME);
4028
+ if (!fs9__namespace.default.existsSync(stateStaticPath)) {
4029
+ fs9__namespace.default.writeFileSync(
4030
+ stateStaticPath,
4031
+ "/* tw-state-static.css \u2014 placeholder, akan di-generate setelah scan */\n",
4032
+ "utf-8"
4033
+ );
4034
+ }
4035
+ try {
4036
+ const CSS_CANDIDATES = [
4037
+ "src/app/globals.css",
4038
+ "src/globals.css",
4039
+ "src/styles/globals.css",
4040
+ "src/tailwind.css",
4041
+ "src/index.css",
4042
+ "styles/globals.css"
4043
+ ];
4044
+ const safelistDir = path10__namespace.default.dirname(safelistPath);
4045
+ for (const candidate of CSS_CANDIDATES) {
4046
+ const candidatePath = path10__namespace.default.join(process.cwd(), candidate);
4047
+ if (!fs9__namespace.default.existsSync(candidatePath)) continue;
4048
+ const content = fs9__namespace.default.readFileSync(candidatePath, "utf-8");
4049
+ if (content.includes("_tw-state-static.css")) break;
4050
+ const globalsDir = path10__namespace.default.dirname(candidatePath);
4051
+ const rel = path10__namespace.default.relative(globalsDir, stateStaticPath).replace(/\\/g, "/");
4052
+ const importLine = `@import "./${rel}";`;
4053
+ const tailwindImportRe = /(@import\s+["']tailwindcss["']\s*;[^\n]*\n?)/;
4054
+ let updated;
4055
+ if (tailwindImportRe.test(content)) {
4056
+ updated = content.replace(
4057
+ tailwindImportRe,
4058
+ `$1${importLine}
4059
+ `
4060
+ );
4061
+ } else {
4062
+ updated = `${importLine}
4063
+ ${content}`;
4064
+ }
4065
+ fs9__namespace.default.writeFileSync(candidatePath, updated, "utf-8");
4066
+ if (options.verbose) {
4067
+ console.log(
4068
+ `[tailwind-styled] Auto-injected "${importLine}" into ${candidate}`
4069
+ );
4070
+ }
4071
+ break;
4072
+ }
4073
+ } catch {
4074
+ }
2019
4075
  if (!process.env.TW_NATIVE_PATH) {
2020
4076
  const runtimeDir = resolveRuntimeDir2();
2021
- const nativePath = path5__namespace.default.resolve(runtimeDir, "..", "native", "tailwind-styled-native.node");
2022
- if (fs5__namespace.default.existsSync(nativePath)) {
4077
+ const nativePath = path10__namespace.default.resolve(runtimeDir, "..", "native", "tailwind-styled-native.node");
4078
+ if (fs9__namespace.default.existsSync(nativePath)) {
2023
4079
  process.env.TW_NATIVE_PATH = nativePath;
2024
4080
  }
2025
4081
  }
2026
- const srcDir = path5__namespace.default.join(process.cwd(), "src");
2027
- if (fs5__namespace.default.existsSync(srcDir)) {
4082
+ const srcDir = path10__namespace.default.join(process.cwd(), "src");
4083
+ if (fs9__namespace.default.existsSync(srcDir)) {
2028
4084
  try {
2029
- const result = scanWorkspace(srcDir);
4085
+ const result = scanWorkspace2(srcDir);
2030
4086
  if (result.uniqueClasses.length > 0) {
2031
4087
  let atomicWriteFile2 = function(filePath, content) {
2032
4088
  const tmpPath = `${filePath}.tmp`;
2033
4089
  try {
2034
- fs5__namespace.default.writeFileSync(tmpPath, content, "utf-8");
2035
- fs5__namespace.default.renameSync(tmpPath, filePath);
4090
+ fs9__namespace.default.writeFileSync(tmpPath, content, "utf-8");
4091
+ fs9__namespace.default.renameSync(tmpPath, filePath);
2036
4092
  } catch {
2037
4093
  try {
2038
- fs5__namespace.default.unlinkSync(tmpPath);
4094
+ fs9__namespace.default.unlinkSync(tmpPath);
2039
4095
  } catch {
2040
4096
  }
2041
- fs5__namespace.default.writeFileSync(filePath, content, "utf-8");
4097
+ fs9__namespace.default.writeFileSync(filePath, content, "utf-8");
2042
4098
  }
2043
4099
  };
2044
4100
  var atomicWriteFile = atomicWriteFile2;
@@ -2101,14 +4157,14 @@ function withTailwindStyled(options = {}) {
2101
4157
  "styles/globals.css"
2102
4158
  ];
2103
4159
  try {
2104
- const twConfigPath = path5__namespace.default.join(process.cwd(), "tailwind-styled.config.json");
2105
- if (fs5__namespace.default.existsSync(twConfigPath)) {
2106
- const twConfig = JSON.parse(fs5__namespace.default.readFileSync(twConfigPath, "utf-8"));
4160
+ const twConfigPath = path10__namespace.default.join(process.cwd(), "tailwind-styled.config.json");
4161
+ if (fs9__namespace.default.existsSync(twConfigPath)) {
4162
+ const twConfig = JSON.parse(fs9__namespace.default.readFileSync(twConfigPath, "utf-8"));
2107
4163
  const cssEntry = twConfig.css?.entry;
2108
4164
  if (cssEntry) {
2109
- const cssEntryPath = path5__namespace.default.join(process.cwd(), cssEntry);
2110
- if (fs5__namespace.default.existsSync(cssEntryPath)) {
2111
- cssEntryContent = fs5__namespace.default.readFileSync(cssEntryPath, "utf-8");
4165
+ const cssEntryPath = path10__namespace.default.join(process.cwd(), cssEntry);
4166
+ if (fs9__namespace.default.existsSync(cssEntryPath)) {
4167
+ cssEntryContent = fs9__namespace.default.readFileSync(cssEntryPath, "utf-8");
2112
4168
  }
2113
4169
  }
2114
4170
  }
@@ -2116,9 +4172,9 @@ function withTailwindStyled(options = {}) {
2116
4172
  }
2117
4173
  if (!cssEntryContent) {
2118
4174
  for (const candidate of CSS_CANDIDATES) {
2119
- const candidatePath = path5__namespace.default.join(process.cwd(), candidate);
2120
- if (fs5__namespace.default.existsSync(candidatePath)) {
2121
- cssEntryContent = fs5__namespace.default.readFileSync(candidatePath, "utf-8");
4175
+ const candidatePath = path10__namespace.default.join(process.cwd(), candidate);
4176
+ if (fs9__namespace.default.existsSync(candidatePath)) {
4177
+ cssEntryContent = fs9__namespace.default.readFileSync(candidatePath, "utf-8");
2122
4178
  break;
2123
4179
  }
2124
4180
  }
@@ -2126,8 +4182,8 @@ function withTailwindStyled(options = {}) {
2126
4182
  if (cssEntryContent) {
2127
4183
  cssEntryContent = cssEntryContent.replace(/@source\s+["'][^"']+["']\s*;?\s*/g, "").replace(/←[^\n]*/g, "").trim();
2128
4184
  }
2129
- const initialScanPath = path5__namespace.default.join(twClassesDir, "_initial-scan.css");
2130
- if (!fs5__namespace.default.existsSync(initialScanPath)) {
4185
+ const initialScanPath = path10__namespace.default.join(twClassesDir, "_initial-scan.css");
4186
+ if (!fs9__namespace.default.existsSync(initialScanPath)) {
2131
4187
  atomicWriteFile2(
2132
4188
  initialScanPath,
2133
4189
  "/* tw-classes: initial scan \u2014 generating... */\n@layer utilities {}\n"
@@ -2135,7 +4191,7 @@ function withTailwindStyled(options = {}) {
2135
4191
  }
2136
4192
  void (async () => {
2137
4193
  try {
2138
- const compiler = await Promise.resolve().then(() => (init_src2(), src_exports));
4194
+ const compiler = await Promise.resolve().then(() => (init_src(), src_exports));
2139
4195
  const generateCssForClasses2 = compiler.generateCssForClasses;
2140
4196
  const css = await generateCssForClasses2(
2141
4197
  filteredClasses,
@@ -2152,25 +4208,36 @@ function withTailwindStyled(options = {}) {
2152
4208
  `/* tw-classes: initial scan \u2014 auto-generated by withTailwindStyled */
2153
4209
  ${utilitiesOnly}`
2154
4210
  );
4211
+ const summary = appendStaticStateCssToSafelist(srcDir, safelistPath, {
4212
+ verbose: options.verbose ?? false,
4213
+ resolvedCss: css
4214
+ });
4215
+ if (options.verbose) console.log(summary);
2155
4216
  }
2156
4217
  } catch (err) {
2157
- console.warn("[tailwind-styled] generateCssForClasses gagal, fallback ke empty rules:", err.message?.split("\n")[0]);
2158
- const css = [
2159
- "/* tw-safelist: initial scan \u2014 auto-generated by withTailwindStyled (fallback) */",
2160
- "@layer utilities {",
2161
- filteredClasses.map((cls) => `.${cls.replace(/([^a-zA-Z0-9_-])/g, "\\$1")} {}`).join("\n"),
2162
- "}"
2163
- ].join("\n");
2164
- atomicWriteFile2(initialScanPath, css);
4218
+ throw new Error(
4219
+ `[tailwind-styled] generateCssForClasses gagal \u2014 build-time CSS generation wajib berhasil.
4220
+ ${err.message}`,
4221
+ { cause: err }
4222
+ );
2165
4223
  }
2166
4224
  })();
2167
4225
  }
2168
4226
  } catch (e) {
2169
- console.warn("[tailwind-styled] Initial scan skipped:", e.message?.split("\n")[0]);
4227
+ throw new Error(
4228
+ `[tailwind-styled] Scanner gagal \u2014 Rust native binary tidak tersedia. Build tidak bisa dilanjutkan.
4229
+ ${e.message}`,
4230
+ { cause: e }
4231
+ );
2170
4232
  }
2171
4233
  }
2172
4234
  }
2173
- } catch {
4235
+ } catch (err) {
4236
+ throw new Error(
4237
+ `[tailwind-styled] Build-time CSS generation gagal.
4238
+ ${err.message}`,
4239
+ { cause: err }
4240
+ );
2174
4241
  }
2175
4242
  return {
2176
4243
  ...nextConfig,
@@ -2238,7 +4305,9 @@ ${utilitiesOnly}`
2238
4305
  }
2239
4306
 
2240
4307
  exports.NextAdapterOptionsSchema = NextAdapterOptionsSchema;
4308
+ exports.StaticCssWebpackPlugin = StaticCssWebpackPlugin;
2241
4309
  exports.parseNextAdapterOptions = parseNextAdapterOptions;
4310
+ exports.setFileStaticCss = setFileStaticCss;
2242
4311
  exports.withTailwindStyled = withTailwindStyled;
2243
4312
  //# sourceMappingURL=next.js.map
2244
4313
  //# sourceMappingURL=next.js.map