tailwind-styled-v4 5.0.10 → 5.0.11

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 (93) hide show
  1. package/README.md +245 -373
  2. package/dist/analyzer.js +75 -22
  3. package/dist/analyzer.js.map +1 -1
  4. package/dist/analyzer.mjs +74 -21
  5. package/dist/analyzer.mjs.map +1 -1
  6. package/dist/animate.js +4 -2
  7. package/dist/animate.js.map +1 -1
  8. package/dist/animate.mjs +4 -2
  9. package/dist/animate.mjs.map +1 -1
  10. package/dist/atomic.js +20 -5
  11. package/dist/atomic.js.map +1 -1
  12. package/dist/atomic.mjs +20 -5
  13. package/dist/atomic.mjs.map +1 -1
  14. package/dist/cli.js +174 -67
  15. package/dist/cli.js.map +1 -1
  16. package/dist/cli.mjs +171 -64
  17. package/dist/cli.mjs.map +1 -1
  18. package/dist/compiler.d.mts +7 -1
  19. package/dist/compiler.d.ts +7 -1
  20. package/dist/compiler.js +53 -27
  21. package/dist/compiler.js.map +1 -1
  22. package/dist/compiler.mjs +53 -27
  23. package/dist/compiler.mjs.map +1 -1
  24. package/dist/devtools.js.map +1 -1
  25. package/dist/devtools.mjs.map +1 -1
  26. package/dist/engine.js +159 -61
  27. package/dist/engine.js.map +1 -1
  28. package/dist/engine.mjs +159 -61
  29. package/dist/engine.mjs.map +1 -1
  30. package/dist/index.browser.mjs +1512 -0
  31. package/dist/index.browser.mjs.map +1 -0
  32. package/dist/index.d.mts +94 -12
  33. package/dist/index.d.ts +94 -12
  34. package/dist/index.js +436 -106
  35. package/dist/index.js.map +1 -1
  36. package/dist/index.mjs +436 -106
  37. package/dist/index.mjs.map +1 -1
  38. package/dist/next.js +1946 -47
  39. package/dist/next.js.map +1 -1
  40. package/dist/next.mjs +1929 -44
  41. package/dist/next.mjs.map +1 -1
  42. package/dist/plugin-api.js.map +1 -1
  43. package/dist/plugin-api.mjs.map +1 -1
  44. package/dist/plugin-registry.js +23 -10
  45. package/dist/plugin-registry.js.map +1 -1
  46. package/dist/plugin-registry.mjs +23 -11
  47. package/dist/plugin-registry.mjs.map +1 -1
  48. package/dist/plugin.js.map +1 -1
  49. package/dist/plugin.mjs.map +1 -1
  50. package/dist/rspack.js.map +1 -1
  51. package/dist/rspack.mjs.map +1 -1
  52. package/dist/scanner.js +72 -19
  53. package/dist/scanner.js.map +1 -1
  54. package/dist/scanner.mjs +71 -18
  55. package/dist/scanner.mjs.map +1 -1
  56. package/dist/shared.js +32 -15
  57. package/dist/shared.js.map +1 -1
  58. package/dist/shared.mjs +32 -15
  59. package/dist/shared.mjs.map +1 -1
  60. package/dist/svelte.js +38 -12
  61. package/dist/svelte.js.map +1 -1
  62. package/dist/svelte.mjs +38 -12
  63. package/dist/svelte.mjs.map +1 -1
  64. package/dist/syntax.js +17 -5
  65. package/dist/syntax.js.map +1 -1
  66. package/dist/syntax.mjs +17 -5
  67. package/dist/syntax.mjs.map +1 -1
  68. package/dist/theme.js +4 -2
  69. package/dist/theme.js.map +1 -1
  70. package/dist/theme.mjs +4 -2
  71. package/dist/theme.mjs.map +1 -1
  72. package/dist/turbopackLoader.js +87 -33
  73. package/dist/turbopackLoader.js.map +1 -1
  74. package/dist/turbopackLoader.mjs +87 -33
  75. package/dist/turbopackLoader.mjs.map +1 -1
  76. package/dist/tw.js +174 -67
  77. package/dist/tw.js.map +1 -1
  78. package/dist/tw.mjs +171 -64
  79. package/dist/tw.mjs.map +1 -1
  80. package/dist/vite.js +145 -63
  81. package/dist/vite.js.map +1 -1
  82. package/dist/vite.mjs +145 -63
  83. package/dist/vite.mjs.map +1 -1
  84. package/dist/vue.js +38 -12
  85. package/dist/vue.js.map +1 -1
  86. package/dist/vue.mjs +38 -12
  87. package/dist/vue.mjs.map +1 -1
  88. package/dist/webpackLoader.js +20 -5
  89. package/dist/webpackLoader.js.map +1 -1
  90. package/dist/webpackLoader.mjs +20 -5
  91. package/dist/webpackLoader.mjs.map +1 -1
  92. package/native/tailwind-styled-native.node +0 -0
  93. package/package.json +29 -24
package/dist/next.mjs CHANGED
@@ -1,44 +1,42 @@
1
- import { z } from 'zod';
2
- import fs2 from 'fs';
3
1
  import { createRequire } from 'module';
4
- import path2 from 'path';
2
+ import * as fs5 from 'fs';
3
+ import fs5__default from 'fs';
4
+ import * as path5 from 'path';
5
+ import path5__default from 'path';
5
6
  import 'crypto';
6
- import 'url';
7
+ import { fileURLToPath } from 'url';
8
+ import { z } from 'zod';
9
+ import 'worker_threads';
7
10
 
8
11
  /* tailwind-styled-v4 v5.0.4 | MIT | https://github.com/dictionar32/tailwind-styled-v4 */
12
+ var __defProp = Object.defineProperty;
13
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
14
+ var __getOwnPropNames = Object.getOwnPropertyNames;
15
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
9
16
  var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
10
17
  get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
11
18
  }) : x)(function(x) {
12
19
  if (typeof require !== "undefined") return require.apply(this, arguments);
13
20
  throw Error('Dynamic require of "' + x + '" is not supported');
14
21
  });
