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