15
- var formatIssues = (error) => error.issues.map((issue) => {
16
- const p = issue.path.length > 0 ? issue.path.join(".") : "<root>";
17
- return `${p}: ${issue.message}`;
18
- }).join("; ");
19
- var parseWithSchema = (schema, data, label) => {
20
- const parsed = schema.safeParse(data);
21
- if (parsed.success) return parsed.data;
22
- throw new TypeError(`${label}: ${formatIssues(parsed.error)}`);
22
+ var __esm = (fn, res) => function __init() {
23
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
23
24
  };
24
- var NextAdapterOptionsSchema = z.object({
25
- mode: z.literal("zero-runtime").optional(),
26
- autoClientBoundary: z.boolean().optional(),
27
- addDataAttr: z.boolean().optional(),
28
- hoist: z.boolean().optional(),
29
- routeCss: z.boolean().optional(),
30
- incremental: z.boolean().optional(),
31
- verbose: z.boolean().optional(),
32
- include: z.instanceof(RegExp).optional(),
33
- exclude: z.instanceof(RegExp).optional()
34
- });
35
- var parseNextAdapterOptions = (options) => parseWithSchema(NextAdapterOptionsSchema, options ?? {}, "next adapter options are invalid");
25
+ var __export = (target, all) => {
26
+ for (var name in all)
27
+ __defProp(target, name, { get: all[name], enumerable: true });
28
+ };
29
+ var __copyProps = (to, from, except, desc) => {
30
+ if (from && typeof from === "object" || typeof from === "function") {
31
+ for (let key of __getOwnPropNames(from))
32
+ if (!__hasOwnProp.call(to, key) && key !== except)
33
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
34
+ }
35
+ return to;
36
+ };
37
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
36
38
 
37
39
  // packages/domain/shared/src/workerResolver.ts
38
- var isBrowser = typeof window !== "undefined" || typeof document !== "undefined";
39
- var NODE_URL = typeof window === "undefined" || typeof document === "undefined" ? "node:url" : null;
40
- var NODE_FS = typeof window === "undefined" || typeof document === "undefined" ? "node:fs" : null;
41
- var NODE_PATH = typeof window === "undefined" || typeof document === "undefined" ? "node:path" : null;
42
40
  function getDirnameFromUrl(importMetaUrl) {
43
41
  if (!importMetaUrl) return "";
44
42
  if (isBrowser) return "";
@@ -64,11 +62,11 @@ function resolvePath(...segments) {
64
62
  return segments.join("/").replace(/\/+/g, "/");
65
63
  }
66
64
  }
67
- function existsSync(path3) {
65
+ function existsSync(path7) {
68
66
  if (isBrowser) return false;
69
67
  try {
70
68
  const nodeFs = __require(NODE_FS);
71
- return nodeFs.existsSync(path3);
69
+ return nodeFs.existsSync(path7);
72
70
  } catch {
73
71
  return false;
74
72
  }
@@ -118,9 +116,1685 @@ function resolveLoaderPath(loaderBasename, importMetaUrl) {
118
116
  subdirs: [".", "loaders", "lib"]
119
117
  }).path;
120
118
  }
119
+ var isBrowser, NODE_URL, NODE_FS, NODE_PATH;
120
+ var init_workerResolver = __esm({
121
+ "packages/domain/shared/src/workerResolver.ts"() {
122
+ isBrowser = typeof window !== "undefined" || typeof document !== "undefined";
123
+ NODE_URL = typeof window === "undefined" || typeof document === "undefined" ? "node:url" : null;
124
+ NODE_FS = typeof window === "undefined" || typeof document === "undefined" ? "node:fs" : null;
125
+ NODE_PATH = typeof window === "undefined" || typeof document === "undefined" ? "node:path" : null;
126
+ }
127
+ });
128
+ function platformKey() {
129
+ if (isBrowser2) return "browser";
130
+ return `${process.platform}-${process.arch}`;
131
+ }
132
+ function resolveNativeBinary(runtimeDir) {
133
+ const platform = platformKey();
134
+ const tried = [];
135
+ if (isBrowser2) {
136
+ return { path: null, source: "not-found", platform, tried: ["not available in browser"] };
137
+ }
138
+ if (process.env.TWS_DISABLE_NATIVE === "1") {
139
+ return { path: null, source: "not-found", platform, tried: [] };
140
+ }
141
+ const envPath = process.env.TW_NATIVE_PATH?.trim();
142
+ if (envPath) {
143
+ if (fs5.existsSync(envPath)) {
144
+ return { path: envPath, source: "env", platform, tried };
145
+ }
146
+ tried.push(`env:${envPath} (not found)`);
147
+ }
148
+ const prebuiltPkgs = PLATFORM_MAP[platform] ?? [];
149
+ for (const pkg of prebuiltPkgs) {
150
+ try {
151
+ const candidate = _require.resolve(`${pkg}/tailwind_styled_parser.node`);
152
+ if (fs5.existsSync(candidate)) {
153
+ return { path: candidate, source: "prebuilt", platform, tried };
154
+ }
155
+ tried.push(`prebuilt:${pkg} (resolved but missing)`);
156
+ } catch {
157
+ tried.push(`prebuilt:${pkg} (not installed)`);
158
+ }
159
+ }
160
+ const napiPlatform = platform === "linux-x64" ? "linux-x64-gnu" : platform === "linux-arm64" ? "linux-arm64-gnu" : platform;
161
+ const BINARY_NAMES_SELF = ["tailwind-styled-native", "tailwind_styled_parser"];
162
+ if (runtimeDir) {
163
+ for (const depth of ["..", path5.join("..", ".."), path5.join("..", "..", "..")]) {
164
+ const pkgRoot = path5.resolve(runtimeDir, depth);
165
+ for (const bin of BINARY_NAMES_SELF) {
166
+ for (const suffix of ["", `.${platform}`, `.${napiPlatform}`]) {
167
+ const candidate = path5.resolve(pkgRoot, "native", `${bin}${suffix}.node`);
168
+ tried.push(`self-bundled:${candidate}`);
169
+ if (fs5.existsSync(candidate)) {
170
+ return { path: candidate, source: "prebuilt", platform, tried };
171
+ }
172
+ }
173
+ }
174
+ }
175
+ }
176
+ const cwd = process.cwd();
177
+ const base = runtimeDir ?? cwd;
178
+ const BINARY_NAMES = ["tailwind-styled-native", "tailwind_styled_parser"];
179
+ const localCandidates = [];
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`));
185
+ }
186
+ for (const startDir of [cwd, base]) {
187
+ let dir = startDir;
188
+ for (let i = 0; i < 6; i++) {
189
+ const nativeDir = path5.resolve(dir, "native");
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`));
195
+ }
196
+ const parent = path5.resolve(dir, "..");
197
+ if (parent === dir) break;
198
+ dir = parent;
199
+ }
200
+ }
201
+ for (const candidate of localCandidates) {
202
+ tried.push(`local:${candidate}`);
203
+ if (fs5.existsSync(candidate)) {
204
+ return { path: candidate, source: "local", platform, tried };
205
+ }
206
+ }
207
+ return { path: null, source: "not-found", platform, tried };
208
+ }
209
+ var isBrowser2, _require, PLATFORM_MAP;
210
+ var init_native_resolution = __esm({
211
+ "packages/domain/shared/src/native-resolution.ts"() {
212
+ isBrowser2 = typeof window !== "undefined" || typeof document !== "undefined";
213
+ _require = typeof __require !== "undefined" ? __require : createRequire(import.meta.url);
214
+ PLATFORM_MAP = {
215
+ "linux-x64": ["@tailwind-styled/native-linux-x64-gnu", "@tailwind-styled/native-linux-x64"],
216
+ "linux-arm64": ["@tailwind-styled/native-linux-arm64-gnu", "@tailwind-styled/native-linux-arm64"],
217
+ "darwin-x64": ["@tailwind-styled/native-darwin-x64"],
218
+ "darwin-arm64": ["@tailwind-styled/native-darwin-arm64"],
219
+ "win32-x64": ["@tailwind-styled/native-win32-x64-msvc", "@tailwind-styled/native-win32-x64"],
220
+ "win32-arm64": ["@tailwind-styled/native-win32-arm64-msvc", "@tailwind-styled/native-win32-arm64"]
221
+ };
222
+ }
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
+ `);
242
+ }
243
+ };
244
+ }
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);
250
+ }
251
+ };
252
+ }
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(".");
258
+ }
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);
264
+ try {
265
+ if (!fs5__default.existsSync(candidatePath) && !fs5__default.existsSync(candidatePath + ".node")) {
266
+ continue;
267
+ }
268
+ const mod = requireNativeModule(candidatePath);
269
+ if (mod && isValid(mod)) {
270
+ return { binding: mod, loadErrors, loadedPath: candidatePath };
271
+ }
272
+ loadErrors.push({ path: candidatePath, message: options.invalidExportMessage });
273
+ } catch (e) {
274
+ loadErrors.push({ path: candidatePath, message: e instanceof Error ? e.message : String(e) });
275
+ }
276
+ }
277
+ return { binding: null, loadErrors };
278
+ }
279
+ function requireNativeModule(p) {
280
+ return _require2(p);
281
+ }
282
+ function resolveNativeBindingCandidates(options) {
283
+ const {
284
+ envVarNames = ["TW_NATIVE_PATH", "TWS_NATIVE_PATH"],
285
+ includeDefaultCandidates = true,
286
+ enforceNodeExtensionForEnvPath = false
287
+ } = 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);
294
+ }
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 {
303
+ }
304
+ }
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`));
317
+ }
318
+ return Array.from(new Set(candidates));
319
+ }
320
+ function resolveRuntimeDir(dir, importMetaUrl) {
321
+ try {
322
+ return path5__default.dirname(fileURLToPath(importMetaUrl));
323
+ } catch {
324
+ return process.cwd();
325
+ }
326
+ }
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);
385
+ }
386
+ });
387
+
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();
425
+ }
426
+ function scanWorkspaceNative(root, extensions) {
427
+ return scannerGetBinding().scanWorkspace(root, extensions ?? null);
428
+ }
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;
439
+ }
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;
450
+ }
451
+ function isRustCacheAvailable() {
452
+ return true;
453
+ }
454
+ function hasNativeScannerBinding() {
455
+ try {
456
+ scannerBridgeLoader.get();
457
+ return true;
458
+ } catch {
459
+ return false;
460
+ }
461
+ }
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;
472
+ }
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;
483
+ }
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
+ );
500
+ }
501
+ return result;
502
+ }
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) ?? [];
509
+ }
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;
516
+ }
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);
523
+ }
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);
530
+ }
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();
537
+ }
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);
544
+ }
545
+ function collectFilesNative(root, extensions, ignoreDirs) {
546
+ const binding = scannerGetBinding();
547
+ if (!binding.collectFiles) return null;
548
+ return binding.collectFiles(root, extensions, ignoreDirs);
549
+ }
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);
563
+ }
564
+ function generateSubComponentTypesNative(root, outputPath) {
565
+ const binding = scannerGetBinding();
566
+ if (!binding.generateSubComponentTypes) return null;
567
+ return binding.generateSubComponentTypes(root, outputPath ?? null);
568
+ }
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
+ );
577
+ }
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;
585
+ }
586
+ }
587
+ function computeCacheStatsNative(filesClasses, sizes, top) {
588
+ const binding = scannerGetBinding();
589
+ if (!binding.computeCacheStats) return null;
590
+ return binding.computeCacheStats(filesClasses, sizes, top ?? null);
591
+ }
592
+ function startWatchNative(rootDir) {
593
+ try {
594
+ const binding = scannerGetBinding();
595
+ if (!binding.startWatch) return null;
596
+ return binding.startWatch(rootDir);
597
+ } catch {
598
+ return null;
599
+ }
600
+ }
601
+ function pollWatchEventsNative(handleId) {
602
+ try {
603
+ const binding = scannerGetBinding();
604
+ if (!binding.pollWatchEvents) return [];
605
+ return binding.pollWatchEvents(handleId);
606
+ } catch {
607
+ return [];
608
+ }
609
+ }
610
+ function stopWatchNative(handleId) {
611
+ try {
612
+ const binding = scannerGetBinding();
613
+ if (!binding.stopWatch) return false;
614
+ return binding.stopWatch(handleId);
615
+ } catch {
616
+ return false;
617
+ }
618
+ }
619
+ function hasNativeWatchBinding() {
620
+ try {
621
+ const binding = scannerGetBinding();
622
+ return !!(binding.startWatch && binding.pollWatchEvents && binding.stopWatch);
623
+ } catch {
624
+ return false;
625
+ }
626
+ }
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));
635
+ };
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
+ };
704
+ };
705
+ scannerBridgeLoader = createScannerBridgeLoader();
706
+ scannerGetBinding = scannerBridgeLoader.get;
707
+ resetScannerBridgeCache = scannerBridgeLoader.reset;
708
+ }
709
+ });
710
+
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
+ }
764
+ };
765
+ resetNativeBridgeCache = () => {
766
+ nativeBridge = null;
767
+ bridgeLoadAttempted = false;
768
+ bridgeLoadError = null;
769
+ log3("Native bridge cache reset");
770
+ };
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
+ };
779
+ };
780
+ if (typeof process !== "undefined" && !bridgeLoadAttempted) {
781
+ try {
782
+ getNativeBridge();
783
+ } catch {
784
+ }
785
+ }
786
+ }
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;
800
+ 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;
810
+ }
811
+ }
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 "";
844
+ const native = getNativeBridge();
845
+ if (typeof native.processTailwindCssLightning !== "function") {
846
+ throw new Error("FATAL: Native binding 'processTailwindCssLightning' is required but not available.");
847
+ }
848
+ const result = native.processTailwindCssLightning(rawCss);
849
+ return result?.css ?? rawCss;
850
+ }
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);
857
+ 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 };
869
+ }
870
+ function processTailwindCssWithTargets(css, targets) {
871
+ const native = getNativeBridge();
872
+ if (!native?.processTailwindCssWithTargets) {
873
+ throw new Error("FATAL: Native binding 'processTailwindCssWithTargets' is required but not available.");
874
+ }
875
+ const result = native.processTailwindCssWithTargets(css, targets ?? null);
876
+ return (result?.css ?? css).trim();
877
+ }
878
+ var require2, _twEngine, _twEngineError;
879
+ var init_tailwindEngine = __esm({
880
+ "packages/domain/compiler/src/tailwindEngine.ts"() {
881
+ init_nativeBridge();
882
+ require2 = createRequire(import.meta.url);
883
+ _twEngine = null;
884
+ _twEngineError = null;
885
+ }
886
+ });
887
+
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;
965
+ };
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);
972
+ };
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);
979
+ };
980
+ shouldProcess = (source) => {
981
+ return hasTwUsage(source) && !isAlreadyTransformed(source);
982
+ };
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;
993
+ };
994
+ buildStyleTag = (classes) => {
995
+ const result = compileCssFromClasses(classes);
996
+ return result?.code ? `<style data-tailwind-styled>${result.code}</style>` : "";
997
+ };
998
+ compileCssNative = (classes, prefix = null) => {
999
+ return compileCssFromClasses(classes, prefix);
1000
+ };
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;
1005
+ };
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) || [];
1012
+ };
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 ?? []));
1093
+ };
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();
1114
+ };
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;
1129
+ };
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) || [];
1136
+ };
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 };
1143
+ };
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) || [];
1150
+ };
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 };
1157
+ };
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: [] };
1164
+ };
1165
+ compileVariantTable = (configJson) => {
1166
+ const native = getNativeBridge();
1167
+ if (!native?.compileVariantTable) {
1168
+ throw new Error("FATAL: Native binding 'compileVariantTable' is required but not available.");
1169
+ }
1170
+ return native.compileVariantTable(configJson) || { id: "", tableJson: "{}", keys: [], defaultKey: "", combinations: 0 };
1171
+ };
1172
+ compileVariants = (componentId, config) => {
1173
+ return compileVariantTable(JSON.stringify({ componentId, ...config }));
1174
+ };
1175
+ classifyAndSortClasses = (classes) => {
1176
+ const native = getNativeBridge();
1177
+ if (!native?.classifyAndSortClasses) {
1178
+ throw new Error("FATAL: Native binding 'classifyAndSortClasses' is required but not available.");
1179
+ }
1180
+ return native.classifyAndSortClasses(classes) || [];
1181
+ };
1182
+ mergeCssDeclarations = (cssChunks) => {
1183
+ const native = getNativeBridge();
1184
+ if (!native?.mergeCssDeclarations) {
1185
+ throw new Error("FATAL: Native binding 'mergeCssDeclarations' is required but not available.");
1186
+ }
1187
+ return native.mergeCssDeclarations(cssChunks) || { declarationsJson: "{}", declarationString: "", count: 0 };
1188
+ };
1189
+ analyzeClassUsage = (classes, scanResultJson, css) => {
1190
+ const native = getNativeBridge();
1191
+ if (!native?.analyzeClassUsage) {
1192
+ throw new Error("FATAL: Native binding 'analyzeClassUsage' is required but not available.");
1193
+ }
1194
+ return native.analyzeClassUsage(classes, scanResultJson, css) || [];
1195
+ };
1196
+ analyzeRsc = (source, filename) => {
1197
+ const native = getNativeBridge();
1198
+ if (!native?.analyzeRsc) {
1199
+ throw new Error("FATAL: Native binding 'analyzeRsc' is required but not available.");
1200
+ }
1201
+ return native.analyzeRsc(source, filename) || { isServer: true, needsClientDirective: false, clientReasons: [] };
1202
+ };
1203
+ analyzeFile = (source, filename) => {
1204
+ const rsc = analyzeRsc(source, filename);
1205
+ return {
1206
+ isServer: rsc?.isServer ?? true,
1207
+ needsClientDirective: rsc?.needsClientDirective ?? false,
1208
+ clientReasons: rsc?.clientReasons ?? [],
1209
+ interactiveClasses: [],
1210
+ canStaticResolveVariants: true
1211
+ };
1212
+ };
1213
+ analyzeVariantUsage = (source, componentName, variantKeys) => {
1214
+ analyzeRsc(source, componentName);
1215
+ return {
1216
+ resolved: {},
1217
+ dynamic: []
1218
+ };
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;
1269
+ }
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
+ ]
1281
+ };
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 || []
1290
+ };
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
+ return {
1349
+ add: (className) => className,
1350
+ get: (_bucket) => []
1351
+ };
1352
+ };
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
+ };
1377
+ }
1378
+ });
1379
+ var formatIssues = (error) => error.issues.map((issue) => {
1380
+ const p = issue.path.length > 0 ? issue.path.join(".") : "<root>";
1381
+ return `${p}: ${issue.message}`;
1382
+ }).join("; ");
1383
+ var parseWithSchema = (schema, data, label) => {
1384
+ const parsed = schema.safeParse(data);
1385
+ if (parsed.success) return parsed.data;
1386
+ throw new TypeError(`${label}: ${formatIssues(parsed.error)}`);
1387
+ };
1388
+ var NextAdapterOptionsSchema = z.object({
1389
+ mode: z.literal("zero-runtime").optional(),
1390
+ autoClientBoundary: z.boolean().optional(),
1391
+ addDataAttr: z.boolean().optional(),
1392
+ hoist: z.boolean().optional(),
1393
+ routeCss: z.boolean().optional(),
1394
+ incremental: z.boolean().optional(),
1395
+ verbose: z.boolean().optional(),
1396
+ include: z.instanceof(RegExp).optional(),
1397
+ exclude: z.instanceof(RegExp).optional()
1398
+ });
1399
+ var parseNextAdapterOptions = (options) => parseWithSchema(NextAdapterOptionsSchema, options ?? {}, "next adapter options are invalid");
1400
+
1401
+ // packages/presentation/next/src/withTailwindStyled.ts
1402
+ init_src();
1403
+
1404
+ // packages/domain/scanner/src/index.ts
1405
+ init_src();
1406
+
1407
+ // packages/domain/scanner/src/cache-native.ts
1408
+ init_native_bridge();
1409
+ 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");
1412
+ }
1413
+ function readCache(rootDir, cacheDir) {
1414
+ const cachePath = defaultCachePath(rootDir, cacheDir);
1415
+ fs5__default.mkdirSync(path5__default.dirname(cachePath), { recursive: true });
1416
+ const result = cacheReadNative(cachePath);
1417
+ if (!result) return [];
1418
+ return result.entries.map((e) => ({
1419
+ file: e.file,
1420
+ classes: e.classes,
1421
+ hash: e.hash,
1422
+ mtimeMs: e.mtimeMs,
1423
+ size: e.size,
1424
+ hitCount: e.hitCount,
1425
+ lastSeenMs: e.lastSeenMs
1426
+ }));
1427
+ }
1428
+ function writeCache(rootDir, entries, cacheDir) {
1429
+ const cachePath = defaultCachePath(rootDir, cacheDir);
1430
+ fs5__default.mkdirSync(path5__default.dirname(cachePath), { recursive: true });
1431
+ const success = cacheWriteNative(cachePath, entries);
1432
+ if (!success) {
1433
+ throw new Error(
1434
+ "Native cacheWrite failed. Run 'npm run build:rust' to rebuild native bindings."
1435
+ );
1436
+ }
1437
+ }
1438
+ function filePriority(mtimeMs, size, cached, nowMs = Date.now()) {
1439
+ return cachePriorityNative(
1440
+ mtimeMs,
1441
+ size,
1442
+ cached?.mtimeMs ?? 0,
1443
+ cached?.size ?? 0,
1444
+ cached?.hitCount ?? 0,
1445
+ cached?.lastSeenMs ?? 0,
1446
+ nowMs
1447
+ );
1448
+ }
121
1449
 
122
- // packages/domain/shared/src/index.ts
123
- createRequire(import.meta.url);
1450
+ // packages/domain/scanner/src/index.ts
1451
+ init_native_bridge();
1452
+
1453
+ // packages/domain/scanner/src/schemas.ts
1454
+ init_src();
1455
+ var formatIssuePath2 = (path7) => path7.length > 0 ? path7.map(
1456
+ (segment) => typeof segment === "symbol" ? segment.description ?? segment.toString() : String(segment)
1457
+ ).join(".") : "<root>";
1458
+ var formatIssues2 = (error) => error.issues.map((issue) => {
1459
+ const path7 = formatIssuePath2(issue.path);
1460
+ return `${path7}: ${issue.message}`;
1461
+ }).join("; ");
1462
+ var parseWithSchema2 = (schema, data, label) => {
1463
+ const parsed = schema.safeParse(data);
1464
+ if (parsed.success) return parsed.data;
1465
+ const details = formatIssues2(parsed.error);
1466
+ throw new TwError(
1467
+ "validation",
1468
+ "SCHEMA_VALIDATION_FAILED",
1469
+ details ? `${label}: ${details}` : label,
1470
+ parsed.error
1471
+ );
1472
+ };
1473
+ var NonNegativeIntegerSchema = z.number().int().min(0);
1474
+ var ScanWorkspaceOptionsSchema = z.object({
1475
+ includeExtensions: z.array(z.string()).optional(),
1476
+ ignoreDirectories: z.array(z.string()).optional(),
1477
+ useCache: z.boolean().optional(),
1478
+ cacheDir: z.string().min(1).optional(),
1479
+ smartInvalidation: z.boolean().optional()
1480
+ });
1481
+ var ScanFileResultSchema = z.object({
1482
+ file: z.string(),
1483
+ classes: z.array(z.string()),
1484
+ hash: z.string().optional()
1485
+ });
1486
+ var ScanWorkspaceResultSchema = z.object({
1487
+ files: z.array(ScanFileResultSchema),
1488
+ totalFiles: NonNegativeIntegerSchema,
1489
+ uniqueClasses: z.array(z.string())
1490
+ }).refine((value) => value.totalFiles === value.files.length, {
1491
+ message: "scan result totalFiles must match files.length",
1492
+ path: ["totalFiles"]
1493
+ });
1494
+ z.object({
1495
+ rootDir: z.string().min(1),
1496
+ options: ScanWorkspaceOptionsSchema.optional()
1497
+ });
1498
+ var ScannerWorkerSuccessMessageSchema = z.object({
1499
+ ok: z.literal(true),
1500
+ result: ScanWorkspaceResultSchema
1501
+ });
1502
+ var ScannerWorkerErrorMessageSchema = z.object({
1503
+ ok: z.literal(false),
1504
+ error: z.string().optional()
1505
+ });
1506
+ z.union([
1507
+ ScannerWorkerSuccessMessageSchema,
1508
+ ScannerWorkerErrorMessageSchema
1509
+ ]);
1510
+ var parseScanWorkspaceOptions = (options) => parseWithSchema2(ScanWorkspaceOptionsSchema, options ?? {}, "scanner options are invalid");
1511
+ var parseScanWorkspaceResult = (result) => parseWithSchema2(ScanWorkspaceResultSchema, result, "scanner workspace result is invalid");
1512
+
1513
+ // packages/domain/scanner/src/index.ts
1514
+ var log2 = createLogger("scanner");
1515
+ function getRuntimeDir() {
1516
+ if (typeof __dirname !== "undefined" && __dirname.length > 0) {
1517
+ return __dirname;
1518
+ }
1519
+ if (typeof import.meta !== "undefined" && import.meta.url) {
1520
+ return path5__default.dirname(fileURLToPath(import.meta.url));
1521
+ }
1522
+ return process.cwd();
1523
+ }
1524
+ var createNativeParserLoader = () => {
1525
+ const _state = {
1526
+ binding: void 0,
1527
+ initError: null
1528
+ };
1529
+ const debugNative = (message) => {
1530
+ log2.debug(`[native] ${message}`);
1531
+ };
1532
+ const loadNativeParserBinding = () => {
1533
+ if (_state.binding !== void 0) return _state.binding;
1534
+ const runtimeDir = getRuntimeDir();
1535
+ const req = createRequire(path5__default.join(runtimeDir, "noop.cjs"));
1536
+ const _platform = process.platform;
1537
+ const _arch = process.arch;
1538
+ const _platformArch = `${_platform}-${_arch}`;
1539
+ const _platformArchGnu = _platformArch === "linux-x64" ? "linux-x64-gnu" : _platformArch === "linux-arm64" ? "linux-arm64-gnu" : _platformArch;
1540
+ const candidates = [
1541
+ // ── binaryName baru: tailwind-styled-native (napi-rs naming) ──
1542
+ // 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`),
1546
+ // runtimeDir = dist/ → naik 1 level ke package root (npm install case)
1547
+ // 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`),
1551
+ // 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`),
1554
+ // 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`),
1557
+ // ── 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(
1564
+ runtimeDir,
1565
+ "..",
1566
+ "..",
1567
+ "..",
1568
+ "native",
1569
+ "build",
1570
+ "Release",
1571
+ "tailwind_styled_parser.node"
1572
+ )
1573
+ ];
1574
+ for (const fullPath of candidates) {
1575
+ if (!fs5__default.existsSync(fullPath)) continue;
1576
+ try {
1577
+ const required = req(fullPath);
1578
+ if (required && (typeof required.extractClassesFromSource === "function" || typeof required.parseClasses === "function" || typeof required.parse_classes === "function")) {
1579
+ _state.binding = required;
1580
+ debugNative(`using native parser from ${fullPath}`);
1581
+ return _state.binding;
1582
+ }
1583
+ } catch (error) {
1584
+ _state.initError = error instanceof Error ? error.message : String(error);
1585
+ }
1586
+ }
1587
+ _state.binding = null;
1588
+ if (!_state.initError) {
1589
+ _state.initError = "native .node binding not found";
1590
+ }
1591
+ debugNative(`native binding not available: ${_state.initError}`);
1592
+ return _state.binding;
1593
+ };
1594
+ return {
1595
+ get: loadNativeParserBinding,
1596
+ reset: () => {
1597
+ _state.binding = void 0;
1598
+ _state.initError = null;
1599
+ }
1600
+ };
1601
+ };
1602
+ var nativeParserLoader = createNativeParserLoader();
1603
+ var DEFAULT_EXTENSIONS = [".js", ".jsx", ".ts", ".tsx", ".mjs", ".cjs"];
1604
+ var DEFAULT_IGNORES = ["node_modules", ".git", ".next", "dist", "out", ".turbo", ".cache"];
1605
+ function buildExtensionSet(includeExtensions) {
1606
+ return new Set(includeExtensions);
1607
+ }
1608
+ function collectCandidates(rootDir, ignoreDirectories, extensionSet) {
1609
+ const candidates = [];
1610
+ const directories = [rootDir];
1611
+ while (directories.length > 0) {
1612
+ const currentDir = directories.pop();
1613
+ if (!currentDir) continue;
1614
+ const entries = (() => {
1615
+ try {
1616
+ return fs5__default.readdirSync(currentDir, { withFileTypes: true });
1617
+ } catch {
1618
+ return [];
1619
+ }
1620
+ })();
1621
+ for (const entry of entries) {
1622
+ const fullPath = path5__default.join(currentDir, entry.name);
1623
+ if (entry.isDirectory()) {
1624
+ if (!ignoreDirectories.has(entry.name)) directories.push(fullPath);
1625
+ continue;
1626
+ }
1627
+ if (!entry.isFile()) continue;
1628
+ if (!extensionSet.has(path5__default.extname(entry.name))) continue;
1629
+ candidates.push(fullPath);
1630
+ }
1631
+ }
1632
+ return candidates;
1633
+ }
1634
+ function toCacheSize(size) {
1635
+ if (!Number.isFinite(size)) return 0;
1636
+ const normalized = Math.max(0, Math.trunc(size));
1637
+ return Math.min(normalized, 4294967295);
1638
+ }
1639
+ function scanSource(source) {
1640
+ const nativeBinding = nativeParserLoader.get();
1641
+ if (nativeBinding?.extractClassesFromSource) {
1642
+ const result = nativeBinding.extractClassesFromSource(source);
1643
+ if (Array.isArray(result)) {
1644
+ return Array.from(new Set(result.filter(Boolean)));
1645
+ }
1646
+ if (result !== null && result !== void 0 && Array.isArray(result.classes)) {
1647
+ return Array.from(new Set(result.classes.filter(Boolean)));
1648
+ }
1649
+ }
1650
+ throw new Error(
1651
+ "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
+ );
1653
+ }
1654
+ function scanFile(filePath) {
1655
+ const { scanFileNative: scanFileNative2 } = (init_native_bridge(), __toCommonJS(native_bridge_exports));
1656
+ const result = scanFileNative2(filePath);
1657
+ if (!result.ok) {
1658
+ throw new Error(`scanFile failed for ${filePath}: ${result.error ?? "unknown error"}`);
1659
+ }
1660
+ return {
1661
+ file: result.file,
1662
+ classes: result.classes,
1663
+ ...result.hash ? { hash: result.hash } : {}
1664
+ };
1665
+ }
1666
+ function scanWorkspace(rootDir, options = {}) {
1667
+ const normalizedOptions = parseScanWorkspaceOptions(options);
1668
+ const includeExtensions = normalizedOptions.includeExtensions ?? DEFAULT_EXTENSIONS;
1669
+ const extensionSet = buildExtensionSet(includeExtensions);
1670
+ const ignoreDirectories = new Set(normalizedOptions.ignoreDirectories ?? DEFAULT_IGNORES);
1671
+ const useCache = normalizedOptions.useCache ?? true;
1672
+ normalizedOptions.smartInvalidation ?? true;
1673
+ const files = [];
1674
+ const unique = /* @__PURE__ */ new Set();
1675
+ const candidates = collectCandidates(rootDir, ignoreDirectories, extensionSet);
1676
+ const processResult = (result) => {
1677
+ files.push(result);
1678
+ for (const cls of result.classes) unique.add(cls);
1679
+ };
1680
+ const { scanWorkspaceNative: scanWorkspaceNative2 } = (init_native_bridge(), __toCommonJS(native_bridge_exports));
1681
+ if (!normalizedOptions.cacheDir && !useCache) {
1682
+ const nativeResult = scanWorkspaceNative2(rootDir, includeExtensions);
1683
+ if (nativeResult) {
1684
+ return parseScanWorkspaceResult({
1685
+ files: nativeResult.files.map((f) => ({
1686
+ file: f.file,
1687
+ classes: f.classes,
1688
+ ...f.hash ? { hash: f.hash } : {}
1689
+ })),
1690
+ totalFiles: nativeResult.totalFiles,
1691
+ uniqueClasses: nativeResult.uniqueClasses
1692
+ });
1693
+ }
1694
+ }
1695
+ if (useCache && isRustCacheAvailable()) {
1696
+ const cacheEntries = (() => {
1697
+ try {
1698
+ return readCache(rootDir, normalizedOptions.cacheDir);
1699
+ } catch (error) {
1700
+ log2.debug(
1701
+ `cache read failed, continuing without persisted cache: ${error instanceof Error ? error.message : String(error)}`
1702
+ );
1703
+ return [];
1704
+ }
1705
+ })();
1706
+ const cacheMap = new Map(cacheEntries.map((entry) => [entry.file, entry]));
1707
+ const nowMs = Date.now();
1708
+ const ranked = [];
1709
+ for (const filePath of candidates) {
1710
+ const stat = (() => {
1711
+ try {
1712
+ return fs5__default.statSync(filePath);
1713
+ } catch {
1714
+ return null;
1715
+ }
1716
+ })();
1717
+ if (!stat) continue;
1718
+ const size = toCacheSize(stat.size);
1719
+ const cached = cacheMap.get(filePath);
1720
+ const priority = filePriority(
1721
+ stat.mtimeMs,
1722
+ size,
1723
+ cached ? {
1724
+ mtimeMs: cached.mtimeMs,
1725
+ size: cached.size,
1726
+ hitCount: cached.hitCount,
1727
+ lastSeenMs: 0
1728
+ } : void 0,
1729
+ nowMs
1730
+ );
1731
+ ranked.push({ filePath, stat, size, cached, priority });
1732
+ }
1733
+ ranked.sort((a, b) => b.priority - a.priority);
1734
+ const updatedEntries = [];
1735
+ for (const { filePath, stat, size, cached } of ranked) {
1736
+ const content = (() => {
1737
+ try {
1738
+ return fs5__default.readFileSync(filePath, "utf8");
1739
+ } catch {
1740
+ return null;
1741
+ }
1742
+ })();
1743
+ if (!content) continue;
1744
+ const hash = hashContentNative(content);
1745
+ if (cached && cached.hash === hash && cached.mtimeMs === stat.mtimeMs && cached.size === size) {
1746
+ log2.debug(`cache HIT ${filePath}`);
1747
+ processResult({ file: filePath, classes: cached.classes });
1748
+ updatedEntries.push({
1749
+ file: filePath,
1750
+ classes: cached.classes,
1751
+ hash: cached.hash,
1752
+ mtimeMs: stat.mtimeMs,
1753
+ size,
1754
+ hitCount: (cached.hitCount ?? 0) + 1
1755
+ });
1756
+ continue;
1757
+ }
1758
+ log2.debug(`cache MISS ${filePath}`);
1759
+ const classes = scanSource(content);
1760
+ processResult({ file: filePath, classes });
1761
+ updatedEntries.push({
1762
+ file: filePath,
1763
+ classes,
1764
+ hash,
1765
+ mtimeMs: stat.mtimeMs,
1766
+ size,
1767
+ hitCount: 1
1768
+ });
1769
+ }
1770
+ try {
1771
+ writeCache(rootDir, updatedEntries, normalizedOptions.cacheDir);
1772
+ } catch (error) {
1773
+ log2.debug(`cache write failed: ${error instanceof Error ? error.message : String(error)}`);
1774
+ }
1775
+ return parseScanWorkspaceResult({
1776
+ files,
1777
+ totalFiles: files.length,
1778
+ uniqueClasses: Array.from(unique).sort()
1779
+ });
1780
+ }
1781
+ const batchNative = nativeParserLoader.get()?.batchExtractClassesNative;
1782
+ if (batchNative) {
1783
+ const batchResults = batchNative(candidates);
1784
+ for (const r of batchResults ?? []) {
1785
+ if (r.ok) processResult({ file: r.file, classes: r.classes });
1786
+ }
1787
+ } else {
1788
+ for (const filePath of candidates) {
1789
+ processResult(scanFile(filePath));
1790
+ }
1791
+ }
1792
+ return parseScanWorkspaceResult({
1793
+ files,
1794
+ totalFiles: files.length,
1795
+ uniqueClasses: Array.from(unique).sort()
1796
+ });
1797
+ }
124
1798
 
125
1799
  // packages/presentation/next/src/withTailwindStyled.ts
126
1800
  function getDirnameFromUrl2(importMetaUrl) {
@@ -136,20 +1810,20 @@ function getDirnameFromUrl2(importMetaUrl) {
136
1810
  const lastSlash = Math.max(importMetaUrl.lastIndexOf("/"), importMetaUrl.lastIndexOf("\\"));
137
1811
  return lastSlash > 0 ? importMetaUrl.slice(0, lastSlash) : "";
138
1812
  }
139
- var require2 = createRequire(import.meta.url);
140
- var resolveRuntimeDir = () => getDirnameFromUrl2(import.meta.url);
1813
+ var require3 = createRequire(import.meta.url);
1814
+ var resolveRuntimeDir2 = () => getDirnameFromUrl2(import.meta.url);
141
1815
  var resolveLoaderPath2 = (basename) => {
142
1816
  try {
143
1817
  return resolveLoaderPath(basename, import.meta.url);
144
1818
  } catch {
145
- const runtimeDir = resolveRuntimeDir();
1819
+ const runtimeDir = resolveRuntimeDir2();
146
1820
  const candidates = [
147
- path2.resolve(runtimeDir, `${basename}.mjs`),
148
- path2.resolve(runtimeDir, `${basename}.js`),
149
- path2.resolve(runtimeDir, `${basename}.cjs`)
1821
+ path5__default.resolve(runtimeDir, `${basename}.mjs`),
1822
+ path5__default.resolve(runtimeDir, `${basename}.js`),
1823
+ path5__default.resolve(runtimeDir, `${basename}.cjs`)
150
1824
  ];
151
1825
  for (const candidate of candidates) {
152
- if (fs2.existsSync(candidate)) {
1826
+ if (fs5__default.existsSync(candidate)) {
153
1827
  return candidate;
154
1828
  }
155
1829
  }
@@ -160,8 +1834,8 @@ var resolveLoaderPath2 = (basename) => {
160
1834
  };
161
1835
  function checkNextVersion() {
162
1836
  try {
163
- const pkgPath = require2.resolve("next/package.json");
164
- const { version } = require2(pkgPath);
1837
+ const pkgPath = require3.resolve("next/package.json");
1838
+ const { version } = require3(pkgPath);
165
1839
  const major = Number.parseInt(version.split(".")[0], 10);
166
1840
  if (major < 15) {
167
1841
  console.warn(
@@ -187,19 +1861,20 @@ var createLoaderOptions = (options) => {
187
1861
  preserveImports: true
188
1862
  };
189
1863
  if (options.verbose !== void 0) opts.verbose = options.verbose;
190
- opts.safelistPath = options.safelistPath ?? path2.join(process.cwd(), "__tw_safelist.css");
1864
+ opts.safelistPath = options.safelistPath ?? path5__default.join(process.cwd(), ".next", "tailwind-styled-safelist.css");
191
1865
  return Object.freeze(opts);
192
1866
  };
193
1867
  var buildTurbopackRules = (loaderPath, loaderOptions) => {
194
1868
  const extensions = ["js", "jsx", "ts", "tsx", "mjs", "cjs"];
195
1869
  return Object.fromEntries(
196
1870
  extensions.map((ext) => [
197
- `*.${ext}`,
1871
+ `**/*.${ext}`,
1872
+ // ← recursive glob: match semua subdirectory, bukan hanya root
198
1873
  { loaders: [{ loader: loaderPath, options: loaderOptions }] }
199
1874
  ])
200
1875
  );
201
1876
  };
202
- var normalizeLoaderPath = (loaderPath) => path2.resolve(loaderPath);
1877
+ var normalizeLoaderPath = (loaderPath) => path5__default.resolve(loaderPath);
203
1878
  var applyWebpackRule = (config, options, loaderPath) => {
204
1879
  const loaderOptions = createLoaderOptions(options);
205
1880
  const rules = config.module?.rules ?? [];
@@ -223,6 +1898,7 @@ var applyWebpackRule = (config, options, loaderPath) => {
223
1898
  rules: [...rules, tailwindStyledRule]
224
1899
  };
225
1900
  const externalPackages = [
1901
+ "tailwind-styled-v4",
226
1902
  "@tailwind-styled/shared",
227
1903
  "@tailwind-styled/compiler",
228
1904
  "@tailwind-styled/engine",
@@ -288,9 +1964,204 @@ function withTailwindStyled(options = {}) {
288
1964
  return function wrap(nextConfig = {}) {
289
1965
  const previousWebpack = nextConfig.webpack;
290
1966
  const loaderOptions = createLoaderOptions(normalizedOptions);
1967
+ try {
1968
+ const safelistPath = loaderOptions.safelistPath;
1969
+ if (safelistPath) {
1970
+ let extractUtilitiesLayer2 = function(fullCss) {
1971
+ const minified = fullCss.indexOf("@layer utilities{");
1972
+ const spaced = fullCss.indexOf("@layer utilities {");
1973
+ const startIdx = minified !== -1 ? minified : spaced !== -1 ? spaced : -1;
1974
+ if (startIdx === -1) return "";
1975
+ let depth = 0;
1976
+ let endIdx = startIdx;
1977
+ for (let i = startIdx; i < fullCss.length; i++) {
1978
+ if (fullCss[i] === "{") depth++;
1979
+ else if (fullCss[i] === "}") {
1980
+ depth--;
1981
+ if (depth === 0) {
1982
+ endIdx = i;
1983
+ break;
1984
+ }
1985
+ }
1986
+ }
1987
+ return fullCss.slice(startIdx, endIdx + 1);
1988
+ };
1989
+ 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"),
1994
+ String(Date.now()),
1995
+ "utf-8"
1996
+ );
1997
+ if (!process.env.TW_NATIVE_PATH) {
1998
+ const runtimeDir = resolveRuntimeDir2();
1999
+ const nativePath = path5__default.resolve(runtimeDir, "..", "native", "tailwind-styled-native.node");
2000
+ if (fs5__default.existsSync(nativePath)) {
2001
+ process.env.TW_NATIVE_PATH = nativePath;
2002
+ }
2003
+ }
2004
+ const srcDir = path5__default.join(process.cwd(), "src");
2005
+ if (fs5__default.existsSync(srcDir)) {
2006
+ try {
2007
+ const result = scanWorkspace(srcDir);
2008
+ if (result.uniqueClasses.length > 0) {
2009
+ let atomicWriteFile2 = function(filePath, content) {
2010
+ const tmpPath = `${filePath}.tmp`;
2011
+ try {
2012
+ fs5__default.writeFileSync(tmpPath, content, "utf-8");
2013
+ fs5__default.renameSync(tmpPath, filePath);
2014
+ } catch {
2015
+ try {
2016
+ fs5__default.unlinkSync(tmpPath);
2017
+ } catch {
2018
+ }
2019
+ fs5__default.writeFileSync(filePath, content, "utf-8");
2020
+ }
2021
+ };
2022
+ var atomicWriteFile = atomicWriteFile2;
2023
+ const VALID_VARIANT_PREFIXES = /* @__PURE__ */ new Set([
2024
+ "hover",
2025
+ "focus",
2026
+ "active",
2027
+ "disabled",
2028
+ "visited",
2029
+ "checked",
2030
+ "first",
2031
+ "last",
2032
+ "odd",
2033
+ "even",
2034
+ "focus-within",
2035
+ "focus-visible",
2036
+ "placeholder",
2037
+ "before",
2038
+ "after",
2039
+ "dark",
2040
+ "sm",
2041
+ "md",
2042
+ "lg",
2043
+ "xl",
2044
+ "2xl",
2045
+ "motion-reduce",
2046
+ "motion-safe",
2047
+ "group",
2048
+ "peer",
2049
+ "aria",
2050
+ "data",
2051
+ "supports",
2052
+ "not",
2053
+ "has",
2054
+ "is",
2055
+ "where",
2056
+ "rtl",
2057
+ "ltr",
2058
+ "open",
2059
+ "print",
2060
+ "portrait",
2061
+ "landscape"
2062
+ ]);
2063
+ const filteredClasses = result.uniqueClasses.filter((cls) => {
2064
+ if (cls.includes(":")) {
2065
+ const prefix = cls.split(":")[0];
2066
+ if (!VALID_VARIANT_PREFIXES.has(prefix ?? "")) return false;
2067
+ }
2068
+ if (/\[[\d]+\.[\d]{2,}(?:px|rem|em|vh|vw|%)\]/.test(cls)) return false;
2069
+ if (/\[[\d]{5,}(?:px|rem|em)?\]/.test(cls)) return false;
2070
+ return true;
2071
+ });
2072
+ let cssEntryContent = null;
2073
+ const CSS_CANDIDATES = [
2074
+ "src/app/globals.css",
2075
+ "src/globals.css",
2076
+ "src/styles/globals.css",
2077
+ "src/tailwind.css",
2078
+ "src/index.css",
2079
+ "styles/globals.css"
2080
+ ];
2081
+ 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"));
2085
+ const cssEntry = twConfig.css?.entry;
2086
+ 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");
2090
+ }
2091
+ }
2092
+ }
2093
+ } catch {
2094
+ }
2095
+ if (!cssEntryContent) {
2096
+ 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");
2100
+ break;
2101
+ }
2102
+ }
2103
+ }
2104
+ if (cssEntryContent) {
2105
+ cssEntryContent = cssEntryContent.replace(/@source\s+["'][^"']+["']\s*;?\s*/g, "").replace(/←[^\n]*/g, "").trim();
2106
+ }
2107
+ const initialScanPath = path5__default.join(twClassesDir, "_initial-scan.css");
2108
+ if (!fs5__default.existsSync(initialScanPath)) {
2109
+ atomicWriteFile2(
2110
+ initialScanPath,
2111
+ "/* tw-classes: initial scan \u2014 generating... */\n@layer utilities {}\n"
2112
+ );
2113
+ }
2114
+ void (async () => {
2115
+ try {
2116
+ const compiler = await Promise.resolve().then(() => (init_src2(), src_exports));
2117
+ const generateCssForClasses2 = compiler.generateCssForClasses;
2118
+ const css = await generateCssForClasses2(
2119
+ filteredClasses,
2120
+ {},
2121
+ process.cwd(),
2122
+ cssEntryContent ?? void 0,
2123
+ process.env.NODE_ENV === "production"
2124
+ // minify hanya di production
2125
+ );
2126
+ if (css) {
2127
+ const utilitiesOnly = extractUtilitiesLayer2(css);
2128
+ atomicWriteFile2(
2129
+ initialScanPath,
2130
+ `/* tw-classes: initial scan \u2014 auto-generated by withTailwindStyled */
2131
+ ${utilitiesOnly}`
2132
+ );
2133
+ }
2134
+ } 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);
2143
+ }
2144
+ })();
2145
+ }
2146
+ } catch (e) {
2147
+ console.warn("[tailwind-styled] Initial scan skipped:", e.message?.split("\n")[0]);
2148
+ }
2149
+ }
2150
+ }
2151
+ } catch {
2152
+ }
291
2153
  return {
292
2154
  ...nextConfig,
293
2155
  webpack(config, webpackOptions) {
2156
+ if (webpackOptions.dev) {
2157
+ if (typeof previousWebpack !== "function") return config;
2158
+ try {
2159
+ const r = previousWebpack(config, webpackOptions);
2160
+ return r instanceof Promise ? r : r;
2161
+ } catch {
2162
+ return config;
2163
+ }
2164
+ }
294
2165
  const apply = (resolvedConfig) => {
295
2166
  const finalConfig = applyWebpackRule(resolvedConfig, normalizedOptions, webpackLoaderPath);
296
2167
  if (!finalConfig.externals) {
@@ -319,6 +2190,20 @@ function withTailwindStyled(options = {}) {
319
2190
  });
320
2191
  }
321
2192
  },
2193
+ serverExternalPackages: [
2194
+ .../* @__PURE__ */ new Set([
2195
+ ...nextConfig.serverExternalPackages ?? [],
2196
+ "tailwind-styled-v4",
2197
+ "@tailwind-styled/core",
2198
+ "@tailwind-styled/shared",
2199
+ "@tailwind-styled/compiler",
2200
+ "@tailwind-styled/engine",
2201
+ "@tailwind-styled/analyzer",
2202
+ "@tailwind-styled/scanner",
2203
+ "@tailwind-styled/plugin",
2204
+ "@tailwind-styled/runtime-css"
2205
+ ])
2206
+ ],
322
2207
  turbopack: {
323
2208
  ...nextConfig.turbopack ?? {},
324
2209
  rules: mergeTurbopackRules(