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.js CHANGED
@@ -1,52 +1,64 @@
1
1
  'use strict';
2
2
 
3
- var zod = require('zod');
4
- var fs2 = require('fs');
5
3
  var module$1 = require('module');
6
- var path2 = require('path');
4
+ var fs5 = require('fs');
5
+ var path5 = require('path');
7
6
  require('crypto');
8
- require('url');
7
+ var url = require('url');
8
+ var zod = require('zod');
9
+ require('worker_threads');
9
10
 
10
11
  var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
11
- function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
12
+ function _interopNamespace(e) {
13
+ if (e && e.__esModule) return e;
14
+ var n = Object.create(null);
15
+ if (e) {
16
+ Object.keys(e).forEach(function (k) {
17
+ if (k !== 'default') {
18
+ var d = Object.getOwnPropertyDescriptor(e, k);
19
+ Object.defineProperty(n, k, d.get ? d : {
20
+ enumerable: true,
21
+ get: function () { return e[k]; }
22
+ });
23
+ }
24
+ });
25
+ }
26
+ n.default = e;
27
+ return Object.freeze(n);
28
+ }
12
29
 
13
- var fs2__default = /*#__PURE__*/_interopDefault(fs2);
14
- var path2__default = /*#__PURE__*/_interopDefault(path2);
30
+ var fs5__namespace = /*#__PURE__*/_interopNamespace(fs5);
31
+ var path5__namespace = /*#__PURE__*/_interopNamespace(path5);
15
32
 
16
33
  /* tailwind-styled-v4 v5.0.4 | MIT | https://github.com/dictionar32/tailwind-styled-v4 */
34
+ var __defProp = Object.defineProperty;
35
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
36
+ var __getOwnPropNames = Object.getOwnPropertyNames;
37
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
17
38
  var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
18
39
  get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
19
40
  }) : x)(function(x) {
20
41
  if (typeof require !== "undefined") return require.apply(this, arguments);
21
42
  throw Error('Dynamic require of "' + x + '" is not supported');
22
43
  });
23
- var formatIssues = (error) => error.issues.map((issue) => {
24
- const p = issue.path.length > 0 ? issue.path.join(".") : "<root>";
25
- return `${p}: ${issue.message}`;
26
- }).join("; ");
27
- var parseWithSchema = (schema, data, label) => {
28
- const parsed = schema.safeParse(data);
29
- if (parsed.success) return parsed.data;
30
- throw new TypeError(`${label}: ${formatIssues(parsed.error)}`);
44
+ var __esm = (fn, res) => function __init() {
45
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
31
46
  };
32
- var NextAdapterOptionsSchema = zod.z.object({
33
- mode: zod.z.literal("zero-runtime").optional(),
34
- autoClientBoundary: zod.z.boolean().optional(),
35
- addDataAttr: zod.z.boolean().optional(),
36
- hoist: zod.z.boolean().optional(),
37
- routeCss: zod.z.boolean().optional(),
38
- incremental: zod.z.boolean().optional(),
39
- verbose: zod.z.boolean().optional(),
40
- include: zod.z.instanceof(RegExp).optional(),
41
- exclude: zod.z.instanceof(RegExp).optional()
42
- });
43
- var parseNextAdapterOptions = (options) => parseWithSchema(NextAdapterOptionsSchema, options ?? {}, "next adapter options are invalid");
47
+ var __export = (target, all) => {
48
+ for (var name in all)
49
+ __defProp(target, name, { get: all[name], enumerable: true });
50
+ };
51
+ var __copyProps = (to, from, except, desc) => {
52
+ if (from && typeof from === "object" || typeof from === "function") {
53
+ for (let key of __getOwnPropNames(from))
54
+ if (!__hasOwnProp.call(to, key) && key !== except)
55
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
56
+ }
57
+ return to;
58
+ };
59
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
44
60
 
45
61
  // packages/domain/shared/src/workerResolver.ts
46
- var isBrowser = typeof window !== "undefined" || typeof document !== "undefined";
47
- var NODE_URL = typeof window === "undefined" || typeof document === "undefined" ? "node:url" : null;
48
- var NODE_FS = typeof window === "undefined" || typeof document === "undefined" ? "node:fs" : null;
49
- var NODE_PATH = typeof window === "undefined" || typeof document === "undefined" ? "node:path" : null;
50
62
  function getDirnameFromUrl(importMetaUrl) {
51
63
  if (!importMetaUrl) return "";
52
64
  if (isBrowser) return "";
@@ -72,11 +84,11 @@ function resolvePath(...segments) {
72
84
  return segments.join("/").replace(/\/+/g, "/");
73
85
  }
74
86
  }
75
- function existsSync(path3) {
87
+ function existsSync(path7) {
76
88
  if (isBrowser) return false;
77
89
  try {
78
90
  const nodeFs = __require(NODE_FS);
79
- return nodeFs.existsSync(path3);
91
+ return nodeFs.existsSync(path7);
80
92
  } catch {
81
93
  return false;
82
94
  }
@@ -126,9 +138,1685 @@ function resolveLoaderPath(loaderBasename, importMetaUrl) {
126
138
  subdirs: [".", "loaders", "lib"]
127
139
  }).path;
128
140
  }
141
+ var isBrowser, NODE_URL, NODE_FS, NODE_PATH;
142
+ var init_workerResolver = __esm({
143
+ "packages/domain/shared/src/workerResolver.ts"() {
144
+ isBrowser = typeof window !== "undefined" || typeof document !== "undefined";
145
+ NODE_URL = typeof window === "undefined" || typeof document === "undefined" ? "node:url" : null;
146
+ NODE_FS = typeof window === "undefined" || typeof document === "undefined" ? "node:fs" : null;
147
+ NODE_PATH = typeof window === "undefined" || typeof document === "undefined" ? "node:path" : null;
148
+ }
149
+ });
150
+ function platformKey() {
151
+ if (isBrowser2) return "browser";
152
+ return `${process.platform}-${process.arch}`;
153
+ }
154
+ function resolveNativeBinary(runtimeDir) {
155
+ const platform = platformKey();
156
+ const tried = [];
157
+ if (isBrowser2) {
158
+ return { path: null, source: "not-found", platform, tried: ["not available in browser"] };
159
+ }
160
+ if (process.env.TWS_DISABLE_NATIVE === "1") {
161
+ return { path: null, source: "not-found", platform, tried: [] };
162
+ }
163
+ const envPath = process.env.TW_NATIVE_PATH?.trim();
164
+ if (envPath) {
165
+ if (fs5__namespace.existsSync(envPath)) {
166
+ return { path: envPath, source: "env", platform, tried };
167
+ }
168
+ tried.push(`env:${envPath} (not found)`);
169
+ }
170
+ const prebuiltPkgs = PLATFORM_MAP[platform] ?? [];
171
+ for (const pkg of prebuiltPkgs) {
172
+ try {
173
+ const candidate = _require.resolve(`${pkg}/tailwind_styled_parser.node`);
174
+ if (fs5__namespace.existsSync(candidate)) {
175
+ return { path: candidate, source: "prebuilt", platform, tried };
176
+ }
177
+ tried.push(`prebuilt:${pkg} (resolved but missing)`);
178
+ } catch {
179
+ tried.push(`prebuilt:${pkg} (not installed)`);
180
+ }
181
+ }
182
+ const napiPlatform = platform === "linux-x64" ? "linux-x64-gnu" : platform === "linux-arm64" ? "linux-arm64-gnu" : platform;
183
+ const BINARY_NAMES_SELF = ["tailwind-styled-native", "tailwind_styled_parser"];
184
+ if (runtimeDir) {
185
+ for (const depth of ["..", path5__namespace.join("..", ".."), path5__namespace.join("..", "..", "..")]) {
186
+ const pkgRoot = path5__namespace.resolve(runtimeDir, depth);
187
+ for (const bin of BINARY_NAMES_SELF) {
188
+ for (const suffix of ["", `.${platform}`, `.${napiPlatform}`]) {
189
+ const candidate = path5__namespace.resolve(pkgRoot, "native", `${bin}${suffix}.node`);
190
+ tried.push(`self-bundled:${candidate}`);
191
+ if (fs5__namespace.existsSync(candidate)) {
192
+ return { path: candidate, source: "prebuilt", platform, tried };
193
+ }
194
+ }
195
+ }
196
+ }
197
+ }
198
+ const cwd = process.cwd();
199
+ const base = runtimeDir ?? cwd;
200
+ const BINARY_NAMES = ["tailwind-styled-native", "tailwind_styled_parser"];
201
+ const localCandidates = [];
202
+ for (const bin of BINARY_NAMES) {
203
+ localCandidates.push(path5__namespace.resolve(base, `${bin}.node`));
204
+ localCandidates.push(path5__namespace.resolve(base, "..", `${bin}.node`));
205
+ localCandidates.push(path5__namespace.resolve(base, `${bin}.${platform}.node`));
206
+ localCandidates.push(path5__namespace.resolve(base, `${bin}.${napiPlatform}.node`));
207
+ }
208
+ for (const startDir of [cwd, base]) {
209
+ let dir = startDir;
210
+ for (let i = 0; i < 6; i++) {
211
+ const nativeDir = path5__namespace.resolve(dir, "native");
212
+ for (const bin of BINARY_NAMES) {
213
+ localCandidates.push(path5__namespace.resolve(nativeDir, `${bin}.node`));
214
+ localCandidates.push(path5__namespace.resolve(nativeDir, `${bin}.${platform}.node`));
215
+ localCandidates.push(path5__namespace.resolve(nativeDir, `${bin}.${napiPlatform}.node`));
216
+ localCandidates.push(path5__namespace.resolve(nativeDir, "target", "release", `${bin}.node`));
217
+ }
218
+ const parent = path5__namespace.resolve(dir, "..");
219
+ if (parent === dir) break;
220
+ dir = parent;
221
+ }
222
+ }
223
+ for (const candidate of localCandidates) {
224
+ tried.push(`local:${candidate}`);
225
+ if (fs5__namespace.existsSync(candidate)) {
226
+ return { path: candidate, source: "local", platform, tried };
227
+ }
228
+ }
229
+ return { path: null, source: "not-found", platform, tried };
230
+ }
231
+ var isBrowser2, _require, PLATFORM_MAP;
232
+ var init_native_resolution = __esm({
233
+ "packages/domain/shared/src/native-resolution.ts"() {
234
+ isBrowser2 = typeof window !== "undefined" || typeof document !== "undefined";
235
+ _require = typeof __require !== "undefined" ? __require : module$1.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('next.js', document.baseURI).href)));
236
+ PLATFORM_MAP = {
237
+ "linux-x64": ["@tailwind-styled/native-linux-x64-gnu", "@tailwind-styled/native-linux-x64"],
238
+ "linux-arm64": ["@tailwind-styled/native-linux-arm64-gnu", "@tailwind-styled/native-linux-arm64"],
239
+ "darwin-x64": ["@tailwind-styled/native-darwin-x64"],
240
+ "darwin-arm64": ["@tailwind-styled/native-darwin-arm64"],
241
+ "win32-x64": ["@tailwind-styled/native-win32-x64-msvc", "@tailwind-styled/native-win32-x64"],
242
+ "win32-arm64": ["@tailwind-styled/native-win32-arm64-msvc", "@tailwind-styled/native-win32-arm64"]
243
+ };
244
+ }
245
+ });
246
+ function createLogger(namespace) {
247
+ const prefix = `[${namespace}]`;
248
+ return {
249
+ warn(...args) {
250
+ process.stderr.write(`${prefix} ${args.map((a) => typeof a === "string" ? a : String(a)).join(" ")}
251
+ `);
252
+ },
253
+ debug(...args) {
254
+ process.stderr.write(`${prefix} ${args.map((a) => typeof a === "string" ? a : String(a)).join(" ")}
255
+ `);
256
+ },
257
+ error(...args) {
258
+ process.stderr.write(`${prefix} ${args.map((a) => typeof a === "string" ? a : String(a)).join(" ")}
259
+ `);
260
+ },
261
+ log(...args) {
262
+ process.stderr.write(`${prefix} ${args.map((a) => typeof a === "string" ? a : String(a)).join(" ")}
263
+ `);
264
+ }
265
+ };
266
+ }
267
+ function createDebugLogger(namespace, label) {
268
+ const prefix = `[${namespace}]`;
269
+ return (msg) => {
270
+ if (process.env.DEBUG?.includes(namespace) || process.env.TW_DEBUG) {
271
+ console.debug(prefix, msg);
272
+ }
273
+ };
274
+ }
275
+ function formatIssuePath(path7) {
276
+ if (!path7 || path7.length === 0) return "(root)";
277
+ return path7.map(
278
+ (segment) => typeof segment === "symbol" ? segment.description ?? segment.toString() : String(segment)
279
+ ).join(".");
280
+ }
281
+ function loadNativeBinding(options) {
282
+ const { runtimeDir, candidates, isValid } = options;
283
+ const loadErrors = [];
284
+ for (const candidate of candidates) {
285
+ const candidatePath = path5__namespace.default.resolve(runtimeDir, candidate);
286
+ try {
287
+ if (!fs5__namespace.default.existsSync(candidatePath) && !fs5__namespace.default.existsSync(candidatePath + ".node")) {
288
+ continue;
289
+ }
290
+ const mod = requireNativeModule(candidatePath);
291
+ if (mod && isValid(mod)) {
292
+ return { binding: mod, loadErrors, loadedPath: candidatePath };
293
+ }
294
+ loadErrors.push({ path: candidatePath, message: options.invalidExportMessage });
295
+ } catch (e) {
296
+ loadErrors.push({ path: candidatePath, message: e instanceof Error ? e.message : String(e) });
297
+ }
298
+ }
299
+ return { binding: null, loadErrors };
300
+ }
301
+ function requireNativeModule(p) {
302
+ return _require2(p);
303
+ }
304
+ function resolveNativeBindingCandidates(options) {
305
+ const {
306
+ envVarNames = ["TW_NATIVE_PATH", "TWS_NATIVE_PATH"],
307
+ includeDefaultCandidates = true,
308
+ enforceNodeExtensionForEnvPath = false
309
+ } = options;
310
+ const runtimeDir = options.runtimeDir || process.cwd();
311
+ const candidates = [];
312
+ for (const envVar of envVarNames) {
313
+ const envPath = process.env[envVar];
314
+ if (envPath) {
315
+ candidates.push(enforceNodeExtensionForEnvPath && !envPath.endsWith(".node") ? envPath + ".node" : envPath);
316
+ }
317
+ }
318
+ if (!includeDefaultCandidates) return candidates;
319
+ if (fs5__namespace.default.existsSync(runtimeDir)) {
320
+ try {
321
+ for (const entry of fs5__namespace.default.readdirSync(runtimeDir)) {
322
+ if (entry.endsWith(".node")) candidates.push(entry);
323
+ }
324
+ } catch {
325
+ }
326
+ }
327
+ const BINARY_NAMES = ["tailwind-styled-native", "tailwind_styled_parser"];
328
+ const napiPlatform = process.platform === "linux" && process.arch === "x64" ? "linux-x64-gnu" : process.platform === "linux" && process.arch === "arm64" ? "linux-arm64-gnu" : `${process.platform}-${process.arch}`;
329
+ for (const bin of BINARY_NAMES) {
330
+ candidates.push(path5__namespace.default.resolve(runtimeDir, `${bin}.node`));
331
+ candidates.push(path5__namespace.default.resolve(runtimeDir, `${bin}.${napiPlatform}.node`));
332
+ candidates.push(path5__namespace.default.resolve(runtimeDir, "..", "native", `${bin}.node`));
333
+ candidates.push(path5__namespace.default.resolve(runtimeDir, "..", "native", `${bin}.${napiPlatform}.node`));
334
+ candidates.push(path5__namespace.default.resolve(process.cwd(), "native", `${bin}.node`));
335
+ candidates.push(path5__namespace.default.resolve(process.cwd(), "native", `${bin}.${napiPlatform}.node`));
336
+ candidates.push(path5__namespace.default.resolve(runtimeDir, "..", "..", "..", "..", "native", `${bin}.node`));
337
+ candidates.push(path5__namespace.default.resolve(runtimeDir, "..", "..", "..", "..", "native", `${bin}.${napiPlatform}.node`));
338
+ candidates.push(path5__namespace.default.resolve(runtimeDir, "..", "..", "..", "native", `${bin}.node`));
339
+ }
340
+ return Array.from(new Set(candidates));
341
+ }
342
+ function resolveRuntimeDir(dir, importMetaUrl) {
343
+ try {
344
+ return path5__namespace.default.dirname(url.fileURLToPath(importMetaUrl));
345
+ } catch {
346
+ return process.cwd();
347
+ }
348
+ }
349
+ var TwError, _require2;
350
+ var init_src = __esm({
351
+ "packages/domain/shared/src/index.ts"() {
352
+ init_workerResolver();
353
+ init_native_resolution();
354
+ TwError = class _TwError extends Error {
355
+ /** @deprecated Gunakan source */
356
+ domain;
357
+ source;
358
+ code;
359
+ originalCause;
360
+ constructor(domainOrSource, code, message, cause) {
361
+ super(message);
362
+ this.name = "TwError";
363
+ this.domain = domainOrSource;
364
+ this.source = domainOrSource;
365
+ this.code = code;
366
+ this.originalCause = cause;
367
+ if (Error.captureStackTrace) Error.captureStackTrace(this, _TwError);
368
+ }
369
+ static fromIo(code, message) {
370
+ return new _TwError("io", code, message);
371
+ }
372
+ static fromCompile(code, message) {
373
+ return new _TwError("compile", code, message);
374
+ }
375
+ static fromRust(err) {
376
+ if (err instanceof _TwError) return err;
377
+ if (err instanceof Error) return new _TwError("rust", "RUST_ERROR", err.message, err);
378
+ if (err && typeof err === "object") {
379
+ const e = err;
380
+ return new _TwError("rust", e.code ?? "RUST_ERROR", e.message ?? String(err), err);
381
+ }
382
+ return new _TwError("rust", "RUST_ERROR", String(err), err);
383
+ }
384
+ /** Buat TwError dari ZodError — dukung shape Zod v3 (`errors`) dan v4 (`issues`). */
385
+ static fromZod(err) {
386
+ const first = err.issues?.[0] ?? err.errors?.[0];
387
+ const path7 = formatIssuePath(first?.path);
388
+ const message = first ? `${path7}: ${first.message}` : "Schema validation failed";
389
+ return new _TwError("validation", "SCHEMA_VALIDATION_FAILED", message, err);
390
+ }
391
+ static wrap(source, code, err) {
392
+ if (err instanceof _TwError) return err;
393
+ if (err instanceof Error) return new _TwError(source, code, err.message, err);
394
+ return new _TwError(source, code, String(err), err);
395
+ }
396
+ toString() {
397
+ return `TwError [${this.source}:${this.code}] ${this.message}`;
398
+ }
399
+ toJSON() {
400
+ return { name: this.name, source: this.source, code: this.code, message: this.message };
401
+ }
402
+ toCliMessage() {
403
+ return `[${this.source.toUpperCase()}:${this.code}] ${this.message}`;
404
+ }
405
+ };
406
+ _require2 = module$1.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('next.js', document.baseURI).href)));
407
+ }
408
+ });
409
+
410
+ // packages/domain/scanner/src/native-bridge.ts
411
+ var native_bridge_exports = {};
412
+ __export(native_bridge_exports, {
413
+ batchExtractClassesNative: () => batchExtractClassesNative,
414
+ cachePriorityNative: () => cachePriorityNative,
415
+ cacheReadNative: () => cacheReadNative,
416
+ cacheWriteNative: () => cacheWriteNative,
417
+ collectFilesNative: () => collectFilesNative,
418
+ computeCacheStatsNative: () => computeCacheStatsNative,
419
+ extractClassesNative: () => extractClassesNative,
420
+ generateSubComponentTypesNative: () => generateSubComponentTypesNative,
421
+ hasNativeScannerBinding: () => hasNativeScannerBinding,
422
+ hasNativeWatchBinding: () => hasNativeWatchBinding,
423
+ hashContentNative: () => hashContentNative,
424
+ isRustCacheAvailable: () => isRustCacheAvailable,
425
+ pollWatchEventsNative: () => pollWatchEventsNative,
426
+ pruneStaleEntriesNative: () => pruneStaleEntriesNative,
427
+ rebuildWorkspaceResultNative: () => rebuildWorkspaceResultNative,
428
+ resetScannerBridgeCache: () => resetScannerBridgeCache,
429
+ scanCacheGet: () => scanCacheGet,
430
+ scanCacheInvalidate: () => scanCacheInvalidate,
431
+ scanCachePut: () => scanCachePut,
432
+ scanCacheStats: () => scanCacheStats,
433
+ scanFileNative: () => scanFileNative,
434
+ scanFilesBatchNative: () => scanFilesBatchNative,
435
+ scanWorkspaceNative: () => scanWorkspaceNative,
436
+ startWatchNative: () => startWatchNative,
437
+ stopWatchNative: () => stopWatchNative
438
+ });
439
+ function getDirname() {
440
+ if (typeof __dirname !== "undefined") {
441
+ return __dirname;
442
+ }
443
+ if (typeof ({ url: (typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('next.js', document.baseURI).href)) }) !== "undefined" && (typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('next.js', document.baseURI).href))) {
444
+ return path5__namespace.default.dirname(url.fileURLToPath((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('next.js', document.baseURI).href))));
445
+ }
446
+ return process.cwd();
447
+ }
448
+ function scanWorkspaceNative(root, extensions) {
449
+ return scannerGetBinding().scanWorkspace(root, extensions ?? null);
450
+ }
451
+ function extractClassesNative(source) {
452
+ const result = scannerGetBinding().extractClassesFromSource?.(source);
453
+ if (result === null || result === void 0) {
454
+ throw new TwError(
455
+ "rust",
456
+ "SCANNER_EXTRACT_FAILED",
457
+ "Native extractClassesFromSource returned null/undefined"
458
+ );
459
+ }
460
+ return result;
461
+ }
462
+ function hashContentNative(content) {
463
+ const result = scannerGetBinding().hashFileContent?.(content);
464
+ if (result === null || result === void 0) {
465
+ throw new TwError(
466
+ "rust",
467
+ "SCANNER_HASH_FAILED",
468
+ "Native hashFileContent returned null/undefined"
469
+ );
470
+ }
471
+ return result;
472
+ }
473
+ function isRustCacheAvailable() {
474
+ return true;
475
+ }
476
+ function hasNativeScannerBinding() {
477
+ try {
478
+ scannerBridgeLoader.get();
479
+ return true;
480
+ } catch {
481
+ return false;
482
+ }
483
+ }
484
+ function cacheReadNative(cachePath) {
485
+ const result = scannerGetBinding().cacheRead?.(cachePath);
486
+ if (result === null || result === void 0) {
487
+ throw new TwError(
488
+ "rust",
489
+ "SCANNER_CACHE_READ_FAILED",
490
+ "Native cacheRead returned null/undefined"
491
+ );
492
+ }
493
+ return result;
494
+ }
495
+ function cacheWriteNative(cachePath, entries) {
496
+ const result = scannerGetBinding().cacheWrite?.(cachePath, entries);
497
+ if (result === null || result === void 0) {
498
+ throw new TwError(
499
+ "rust",
500
+ "SCANNER_CACHE_WRITE_FAILED",
501
+ "Native cacheWrite returned null/undefined"
502
+ );
503
+ }
504
+ return result;
505
+ }
506
+ function cachePriorityNative(mtimeMs, size, cachedMtimeMs, cachedSize, cachedHitCount, cachedLastSeenMs, nowMs = Date.now()) {
507
+ const result = scannerGetBinding().cachePriority?.(
508
+ mtimeMs,
509
+ size,
510
+ cachedMtimeMs,
511
+ cachedSize,
512
+ cachedHitCount,
513
+ cachedLastSeenMs,
514
+ nowMs
515
+ );
516
+ if (result === null || result === void 0) {
517
+ throw new TwError(
518
+ "rust",
519
+ "SCANNER_CACHE_PRIORITY_FAILED",
520
+ "Native cachePriority returned null/undefined"
521
+ );
522
+ }
523
+ return result;
524
+ }
525
+ function batchExtractClassesNative(filePaths) {
526
+ const binding = scannerGetBinding();
527
+ if (!binding.batchExtractClasses) {
528
+ throw new Error("FATAL: Native binding 'batchExtractClasses' is required but not available.");
529
+ }
530
+ return binding.batchExtractClasses(filePaths) ?? [];
531
+ }
532
+ function scanCacheGet(filePath, contentHash) {
533
+ const binding = scannerGetBinding();
534
+ if (!binding.scanCacheGet) {
535
+ throw new Error("FATAL: Native binding 'scanCacheGet' is required but not available.");
536
+ }
537
+ return binding.scanCacheGet(filePath, contentHash) ?? null;
538
+ }
539
+ function scanCachePut(filePath, contentHash, classes, mtimeMs, size) {
540
+ const binding = scannerGetBinding();
541
+ if (!binding.scanCachePut) {
542
+ throw new Error("FATAL: Native binding 'scanCachePut' is required but not available.");
543
+ }
544
+ binding.scanCachePut(filePath, contentHash, classes, mtimeMs, size);
545
+ }
546
+ function scanCacheInvalidate(filePath) {
547
+ const binding = scannerGetBinding();
548
+ if (!binding.scanCacheInvalidate) {
549
+ throw new Error("FATAL: Native binding 'scanCacheInvalidate' is required but not available.");
550
+ }
551
+ binding.scanCacheInvalidate(filePath);
552
+ }
553
+ function scanCacheStats() {
554
+ const binding = scannerGetBinding();
555
+ if (!binding.scanCacheStats) {
556
+ throw new Error("FATAL: Native binding 'scanCacheStats' is required but not available.");
557
+ }
558
+ return binding.scanCacheStats();
559
+ }
560
+ function scanFileNative(filePath) {
561
+ const binding = scannerGetBinding();
562
+ if (!binding.scanFile) {
563
+ throw new Error("FATAL: Native binding 'scanFile' is required but not available.");
564
+ }
565
+ return binding.scanFile(filePath);
566
+ }
567
+ function collectFilesNative(root, extensions, ignoreDirs) {
568
+ const binding = scannerGetBinding();
569
+ if (!binding.collectFiles) return null;
570
+ return binding.collectFiles(root, extensions, ignoreDirs);
571
+ }
572
+ function scanFilesBatchNative(filePaths) {
573
+ const binding = scannerGetBinding();
574
+ if (!binding.scanFilesBatch) {
575
+ return filePaths.map((fp) => {
576
+ try {
577
+ const r = binding.scanFile?.(fp);
578
+ return r ? { file: r.file, classes: r.classes, hash: r.hash ?? "" } : { file: fp, classes: [], hash: "" };
579
+ } catch {
580
+ return { file: fp, classes: [], hash: "" };
581
+ }
582
+ });
583
+ }
584
+ return binding.scanFilesBatch(filePaths);
585
+ }
586
+ function generateSubComponentTypesNative(root, outputPath) {
587
+ const binding = scannerGetBinding();
588
+ if (!binding.generateSubComponentTypes) return null;
589
+ return binding.generateSubComponentTypes(root, outputPath ?? null);
590
+ }
591
+ function pruneStaleEntriesNative(entries, maxAgeMs, checkExists) {
592
+ const binding = scannerGetBinding();
593
+ if (!binding.pruneStaleEntries) return null;
594
+ return binding.pruneStaleEntries(
595
+ entries.map((e) => ({ file: e.file, lastSeenMs: e.lastSeenMs ?? 0 })),
596
+ maxAgeMs ?? null,
597
+ checkExists ?? null
598
+ );
599
+ }
600
+ function rebuildWorkspaceResultNative(files) {
601
+ const binding = scannerBridgeLoader.get();
602
+ if (!binding?.rebuildWorkspaceResult) return null;
603
+ try {
604
+ return binding.rebuildWorkspaceResult(files);
605
+ } catch {
606
+ return null;
607
+ }
608
+ }
609
+ function computeCacheStatsNative(filesClasses, sizes, top) {
610
+ const binding = scannerGetBinding();
611
+ if (!binding.computeCacheStats) return null;
612
+ return binding.computeCacheStats(filesClasses, sizes, top ?? null);
613
+ }
614
+ function startWatchNative(rootDir) {
615
+ try {
616
+ const binding = scannerGetBinding();
617
+ if (!binding.startWatch) return null;
618
+ return binding.startWatch(rootDir);
619
+ } catch {
620
+ return null;
621
+ }
622
+ }
623
+ function pollWatchEventsNative(handleId) {
624
+ try {
625
+ const binding = scannerGetBinding();
626
+ if (!binding.pollWatchEvents) return [];
627
+ return binding.pollWatchEvents(handleId);
628
+ } catch {
629
+ return [];
630
+ }
631
+ }
632
+ function stopWatchNative(handleId) {
633
+ try {
634
+ const binding = scannerGetBinding();
635
+ if (!binding.stopWatch) return false;
636
+ return binding.stopWatch(handleId);
637
+ } catch {
638
+ return false;
639
+ }
640
+ }
641
+ function hasNativeWatchBinding() {
642
+ try {
643
+ const binding = scannerGetBinding();
644
+ return !!(binding.startWatch && binding.pollWatchEvents && binding.stopWatch);
645
+ } catch {
646
+ return false;
647
+ }
648
+ }
649
+ var log, isValidScannerBinding, createScannerBridgeLoader, scannerBridgeLoader, scannerGetBinding, resetScannerBridgeCache;
650
+ var init_native_bridge = __esm({
651
+ "packages/domain/scanner/src/native-bridge.ts"() {
652
+ init_src();
653
+ log = createDebugLogger("scanner:native");
654
+ isValidScannerBinding = (module) => {
655
+ const candidate = module;
656
+ return !!(candidate && (candidate.scanWorkspace || candidate.extractClassesFromSource || candidate.hashFileContent || candidate.cacheRead || candidate.cacheWrite));
657
+ };
658
+ createScannerBridgeLoader = () => {
659
+ const _state = {
660
+ binding: void 0,
661
+ loadError: null,
662
+ candidatePaths: []
663
+ };
664
+ const throwNativeBindingError = () => {
665
+ const lines = [
666
+ "FATAL: Native scanner binding not found.",
667
+ "",
668
+ "This package requires the Rust native binding 'tailwind_styled_parser.node'.",
669
+ "The binding was not found in any of these paths:",
670
+ ..._state.candidatePaths.map((p) => ` - ${p}`),
671
+ ""
672
+ ];
673
+ if (_state.loadError) {
674
+ lines.push("Load error:", ` ${_state.loadError}`, "");
675
+ }
676
+ lines.push(
677
+ "To fix this, run:",
678
+ " npm run build:rust",
679
+ "",
680
+ "This will build the native Rust module from the 'native/' directory.",
681
+ "If you're using this package in a CI/CD environment, ensure Rust toolchain is installed",
682
+ "and 'npm run build:rust' is executed before running tests or building."
683
+ );
684
+ throw new TwError("rust", "SCANNER_NATIVE_BINDING_NOT_FOUND", lines.join("\n"));
685
+ };
686
+ const scannerGetBinding2 = () => {
687
+ const cachedBinding = _state.binding;
688
+ if (cachedBinding !== void 0) {
689
+ if (cachedBinding !== null) {
690
+ return cachedBinding;
691
+ }
692
+ return throwNativeBindingError();
693
+ }
694
+ const runtimeDir = getDirname();
695
+ const candidates = resolveNativeBindingCandidates({
696
+ runtimeDir,
697
+ includeDefaultCandidates: true
698
+ });
699
+ _state.candidatePaths = candidates;
700
+ const { binding, loadErrors } = loadNativeBinding({
701
+ runtimeDir,
702
+ candidates,
703
+ isValid: isValidScannerBinding,
704
+ invalidExportMessage: "Module loaded but missing expected scanner binding functions"
705
+ });
706
+ if (binding) {
707
+ log(`scanner native binding loaded successfully`);
708
+ _state.binding = binding;
709
+ return _state.binding;
710
+ }
711
+ if (loadErrors.length > 0) {
712
+ _state.loadError = loadErrors.map((e) => `${e.path}: ${e.message}`).join("; ");
713
+ }
714
+ _state.binding = null;
715
+ return throwNativeBindingError();
716
+ };
717
+ return {
718
+ get: scannerGetBinding2,
719
+ scannerGetBinding: scannerGetBinding2,
720
+ reset: () => {
721
+ _state.binding = void 0;
722
+ _state.loadError = null;
723
+ _state.candidatePaths = [];
724
+ }
725
+ };
726
+ };
727
+ scannerBridgeLoader = createScannerBridgeLoader();
728
+ scannerGetBinding = scannerBridgeLoader.get;
729
+ resetScannerBridgeCache = scannerBridgeLoader.reset;
730
+ }
731
+ });
732
+
733
+ // packages/domain/compiler/src/nativeBridge.ts
734
+ var _loadNative, log3, NATIVE_UNAVAILABLE_MESSAGE, nativeBridge, bridgeLoadAttempted, bridgeLoadError, isValidNativeBridge, getNativeBridge, resetNativeBridgeCache, adaptNativeResult;
735
+ var init_nativeBridge = __esm({
736
+ "packages/domain/compiler/src/nativeBridge.ts"() {
737
+ init_src();
738
+ _loadNative = (path7) => __require(path7);
739
+ log3 = (...args) => {
740
+ if (process.env.DEBUG?.includes("compiler:native")) {
741
+ console.log("[compiler:native]", ...args);
742
+ }
743
+ };
744
+ NATIVE_UNAVAILABLE_MESSAGE = "[tailwind-styled/compiler v5] Native binding is required but not available.\nThis package requires native Rust bindings. There is no JavaScript fallback.\nPlease ensure:\n 1. The native module is properly installed\n 2. You have run: npm run build:rust (or use prebuilt binary)\n\nFor help, see: https://tailwind-styled.dev/docs/install";
745
+ nativeBridge = null;
746
+ bridgeLoadAttempted = false;
747
+ bridgeLoadError = null;
748
+ isValidNativeBridge = (mod) => {
749
+ const m = mod;
750
+ return !!(typeof m.transformSource === "function" || typeof m.extractAllClasses === "function" || typeof m.hasTwUsage === "function");
751
+ };
752
+ getNativeBridge = () => {
753
+ if (nativeBridge) {
754
+ return nativeBridge;
755
+ }
756
+ if (bridgeLoadAttempted) {
757
+ if (bridgeLoadError) {
758
+ throw bridgeLoadError;
759
+ }
760
+ throw new Error(NATIVE_UNAVAILABLE_MESSAGE);
761
+ }
762
+ bridgeLoadAttempted = true;
763
+ try {
764
+ const runtimeDir = resolveRuntimeDir(void 0, (typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('next.js', document.baseURI).href)));
765
+ const result = resolveNativeBinary(runtimeDir);
766
+ if (result.path && result.path.endsWith(".node")) {
767
+ try {
768
+ const binding = _loadNative(result.path);
769
+ if (isValidNativeBridge(binding)) {
770
+ nativeBridge = binding;
771
+ log3("Native bridge loaded successfully from:", result.path);
772
+ return nativeBridge;
773
+ }
774
+ } catch (e) {
775
+ log3("Failed to require native binding:", e);
776
+ }
777
+ }
778
+ throw new Error(`${NATIVE_UNAVAILABLE_MESSAGE}
779
+
780
+ Tried paths: ${result.tried.join("\n")}`);
781
+ } catch (err) {
782
+ bridgeLoadError = err instanceof Error ? err : new Error(String(err));
783
+ log3("Failed to load native bridge:", bridgeLoadError.message);
784
+ throw bridgeLoadError;
785
+ }
786
+ };
787
+ resetNativeBridgeCache = () => {
788
+ nativeBridge = null;
789
+ bridgeLoadAttempted = false;
790
+ bridgeLoadError = null;
791
+ log3("Native bridge cache reset");
792
+ };
793
+ adaptNativeResult = (raw) => {
794
+ return {
795
+ code: raw.code ?? "",
796
+ classes: raw.classes ?? [],
797
+ changed: raw.changed ?? false,
798
+ rsc: raw.rscJson ? JSON.parse(raw.rscJson) : void 0,
799
+ metadata: raw.metadataJson ? JSON.parse(raw.metadataJson) : void 0
800
+ };
801
+ };
802
+ if (typeof process !== "undefined" && !bridgeLoadAttempted) {
803
+ try {
804
+ getNativeBridge();
805
+ } catch {
806
+ }
807
+ }
808
+ }
809
+ });
810
+
811
+ // packages/domain/compiler/src/tailwindEngine.ts
812
+ var tailwindEngine_exports = {};
813
+ __export(tailwindEngine_exports, {
814
+ generateRawCss: () => generateRawCss,
815
+ processTailwindCssWithTargets: () => processTailwindCssWithTargets,
816
+ runCssPipeline: () => runCssPipeline,
817
+ runCssPipelineSync: () => runCssPipelineSync
818
+ });
819
+ function loadTailwindEngine() {
820
+ if (_twEngine) return _twEngine;
821
+ if (_twEngineError) throw _twEngineError;
822
+ try {
823
+ const tw = require2("tailwindcss");
824
+ if (typeof tw.compile !== "function") {
825
+ throw new Error("tailwindcss v4 not found \u2014 compile() API missing. Check tailwindcss version >= 4.");
826
+ }
827
+ _twEngine = tw;
828
+ return _twEngine;
829
+ } catch (e) {
830
+ _twEngineError = e instanceof Error ? e : new Error(String(e));
831
+ throw _twEngineError;
832
+ }
833
+ }
834
+ async function generateRawCss(classes, cssEntryContent, root) {
835
+ if (classes.length === 0) return "";
836
+ const tw = loadTailwindEngine();
837
+ const input = cssEntryContent ?? "@import 'tailwindcss';";
838
+ const { readFileSync, existsSync: existsSync3 } = await import('fs');
839
+ const { dirname, resolve: resolve2 } = await import('path');
840
+ const projectRoot = root ?? process.cwd();
841
+ const req = module$1.createRequire(resolve2(projectRoot, "package.json"));
842
+ const loadStylesheet = async (id, base) => {
843
+ try {
844
+ const cssId = id === "tailwindcss" ? "tailwindcss/index.css" : id === "tailwindcss/preflight" ? "tailwindcss/preflight.css" : id === "tailwindcss/utilities" ? "tailwindcss/utilities.css" : id === "tailwindcss/theme" ? "tailwindcss/theme.css" : id;
845
+ const pkgPath = req.resolve(cssId);
846
+ return {
847
+ content: readFileSync(pkgPath, "utf-8"),
848
+ base: dirname(pkgPath)
849
+ };
850
+ } catch {
851
+ try {
852
+ const absPath = resolve2(base, id);
853
+ if (existsSync3(absPath)) {
854
+ return { content: readFileSync(absPath, "utf-8"), base: dirname(absPath) };
855
+ }
856
+ } catch {
857
+ }
858
+ return { content: "", base };
859
+ }
860
+ };
861
+ const compiler = await Promise.resolve(tw.compile(input, { loadStylesheet }));
862
+ return compiler.build(classes);
863
+ }
864
+ function postProcessWithLightning(rawCss) {
865
+ if (!rawCss) return "";
866
+ const native = getNativeBridge();
867
+ if (typeof native.processTailwindCssLightning !== "function") {
868
+ throw new Error("FATAL: Native binding 'processTailwindCssLightning' is required but not available.");
869
+ }
870
+ const result = native.processTailwindCssLightning(rawCss);
871
+ return result?.css ?? rawCss;
872
+ }
873
+ async function runCssPipeline(classes, cssEntryContent, root, minify = true) {
874
+ const unique = [...new Set(classes.filter(Boolean))];
875
+ if (unique.length === 0) {
876
+ return { css: "", classes: [], sizeBytes: 0, optimized: false };
877
+ }
878
+ const rawCss = await generateRawCss(unique, cssEntryContent, root);
879
+ const native = getNativeBridge();
880
+ const hasLightning = minify && typeof native.processTailwindCssLightning === "function";
881
+ const finalCss = hasLightning ? postProcessWithLightning(rawCss) : rawCss;
882
+ return {
883
+ css: finalCss,
884
+ classes: unique,
885
+ sizeBytes: finalCss.length,
886
+ optimized: hasLightning
887
+ };
888
+ }
889
+ function runCssPipelineSync(_classes) {
890
+ return { css: "", classes: [], sizeBytes: 0, optimized: false };
891
+ }
892
+ function processTailwindCssWithTargets(css, targets) {
893
+ const native = getNativeBridge();
894
+ if (!native?.processTailwindCssWithTargets) {
895
+ throw new Error("FATAL: Native binding 'processTailwindCssWithTargets' is required but not available.");
896
+ }
897
+ const result = native.processTailwindCssWithTargets(css, targets ?? null);
898
+ return (result?.css ?? css).trim();
899
+ }
900
+ var require2, _twEngine, _twEngineError;
901
+ var init_tailwindEngine = __esm({
902
+ "packages/domain/compiler/src/tailwindEngine.ts"() {
903
+ init_nativeBridge();
904
+ require2 = module$1.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('next.js', document.baseURI).href)));
905
+ _twEngine = null;
906
+ _twEngineError = null;
907
+ }
908
+ });
909
+
910
+ // packages/domain/compiler/src/index.ts
911
+ var src_exports = {};
912
+ __export(src_exports, {
913
+ BucketEngine: () => BucketEngine,
914
+ IncrementalEngine: () => IncrementalEngine,
915
+ adaptNativeResult: () => adaptNativeResult,
916
+ analyzeClassUsage: () => analyzeClassUsage,
917
+ analyzeClasses: () => analyzeClasses,
918
+ analyzeFile: () => analyzeFile,
919
+ analyzeRsc: () => analyzeRsc,
920
+ analyzeVariantUsage: () => analyzeVariantUsage,
921
+ astExtractClasses: () => astExtractClasses,
922
+ batchExtractClasses: () => batchExtractClasses,
923
+ bucketSort: () => bucketSort,
924
+ buildStyleTag: () => buildStyleTag,
925
+ checkAgainstSafelist: () => checkAgainstSafelist,
926
+ classifyAndSortClasses: () => classifyAndSortClasses,
927
+ classifyNode: () => classifyNode,
928
+ compileCssFromClasses: () => compileCssFromClasses,
929
+ compileCssNative: () => compileCssNative,
930
+ compileVariantTable: () => compileVariantTable,
931
+ compileVariants: () => compileVariants,
932
+ detectConflicts: () => detectConflicts,
933
+ diffClassLists: () => diffClassLists,
934
+ eliminateDeadCss: () => eliminateDeadCss,
935
+ extractAllClasses: () => extractAllClasses,
936
+ extractClassesFromSource: () => extractClassesFromSource,
937
+ extractComponentUsage: () => extractComponentUsage,
938
+ fileToRoute: () => fileToRoute,
939
+ findDeadVariants: () => findDeadVariants,
940
+ generateCssForClasses: () => generateCssForClasses,
941
+ generateSafelist: () => generateSafelist,
942
+ getAllRoutes: () => getAllRoutes,
943
+ getBucketEngine: () => getBucketEngine,
944
+ getContentPaths: () => getContentPaths,
945
+ getIncrementalEngine: () => getIncrementalEngine,
946
+ getNativeBridge: () => getNativeBridge,
947
+ getRouteClasses: () => getRouteClasses,
948
+ hasTwUsage: () => hasTwUsage,
949
+ hoistComponents: () => hoistComponents,
950
+ injectClientDirective: () => injectClientDirective,
951
+ injectServerOnlyComment: () => injectServerOnlyComment,
952
+ isAlreadyTransformed: () => isAlreadyTransformed,
953
+ loadSafelist: () => loadSafelist,
954
+ loadTailwindConfig: () => loadTailwindConfig,
955
+ mergeClassesStatic: () => mergeClassesStatic,
956
+ mergeCssDeclarations: () => mergeCssDeclarations,
957
+ normalizeAndDedupClasses: () => normalizeAndDedupClasses,
958
+ normalizeClasses: () => normalizeClasses,
959
+ optimizeCss: () => optimizeCss,
960
+ parseClasses: () => parseClasses,
961
+ registerFileClasses: () => registerFileClasses,
962
+ registerGlobalClasses: () => registerGlobalClasses,
963
+ resetBucketEngine: () => resetBucketEngine,
964
+ resetIncrementalEngine: () => resetIncrementalEngine,
965
+ resetNativeBridgeCache: () => resetNativeBridgeCache,
966
+ runElimination: () => runElimination,
967
+ runLoaderTransform: () => runLoaderTransform,
968
+ scanProjectUsage: () => scanProjectUsage,
969
+ shouldProcess: () => shouldProcess,
970
+ shouldSkipFile: () => shouldSkipFile,
971
+ transformSource: () => transformSource
972
+ });
973
+ var transformSource, hasTwUsage, isAlreadyTransformed, shouldProcess, compileCssFromClasses, buildStyleTag, compileCssNative, generateCssForClasses, extractAllClasses, extractClassesFromSource, astExtractClasses, parseClasses, normalizeClasses, mergeClassesStatic, normalizeAndDedupClasses, eliminateDeadCss, findDeadVariants, runElimination, optimizeCss, scanProjectUsage, extractComponentUsage, diffClassLists, batchExtractClasses, checkAgainstSafelist, hoistComponents, compileVariantTable, compileVariants, classifyAndSortClasses, mergeCssDeclarations, analyzeClassUsage, analyzeRsc, analyzeFile, analyzeVariantUsage, injectClientDirective, injectServerOnlyComment, analyzeClasses, generateSafelist, loadSafelist, loadTailwindConfig, getContentPaths, runLoaderTransform, shouldSkipFile, fileToRoute, getAllRoutes, getRouteClasses, registerFileClasses, registerGlobalClasses, _incrementalEngineInstance, getIncrementalEngine, resetIncrementalEngine, IncrementalEngine, getBucketEngine, resetBucketEngine, BucketEngine, classifyNode, detectConflicts, bucketSort;
974
+ var init_src2 = __esm({
975
+ "packages/domain/compiler/src/index.ts"() {
976
+ init_nativeBridge();
977
+ transformSource = (source, opts) => {
978
+ const native = getNativeBridge();
979
+ if (!native?.transformSource) {
980
+ throw new Error("FATAL: Native binding 'transformSource' is required but not available.");
981
+ }
982
+ const result = native.transformSource(source, opts);
983
+ if (!result) {
984
+ throw new Error("FATAL: transformSource returned null");
985
+ }
986
+ return result;
987
+ };
988
+ hasTwUsage = (source) => {
989
+ const native = getNativeBridge();
990
+ if (!native?.hasTwUsage) {
991
+ throw new Error("FATAL: Native binding 'hasTwUsage' is required but not available.");
992
+ }
993
+ return native.hasTwUsage(source);
994
+ };
995
+ isAlreadyTransformed = (source) => {
996
+ const native = getNativeBridge();
997
+ if (!native?.isAlreadyTransformed) {
998
+ throw new Error("FATAL: Native binding 'isAlreadyTransformed' is required but not available.");
999
+ }
1000
+ return native.isAlreadyTransformed(source);
1001
+ };
1002
+ shouldProcess = (source) => {
1003
+ return hasTwUsage(source) && !isAlreadyTransformed(source);
1004
+ };
1005
+ compileCssFromClasses = (classes, prefix) => {
1006
+ const native = getNativeBridge();
1007
+ if (!native?.transformSource) {
1008
+ throw new Error("FATAL: Native binding 'transformSource' is required but not available.");
1009
+ }
1010
+ const result = native.transformSource(classes.join(" "), { prefix: prefix ?? "" });
1011
+ if (!result) {
1012
+ throw new Error("FATAL: transformSource returned null");
1013
+ }
1014
+ return result;
1015
+ };
1016
+ buildStyleTag = (classes) => {
1017
+ const result = compileCssFromClasses(classes);
1018
+ return result?.code ? `<style data-tailwind-styled>${result.code}</style>` : "";
1019
+ };
1020
+ compileCssNative = (classes, prefix = null) => {
1021
+ return compileCssFromClasses(classes, prefix);
1022
+ };
1023
+ generateCssForClasses = async (classes, _tailwindConfig, root, cssEntryContent, minify = false) => {
1024
+ const { runCssPipeline: runCssPipeline2 } = await Promise.resolve().then(() => (init_tailwindEngine(), tailwindEngine_exports));
1025
+ const result = await runCssPipeline2(classes, cssEntryContent, root, minify);
1026
+ return result.css;
1027
+ };
1028
+ extractAllClasses = (source) => {
1029
+ const native = getNativeBridge();
1030
+ if (!native?.extractAllClasses) {
1031
+ throw new Error("FATAL: Native binding 'extractAllClasses' is required but not available.");
1032
+ }
1033
+ return native.extractAllClasses(source) || [];
1034
+ };
1035
+ extractClassesFromSource = (source) => {
1036
+ const native = getNativeBridge();
1037
+ if (!native?.extractClassesFromSource) {
1038
+ throw new Error("FATAL: Native binding 'extractClassesFromSource' is required but not available.");
1039
+ }
1040
+ const result = native.extractClassesFromSource(source);
1041
+ return Array.isArray(result) ? result.join(" ") : String(result || "");
1042
+ };
1043
+ astExtractClasses = (source, filename) => {
1044
+ const native = getNativeBridge();
1045
+ if (!native?.extractClassesFromSource) {
1046
+ throw new Error("FATAL: Native binding 'extractClassesFromSource' is required but not available.");
1047
+ }
1048
+ return native.extractClassesFromSource(source) || [];
1049
+ };
1050
+ parseClasses = (raw) => {
1051
+ const native = getNativeBridge();
1052
+ if (!native?.parseClasses) {
1053
+ throw new Error("FATAL: Native binding 'parseClasses' is required but not available.");
1054
+ }
1055
+ return native.parseClasses(raw) || [];
1056
+ };
1057
+ normalizeClasses = (raw) => {
1058
+ const result = normalizeAndDedupClasses(raw);
1059
+ return result?.normalized || "";
1060
+ };
1061
+ mergeClassesStatic = (classes) => {
1062
+ const result = normalizeAndDedupClasses(classes);
1063
+ return result?.normalized || "";
1064
+ };
1065
+ normalizeAndDedupClasses = (raw) => {
1066
+ const native = getNativeBridge();
1067
+ if (!native?.normalizeAndDedupClasses) {
1068
+ throw new Error("FATAL: Native binding 'normalizeAndDedupClasses' is required but not available.");
1069
+ }
1070
+ const result = native.normalizeAndDedupClasses(raw);
1071
+ return result || { normalized: "", duplicatesRemoved: 0, uniqueCount: 0 };
1072
+ };
1073
+ eliminateDeadCss = (css, deadClasses) => {
1074
+ const native = getNativeBridge();
1075
+ if (!native?.processTailwindCssLightning) {
1076
+ throw new Error("FATAL: Native binding 'processTailwindCssLightning' is required but not available.");
1077
+ }
1078
+ const deadSet = deadClasses;
1079
+ const pruned = css.split(/(?<=\})\s*/).filter((rule) => {
1080
+ const m = rule.match(/\.([a-zA-Z0-9_-]+)/);
1081
+ return !m || !deadSet.has(m[1]);
1082
+ }).join("\n");
1083
+ const compiled = native.processTailwindCssLightning(pruned);
1084
+ return (compiled?.css ?? pruned).trim();
1085
+ };
1086
+ findDeadVariants = (variantConfig, usage) => {
1087
+ const unused = [];
1088
+ const configs = Array.isArray(variantConfig) ? variantConfig : [{ name: "__root__", variants: variantConfig }];
1089
+ for (const component of configs) {
1090
+ const componentUsage = usage[component.name] ?? /* @__PURE__ */ new Set();
1091
+ const variants = component.variants;
1092
+ for (const [key, values] of Object.entries(variants)) {
1093
+ for (const [value] of Object.entries(values)) {
1094
+ if (!componentUsage.has(`${key}:${value}`)) {
1095
+ unused.push(`${component.name !== "__root__" ? `${component.name}/` : ""}${key}:${value}`);
1096
+ }
1097
+ }
1098
+ }
1099
+ }
1100
+ return {
1101
+ unusedCount: unused.length,
1102
+ unused
1103
+ };
1104
+ };
1105
+ runElimination = (css, scanResult) => {
1106
+ const native = getNativeBridge();
1107
+ if (!native?.detectDeadCode) {
1108
+ throw new Error("FATAL: Native binding 'detectDeadCode' is required but not available.");
1109
+ }
1110
+ const dead = native.detectDeadCode(
1111
+ JSON.stringify(scanResult),
1112
+ css
1113
+ );
1114
+ return eliminateDeadCss(css, new Set(dead.deadInCss ?? []));
1115
+ };
1116
+ optimizeCss = (css) => {
1117
+ const native = getNativeBridge();
1118
+ if (!native?.detectDeadCode) {
1119
+ throw new Error("FATAL: Native binding 'detectDeadCode' is required but not available.");
1120
+ }
1121
+ const deadResult = native.detectDeadCode(
1122
+ JSON.stringify({ uniqueClasses: [] }),
1123
+ css
1124
+ );
1125
+ if (!native?.processTailwindCssLightning) {
1126
+ throw new Error("FATAL: Native binding 'processTailwindCssLightning' is required but not available.");
1127
+ }
1128
+ const deadSet = new Set(deadResult.deadInCss ?? []);
1129
+ const pruned = css.split(/(?<=\})\s*/).filter((rule) => {
1130
+ const selectorMatch = rule.match(/\.([a-zA-Z0-9_-]+)/);
1131
+ if (!selectorMatch) return true;
1132
+ return !deadSet.has(selectorMatch[1]);
1133
+ }).join("\n");
1134
+ const compiled = native.processTailwindCssLightning(pruned);
1135
+ return (compiled?.css ?? pruned).trim();
1136
+ };
1137
+ scanProjectUsage = (dirs, cwd) => {
1138
+ const path7 = __require("path");
1139
+ const files = dirs.map((dir) => path7.resolve(cwd, dir));
1140
+ const results = batchExtractClasses(files) || [];
1141
+ const combined = {};
1142
+ for (const result of results) {
1143
+ if (result.ok && result.classes) {
1144
+ for (const cls of result.classes) {
1145
+ if (!combined[cls]) combined[cls] = {};
1146
+ combined[cls][result.file] = /* @__PURE__ */ new Set([cls]);
1147
+ }
1148
+ }
1149
+ }
1150
+ return combined;
1151
+ };
1152
+ extractComponentUsage = (source) => {
1153
+ const native = getNativeBridge();
1154
+ if (!native?.extractComponentUsage) {
1155
+ throw new Error("FATAL: Native binding 'extractComponentUsage' is required but not available.");
1156
+ }
1157
+ return native.extractComponentUsage(source) || [];
1158
+ };
1159
+ diffClassLists = (previous, current) => {
1160
+ const native = getNativeBridge();
1161
+ if (!native?.diffClassLists) {
1162
+ throw new Error("FATAL: Native binding 'diffClassLists' is required but not available.");
1163
+ }
1164
+ return native.diffClassLists(previous, current) || { added: [], removed: [], unchanged: [], hasChanges: false };
1165
+ };
1166
+ batchExtractClasses = (filePaths) => {
1167
+ const native = getNativeBridge();
1168
+ if (!native?.batchExtractClasses) {
1169
+ throw new Error("FATAL: Native binding 'batchExtractClasses' is required but not available.");
1170
+ }
1171
+ return native.batchExtractClasses(filePaths) || [];
1172
+ };
1173
+ checkAgainstSafelist = (classes, safelist) => {
1174
+ const native = getNativeBridge();
1175
+ if (!native?.checkAgainstSafelist) {
1176
+ throw new Error("FATAL: Native binding 'checkAgainstSafelist' is required but not available.");
1177
+ }
1178
+ return native.checkAgainstSafelist(classes, safelist) || { matched: [], unmatched: [], safelistSize: 0 };
1179
+ };
1180
+ hoistComponents = (source) => {
1181
+ const native = getNativeBridge();
1182
+ if (!native?.hoistComponents) {
1183
+ throw new Error("FATAL: Native binding 'hoistComponents' is required but not available.");
1184
+ }
1185
+ return native.hoistComponents(source) || { code: source, hoisted: [], warnings: [] };
1186
+ };
1187
+ compileVariantTable = (configJson) => {
1188
+ const native = getNativeBridge();
1189
+ if (!native?.compileVariantTable) {
1190
+ throw new Error("FATAL: Native binding 'compileVariantTable' is required but not available.");
1191
+ }
1192
+ return native.compileVariantTable(configJson) || { id: "", tableJson: "{}", keys: [], defaultKey: "", combinations: 0 };
1193
+ };
1194
+ compileVariants = (componentId, config) => {
1195
+ return compileVariantTable(JSON.stringify({ componentId, ...config }));
1196
+ };
1197
+ classifyAndSortClasses = (classes) => {
1198
+ const native = getNativeBridge();
1199
+ if (!native?.classifyAndSortClasses) {
1200
+ throw new Error("FATAL: Native binding 'classifyAndSortClasses' is required but not available.");
1201
+ }
1202
+ return native.classifyAndSortClasses(classes) || [];
1203
+ };
1204
+ mergeCssDeclarations = (cssChunks) => {
1205
+ const native = getNativeBridge();
1206
+ if (!native?.mergeCssDeclarations) {
1207
+ throw new Error("FATAL: Native binding 'mergeCssDeclarations' is required but not available.");
1208
+ }
1209
+ return native.mergeCssDeclarations(cssChunks) || { declarationsJson: "{}", declarationString: "", count: 0 };
1210
+ };
1211
+ analyzeClassUsage = (classes, scanResultJson, css) => {
1212
+ const native = getNativeBridge();
1213
+ if (!native?.analyzeClassUsage) {
1214
+ throw new Error("FATAL: Native binding 'analyzeClassUsage' is required but not available.");
1215
+ }
1216
+ return native.analyzeClassUsage(classes, scanResultJson, css) || [];
1217
+ };
1218
+ analyzeRsc = (source, filename) => {
1219
+ const native = getNativeBridge();
1220
+ if (!native?.analyzeRsc) {
1221
+ throw new Error("FATAL: Native binding 'analyzeRsc' is required but not available.");
1222
+ }
1223
+ return native.analyzeRsc(source, filename) || { isServer: true, needsClientDirective: false, clientReasons: [] };
1224
+ };
1225
+ analyzeFile = (source, filename) => {
1226
+ const rsc = analyzeRsc(source, filename);
1227
+ return {
1228
+ isServer: rsc?.isServer ?? true,
1229
+ needsClientDirective: rsc?.needsClientDirective ?? false,
1230
+ clientReasons: rsc?.clientReasons ?? [],
1231
+ interactiveClasses: [],
1232
+ canStaticResolveVariants: true
1233
+ };
1234
+ };
1235
+ analyzeVariantUsage = (source, componentName, variantKeys) => {
1236
+ analyzeRsc(source, componentName);
1237
+ return {
1238
+ resolved: {},
1239
+ dynamic: []
1240
+ };
1241
+ };
1242
+ injectClientDirective = (source) => {
1243
+ if (!source.includes('"use client"') && !source.includes("'use client'")) {
1244
+ return '"use client";\n' + source;
1245
+ }
1246
+ return source;
1247
+ };
1248
+ injectServerOnlyComment = (source) => {
1249
+ return `/* @server-only */
1250
+ ${source}`;
1251
+ };
1252
+ analyzeClasses = (filesJson, cwd, flags) => {
1253
+ const native = getNativeBridge();
1254
+ if (!native?.analyzeClasses) {
1255
+ throw new Error("FATAL: Native binding 'analyzeClasses' is required but not available.");
1256
+ }
1257
+ return native.analyzeClasses(filesJson, cwd, flags);
1258
+ };
1259
+ generateSafelist = (scanDirs, outputPath, cwd) => {
1260
+ const classes = scanProjectUsage(scanDirs, cwd || process.cwd());
1261
+ const allClasses = Object.keys(classes).sort();
1262
+ if (outputPath) {
1263
+ const fs6 = __require("fs");
1264
+ fs6.writeFileSync(outputPath, JSON.stringify(allClasses, null, 2));
1265
+ }
1266
+ return allClasses;
1267
+ };
1268
+ loadSafelist = (safelistPath) => {
1269
+ const fs6 = __require("fs");
1270
+ try {
1271
+ const content = fs6.readFileSync(safelistPath, "utf-8");
1272
+ return JSON.parse(content);
1273
+ } catch {
1274
+ return [];
1275
+ }
1276
+ };
1277
+ loadTailwindConfig = (cwd = process.cwd()) => {
1278
+ const fs6 = __require("fs");
1279
+ const path7 = __require("path");
1280
+ const configFiles = [
1281
+ "tailwind.config.ts",
1282
+ "tailwind.config.js",
1283
+ "tailwind.config.mjs",
1284
+ "tailwind.config.cjs"
1285
+ ];
1286
+ for (const file of configFiles) {
1287
+ const fullPath = path7.join(cwd, file);
1288
+ if (fs6.existsSync(fullPath)) {
1289
+ const mod = __require(fullPath);
1290
+ return mod.default || mod;
1291
+ }
1292
+ }
1293
+ return {};
1294
+ };
1295
+ getContentPaths = (cwd = process.cwd()) => {
1296
+ const path7 = __require("path");
1297
+ return {
1298
+ content: [
1299
+ path7.join(cwd, "src/**/*.{js,ts,jsx,tsx}"),
1300
+ path7.join(cwd, "app/**/*.{js,ts,jsx,tsx}"),
1301
+ path7.join(cwd, "pages/**/*.{js,ts,jsx,tsx}")
1302
+ ]
1303
+ };
1304
+ };
1305
+ runLoaderTransform = (ctx) => {
1306
+ const { filepath, source, options } = ctx;
1307
+ const result = transformSource(source, { filename: filepath, ...options });
1308
+ return {
1309
+ code: result?.code || "",
1310
+ changed: result?.changed || false,
1311
+ classes: result?.classes || []
1312
+ };
1313
+ };
1314
+ shouldSkipFile = (filepath) => {
1315
+ const SKIP_PATHS = ["node_modules", ".next", ".rspack-dist", ".turbo", "dist/", "out/"];
1316
+ const skipExtensions = [".css", ".json", ".md", ".txt", ".yaml", ".yml"];
1317
+ for (const p of SKIP_PATHS) {
1318
+ if (filepath.includes(p)) return true;
1319
+ }
1320
+ for (const ext of skipExtensions) {
1321
+ if (filepath.endsWith(ext)) return true;
1322
+ }
1323
+ return false;
1324
+ };
1325
+ fileToRoute = (filepath) => {
1326
+ const normalized = filepath.replace(/\\/g, "/");
1327
+ if (normalized.includes("/layout.") || normalized.includes("/loading.") || normalized.includes("/error.")) {
1328
+ return "__global";
1329
+ }
1330
+ const pageMatch = normalized.match(/\/app\/(.+?)\/page\.[tj]sx?$/);
1331
+ if (pageMatch) return `/${pageMatch[1]}`;
1332
+ const rootPage = normalized.match(/\/app\/page\.[tj]sx?$/);
1333
+ if (rootPage) return "/";
1334
+ return null;
1335
+ };
1336
+ getAllRoutes = () => {
1337
+ const native = getNativeBridge();
1338
+ if (!native?.analyzeClasses) {
1339
+ throw new Error("FATAL: Native binding 'analyzeClasses' is required but not available.");
1340
+ }
1341
+ return ["/", "__global"];
1342
+ };
1343
+ getRouteClasses = (_route) => {
1344
+ return /* @__PURE__ */ new Set();
1345
+ };
1346
+ registerFileClasses = (_filepath, _classes) => {
1347
+ };
1348
+ registerGlobalClasses = (_classes) => {
1349
+ };
1350
+ _incrementalEngineInstance = null;
1351
+ getIncrementalEngine = () => {
1352
+ if (!_incrementalEngineInstance) {
1353
+ _incrementalEngineInstance = new IncrementalEngine();
1354
+ }
1355
+ return _incrementalEngineInstance;
1356
+ };
1357
+ resetIncrementalEngine = () => {
1358
+ _incrementalEngineInstance = null;
1359
+ };
1360
+ IncrementalEngine = class {
1361
+ compile(source) {
1362
+ return transformSource(source);
1363
+ }
1364
+ };
1365
+ getBucketEngine = () => {
1366
+ const native = getNativeBridge();
1367
+ if (!native?.classifyAndSortClasses) {
1368
+ throw new Error("FATAL: Native binding 'classifyAndSortClasses' is required but not available.");
1369
+ }
1370
+ return {
1371
+ add: (className) => className,
1372
+ get: (_bucket) => []
1373
+ };
1374
+ };
1375
+ resetBucketEngine = () => {
1376
+ };
1377
+ BucketEngine = class {
1378
+ add(className) {
1379
+ return className;
1380
+ }
1381
+ };
1382
+ classifyNode = (_node) => {
1383
+ const native = getNativeBridge();
1384
+ if (!native?.classifyAndSortClasses) {
1385
+ throw new Error("FATAL: Native binding 'classifyAndSortClasses' is required but not available.");
1386
+ }
1387
+ return "unknown";
1388
+ };
1389
+ detectConflicts = (classes) => {
1390
+ const native = getNativeBridge();
1391
+ if (!native?.analyzeClassUsage) {
1392
+ throw new Error("FATAL: Native binding 'analyzeClassUsage' is required but not available.");
1393
+ }
1394
+ return [];
1395
+ };
1396
+ bucketSort = (classes) => {
1397
+ return classifyAndSortClasses(classes).map((c) => c.raw ?? c);
1398
+ };
1399
+ }
1400
+ });
1401
+ var formatIssues = (error) => error.issues.map((issue) => {
1402
+ const p = issue.path.length > 0 ? issue.path.join(".") : "<root>";
1403
+ return `${p}: ${issue.message}`;
1404
+ }).join("; ");
1405
+ var parseWithSchema = (schema, data, label) => {
1406
+ const parsed = schema.safeParse(data);
1407
+ if (parsed.success) return parsed.data;
1408
+ throw new TypeError(`${label}: ${formatIssues(parsed.error)}`);
1409
+ };
1410
+ var NextAdapterOptionsSchema = zod.z.object({
1411
+ mode: zod.z.literal("zero-runtime").optional(),
1412
+ autoClientBoundary: zod.z.boolean().optional(),
1413
+ addDataAttr: zod.z.boolean().optional(),
1414
+ hoist: zod.z.boolean().optional(),
1415
+ routeCss: zod.z.boolean().optional(),
1416
+ incremental: zod.z.boolean().optional(),
1417
+ verbose: zod.z.boolean().optional(),
1418
+ include: zod.z.instanceof(RegExp).optional(),
1419
+ exclude: zod.z.instanceof(RegExp).optional()
1420
+ });
1421
+ var parseNextAdapterOptions = (options) => parseWithSchema(NextAdapterOptionsSchema, options ?? {}, "next adapter options are invalid");
1422
+
1423
+ // packages/presentation/next/src/withTailwindStyled.ts
1424
+ init_src();
1425
+
1426
+ // packages/domain/scanner/src/index.ts
1427
+ init_src();
1428
+
1429
+ // packages/domain/scanner/src/cache-native.ts
1430
+ init_native_bridge();
1431
+ function defaultCachePath(rootDir, cacheDir) {
1432
+ const dir = cacheDir ? path5__namespace.default.resolve(rootDir, cacheDir) : path5__namespace.default.join(process.cwd(), ".cache", "tailwind-styled");
1433
+ return path5__namespace.default.join(dir, "scanner-cache.json");
1434
+ }
1435
+ function readCache(rootDir, cacheDir) {
1436
+ const cachePath = defaultCachePath(rootDir, cacheDir);
1437
+ fs5__namespace.default.mkdirSync(path5__namespace.default.dirname(cachePath), { recursive: true });
1438
+ const result = cacheReadNative(cachePath);
1439
+ if (!result) return [];
1440
+ return result.entries.map((e) => ({
1441
+ file: e.file,
1442
+ classes: e.classes,
1443
+ hash: e.hash,
1444
+ mtimeMs: e.mtimeMs,
1445
+ size: e.size,
1446
+ hitCount: e.hitCount,
1447
+ lastSeenMs: e.lastSeenMs
1448
+ }));
1449
+ }
1450
+ function writeCache(rootDir, entries, cacheDir) {
1451
+ const cachePath = defaultCachePath(rootDir, cacheDir);
1452
+ fs5__namespace.default.mkdirSync(path5__namespace.default.dirname(cachePath), { recursive: true });
1453
+ const success = cacheWriteNative(cachePath, entries);
1454
+ if (!success) {
1455
+ throw new Error(
1456
+ "Native cacheWrite failed. Run 'npm run build:rust' to rebuild native bindings."
1457
+ );
1458
+ }
1459
+ }
1460
+ function filePriority(mtimeMs, size, cached, nowMs = Date.now()) {
1461
+ return cachePriorityNative(
1462
+ mtimeMs,
1463
+ size,
1464
+ cached?.mtimeMs ?? 0,
1465
+ cached?.size ?? 0,
1466
+ cached?.hitCount ?? 0,
1467
+ cached?.lastSeenMs ?? 0,
1468
+ nowMs
1469
+ );
1470
+ }
1471
+
1472
+ // packages/domain/scanner/src/index.ts
1473
+ init_native_bridge();
129
1474
 
130
- // packages/domain/shared/src/index.ts
131
- module$1.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('next.js', document.baseURI).href)));
1475
+ // packages/domain/scanner/src/schemas.ts
1476
+ init_src();
1477
+ var formatIssuePath2 = (path7) => path7.length > 0 ? path7.map(
1478
+ (segment) => typeof segment === "symbol" ? segment.description ?? segment.toString() : String(segment)
1479
+ ).join(".") : "<root>";
1480
+ var formatIssues2 = (error) => error.issues.map((issue) => {
1481
+ const path7 = formatIssuePath2(issue.path);
1482
+ return `${path7}: ${issue.message}`;
1483
+ }).join("; ");
1484
+ var parseWithSchema2 = (schema, data, label) => {
1485
+ const parsed = schema.safeParse(data);
1486
+ if (parsed.success) return parsed.data;
1487
+ const details = formatIssues2(parsed.error);
1488
+ throw new TwError(
1489
+ "validation",
1490
+ "SCHEMA_VALIDATION_FAILED",
1491
+ details ? `${label}: ${details}` : label,
1492
+ parsed.error
1493
+ );
1494
+ };
1495
+ var NonNegativeIntegerSchema = zod.z.number().int().min(0);
1496
+ var ScanWorkspaceOptionsSchema = zod.z.object({
1497
+ includeExtensions: zod.z.array(zod.z.string()).optional(),
1498
+ ignoreDirectories: zod.z.array(zod.z.string()).optional(),
1499
+ useCache: zod.z.boolean().optional(),
1500
+ cacheDir: zod.z.string().min(1).optional(),
1501
+ smartInvalidation: zod.z.boolean().optional()
1502
+ });
1503
+ var ScanFileResultSchema = zod.z.object({
1504
+ file: zod.z.string(),
1505
+ classes: zod.z.array(zod.z.string()),
1506
+ hash: zod.z.string().optional()
1507
+ });
1508
+ var ScanWorkspaceResultSchema = zod.z.object({
1509
+ files: zod.z.array(ScanFileResultSchema),
1510
+ totalFiles: NonNegativeIntegerSchema,
1511
+ uniqueClasses: zod.z.array(zod.z.string())
1512
+ }).refine((value) => value.totalFiles === value.files.length, {
1513
+ message: "scan result totalFiles must match files.length",
1514
+ path: ["totalFiles"]
1515
+ });
1516
+ zod.z.object({
1517
+ rootDir: zod.z.string().min(1),
1518
+ options: ScanWorkspaceOptionsSchema.optional()
1519
+ });
1520
+ var ScannerWorkerSuccessMessageSchema = zod.z.object({
1521
+ ok: zod.z.literal(true),
1522
+ result: ScanWorkspaceResultSchema
1523
+ });
1524
+ var ScannerWorkerErrorMessageSchema = zod.z.object({
1525
+ ok: zod.z.literal(false),
1526
+ error: zod.z.string().optional()
1527
+ });
1528
+ zod.z.union([
1529
+ ScannerWorkerSuccessMessageSchema,
1530
+ ScannerWorkerErrorMessageSchema
1531
+ ]);
1532
+ var parseScanWorkspaceOptions = (options) => parseWithSchema2(ScanWorkspaceOptionsSchema, options ?? {}, "scanner options are invalid");
1533
+ var parseScanWorkspaceResult = (result) => parseWithSchema2(ScanWorkspaceResultSchema, result, "scanner workspace result is invalid");
1534
+
1535
+ // packages/domain/scanner/src/index.ts
1536
+ var log2 = createLogger("scanner");
1537
+ function getRuntimeDir() {
1538
+ if (typeof __dirname !== "undefined" && __dirname.length > 0) {
1539
+ return __dirname;
1540
+ }
1541
+ if (typeof ({ url: (typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('next.js', document.baseURI).href)) }) !== "undefined" && (typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('next.js', document.baseURI).href))) {
1542
+ return path5__namespace.default.dirname(url.fileURLToPath((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('next.js', document.baseURI).href))));
1543
+ }
1544
+ return process.cwd();
1545
+ }
1546
+ var createNativeParserLoader = () => {
1547
+ const _state = {
1548
+ binding: void 0,
1549
+ initError: null
1550
+ };
1551
+ const debugNative = (message) => {
1552
+ log2.debug(`[native] ${message}`);
1553
+ };
1554
+ const loadNativeParserBinding = () => {
1555
+ if (_state.binding !== void 0) return _state.binding;
1556
+ const runtimeDir = getRuntimeDir();
1557
+ const req = module$1.createRequire(path5__namespace.default.join(runtimeDir, "noop.cjs"));
1558
+ const _platform = process.platform;
1559
+ const _arch = process.arch;
1560
+ const _platformArch = `${_platform}-${_arch}`;
1561
+ const _platformArchGnu = _platformArch === "linux-x64" ? "linux-x64-gnu" : _platformArch === "linux-arm64" ? "linux-arm64-gnu" : _platformArch;
1562
+ const candidates = [
1563
+ // ── binaryName baru: tailwind-styled-native (napi-rs naming) ──
1564
+ // cwd = repo root saat run dari root, atau package dir saat workspaces
1565
+ path5__namespace.default.resolve(process.cwd(), "native", "tailwind-styled-native.node"),
1566
+ path5__namespace.default.resolve(process.cwd(), "native", `tailwind-styled-native.${_platformArch}.node`),
1567
+ path5__namespace.default.resolve(process.cwd(), "native", `tailwind-styled-native.${_platformArchGnu}.node`),
1568
+ // runtimeDir = dist/ → naik 1 level ke package root (npm install case)
1569
+ // e.g. node_modules/tailwind-styled-v4/dist/ → node_modules/tailwind-styled-v4/native/
1570
+ path5__namespace.default.resolve(runtimeDir, "..", "native", "tailwind-styled-native.node"),
1571
+ path5__namespace.default.resolve(runtimeDir, "..", "native", `tailwind-styled-native.${_platformArch}.node`),
1572
+ path5__namespace.default.resolve(runtimeDir, "..", "native", `tailwind-styled-native.${_platformArchGnu}.node`),
1573
+ // runtimeDir = dist/ → naik 4 level ke repo root (monorepo dev case)
1574
+ path5__namespace.default.resolve(runtimeDir, "..", "..", "..", "..", "native", "tailwind-styled-native.node"),
1575
+ path5__namespace.default.resolve(runtimeDir, "..", "..", "..", "..", "native", `tailwind-styled-native.${_platformArchGnu}.node`),
1576
+ // 3 level fallback (jika package di-nest lebih dangkal)
1577
+ path5__namespace.default.resolve(runtimeDir, "..", "..", "..", "native", "tailwind-styled-native.node"),
1578
+ path5__namespace.default.resolve(runtimeDir, "..", "..", "..", "native", `tailwind-styled-native.${_platformArchGnu}.node`),
1579
+ // ── binaryName lama: tailwind_styled_parser (backward compat) ──
1580
+ path5__namespace.default.resolve(process.cwd(), "native/tailwind_styled_parser.node"),
1581
+ path5__namespace.default.resolve(process.cwd(), "native/build/Release/tailwind_styled_parser.node"),
1582
+ path5__namespace.default.resolve(runtimeDir, "..", "native", "tailwind_styled_parser.node"),
1583
+ path5__namespace.default.resolve(runtimeDir, "..", "..", "..", "..", "native", "tailwind_styled_parser.node"),
1584
+ path5__namespace.default.resolve(runtimeDir, "..", "..", "..", "native", "tailwind_styled_parser.node"),
1585
+ path5__namespace.default.resolve(
1586
+ runtimeDir,
1587
+ "..",
1588
+ "..",
1589
+ "..",
1590
+ "native",
1591
+ "build",
1592
+ "Release",
1593
+ "tailwind_styled_parser.node"
1594
+ )
1595
+ ];
1596
+ for (const fullPath of candidates) {
1597
+ if (!fs5__namespace.default.existsSync(fullPath)) continue;
1598
+ try {
1599
+ const required = req(fullPath);
1600
+ if (required && (typeof required.extractClassesFromSource === "function" || typeof required.parseClasses === "function" || typeof required.parse_classes === "function")) {
1601
+ _state.binding = required;
1602
+ debugNative(`using native parser from ${fullPath}`);
1603
+ return _state.binding;
1604
+ }
1605
+ } catch (error) {
1606
+ _state.initError = error instanceof Error ? error.message : String(error);
1607
+ }
1608
+ }
1609
+ _state.binding = null;
1610
+ if (!_state.initError) {
1611
+ _state.initError = "native .node binding not found";
1612
+ }
1613
+ debugNative(`native binding not available: ${_state.initError}`);
1614
+ return _state.binding;
1615
+ };
1616
+ return {
1617
+ get: loadNativeParserBinding,
1618
+ reset: () => {
1619
+ _state.binding = void 0;
1620
+ _state.initError = null;
1621
+ }
1622
+ };
1623
+ };
1624
+ var nativeParserLoader = createNativeParserLoader();
1625
+ var DEFAULT_EXTENSIONS = [".js", ".jsx", ".ts", ".tsx", ".mjs", ".cjs"];
1626
+ var DEFAULT_IGNORES = ["node_modules", ".git", ".next", "dist", "out", ".turbo", ".cache"];
1627
+ function buildExtensionSet(includeExtensions) {
1628
+ return new Set(includeExtensions);
1629
+ }
1630
+ function collectCandidates(rootDir, ignoreDirectories, extensionSet) {
1631
+ const candidates = [];
1632
+ const directories = [rootDir];
1633
+ while (directories.length > 0) {
1634
+ const currentDir = directories.pop();
1635
+ if (!currentDir) continue;
1636
+ const entries = (() => {
1637
+ try {
1638
+ return fs5__namespace.default.readdirSync(currentDir, { withFileTypes: true });
1639
+ } catch {
1640
+ return [];
1641
+ }
1642
+ })();
1643
+ for (const entry of entries) {
1644
+ const fullPath = path5__namespace.default.join(currentDir, entry.name);
1645
+ if (entry.isDirectory()) {
1646
+ if (!ignoreDirectories.has(entry.name)) directories.push(fullPath);
1647
+ continue;
1648
+ }
1649
+ if (!entry.isFile()) continue;
1650
+ if (!extensionSet.has(path5__namespace.default.extname(entry.name))) continue;
1651
+ candidates.push(fullPath);
1652
+ }
1653
+ }
1654
+ return candidates;
1655
+ }
1656
+ function toCacheSize(size) {
1657
+ if (!Number.isFinite(size)) return 0;
1658
+ const normalized = Math.max(0, Math.trunc(size));
1659
+ return Math.min(normalized, 4294967295);
1660
+ }
1661
+ function scanSource(source) {
1662
+ const nativeBinding = nativeParserLoader.get();
1663
+ if (nativeBinding?.extractClassesFromSource) {
1664
+ const result = nativeBinding.extractClassesFromSource(source);
1665
+ if (Array.isArray(result)) {
1666
+ return Array.from(new Set(result.filter(Boolean)));
1667
+ }
1668
+ if (result !== null && result !== void 0 && Array.isArray(result.classes)) {
1669
+ return Array.from(new Set(result.classes.filter(Boolean)));
1670
+ }
1671
+ }
1672
+ throw new Error(
1673
+ "FATAL: Native parser binding is required but not available.\nThis package requires native Rust bindings.\n\nResolution steps:\n1. Build the native Rust module: npm run build:rust"
1674
+ );
1675
+ }
1676
+ function scanFile(filePath) {
1677
+ const { scanFileNative: scanFileNative2 } = (init_native_bridge(), __toCommonJS(native_bridge_exports));
1678
+ const result = scanFileNative2(filePath);
1679
+ if (!result.ok) {
1680
+ throw new Error(`scanFile failed for ${filePath}: ${result.error ?? "unknown error"}`);
1681
+ }
1682
+ return {
1683
+ file: result.file,
1684
+ classes: result.classes,
1685
+ ...result.hash ? { hash: result.hash } : {}
1686
+ };
1687
+ }
1688
+ function scanWorkspace(rootDir, options = {}) {
1689
+ const normalizedOptions = parseScanWorkspaceOptions(options);
1690
+ const includeExtensions = normalizedOptions.includeExtensions ?? DEFAULT_EXTENSIONS;
1691
+ const extensionSet = buildExtensionSet(includeExtensions);
1692
+ const ignoreDirectories = new Set(normalizedOptions.ignoreDirectories ?? DEFAULT_IGNORES);
1693
+ const useCache = normalizedOptions.useCache ?? true;
1694
+ normalizedOptions.smartInvalidation ?? true;
1695
+ const files = [];
1696
+ const unique = /* @__PURE__ */ new Set();
1697
+ const candidates = collectCandidates(rootDir, ignoreDirectories, extensionSet);
1698
+ const processResult = (result) => {
1699
+ files.push(result);
1700
+ for (const cls of result.classes) unique.add(cls);
1701
+ };
1702
+ const { scanWorkspaceNative: scanWorkspaceNative2 } = (init_native_bridge(), __toCommonJS(native_bridge_exports));
1703
+ if (!normalizedOptions.cacheDir && !useCache) {
1704
+ const nativeResult = scanWorkspaceNative2(rootDir, includeExtensions);
1705
+ if (nativeResult) {
1706
+ return parseScanWorkspaceResult({
1707
+ files: nativeResult.files.map((f) => ({
1708
+ file: f.file,
1709
+ classes: f.classes,
1710
+ ...f.hash ? { hash: f.hash } : {}
1711
+ })),
1712
+ totalFiles: nativeResult.totalFiles,
1713
+ uniqueClasses: nativeResult.uniqueClasses
1714
+ });
1715
+ }
1716
+ }
1717
+ if (useCache && isRustCacheAvailable()) {
1718
+ const cacheEntries = (() => {
1719
+ try {
1720
+ return readCache(rootDir, normalizedOptions.cacheDir);
1721
+ } catch (error) {
1722
+ log2.debug(
1723
+ `cache read failed, continuing without persisted cache: ${error instanceof Error ? error.message : String(error)}`
1724
+ );
1725
+ return [];
1726
+ }
1727
+ })();
1728
+ const cacheMap = new Map(cacheEntries.map((entry) => [entry.file, entry]));
1729
+ const nowMs = Date.now();
1730
+ const ranked = [];
1731
+ for (const filePath of candidates) {
1732
+ const stat = (() => {
1733
+ try {
1734
+ return fs5__namespace.default.statSync(filePath);
1735
+ } catch {
1736
+ return null;
1737
+ }
1738
+ })();
1739
+ if (!stat) continue;
1740
+ const size = toCacheSize(stat.size);
1741
+ const cached = cacheMap.get(filePath);
1742
+ const priority = filePriority(
1743
+ stat.mtimeMs,
1744
+ size,
1745
+ cached ? {
1746
+ mtimeMs: cached.mtimeMs,
1747
+ size: cached.size,
1748
+ hitCount: cached.hitCount,
1749
+ lastSeenMs: 0
1750
+ } : void 0,
1751
+ nowMs
1752
+ );
1753
+ ranked.push({ filePath, stat, size, cached, priority });
1754
+ }
1755
+ ranked.sort((a, b) => b.priority - a.priority);
1756
+ const updatedEntries = [];
1757
+ for (const { filePath, stat, size, cached } of ranked) {
1758
+ const content = (() => {
1759
+ try {
1760
+ return fs5__namespace.default.readFileSync(filePath, "utf8");
1761
+ } catch {
1762
+ return null;
1763
+ }
1764
+ })();
1765
+ if (!content) continue;
1766
+ const hash = hashContentNative(content);
1767
+ if (cached && cached.hash === hash && cached.mtimeMs === stat.mtimeMs && cached.size === size) {
1768
+ log2.debug(`cache HIT ${filePath}`);
1769
+ processResult({ file: filePath, classes: cached.classes });
1770
+ updatedEntries.push({
1771
+ file: filePath,
1772
+ classes: cached.classes,
1773
+ hash: cached.hash,
1774
+ mtimeMs: stat.mtimeMs,
1775
+ size,
1776
+ hitCount: (cached.hitCount ?? 0) + 1
1777
+ });
1778
+ continue;
1779
+ }
1780
+ log2.debug(`cache MISS ${filePath}`);
1781
+ const classes = scanSource(content);
1782
+ processResult({ file: filePath, classes });
1783
+ updatedEntries.push({
1784
+ file: filePath,
1785
+ classes,
1786
+ hash,
1787
+ mtimeMs: stat.mtimeMs,
1788
+ size,
1789
+ hitCount: 1
1790
+ });
1791
+ }
1792
+ try {
1793
+ writeCache(rootDir, updatedEntries, normalizedOptions.cacheDir);
1794
+ } catch (error) {
1795
+ log2.debug(`cache write failed: ${error instanceof Error ? error.message : String(error)}`);
1796
+ }
1797
+ return parseScanWorkspaceResult({
1798
+ files,
1799
+ totalFiles: files.length,
1800
+ uniqueClasses: Array.from(unique).sort()
1801
+ });
1802
+ }
1803
+ const batchNative = nativeParserLoader.get()?.batchExtractClassesNative;
1804
+ if (batchNative) {
1805
+ const batchResults = batchNative(candidates);
1806
+ for (const r of batchResults ?? []) {
1807
+ if (r.ok) processResult({ file: r.file, classes: r.classes });
1808
+ }
1809
+ } else {
1810
+ for (const filePath of candidates) {
1811
+ processResult(scanFile(filePath));
1812
+ }
1813
+ }
1814
+ return parseScanWorkspaceResult({
1815
+ files,
1816
+ totalFiles: files.length,
1817
+ uniqueClasses: Array.from(unique).sort()
1818
+ });
1819
+ }
132
1820
 
133
1821
  // packages/presentation/next/src/withTailwindStyled.ts
134
1822
  function getDirnameFromUrl2(importMetaUrl) {
@@ -144,20 +1832,20 @@ function getDirnameFromUrl2(importMetaUrl) {
144
1832
  const lastSlash = Math.max(importMetaUrl.lastIndexOf("/"), importMetaUrl.lastIndexOf("\\"));
145
1833
  return lastSlash > 0 ? importMetaUrl.slice(0, lastSlash) : "";
146
1834
  }
147
- var require2 = module$1.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('next.js', document.baseURI).href)));
148
- var resolveRuntimeDir = () => getDirnameFromUrl2((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('next.js', document.baseURI).href)));
1835
+ var require3 = module$1.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('next.js', document.baseURI).href)));
1836
+ var resolveRuntimeDir2 = () => getDirnameFromUrl2((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('next.js', document.baseURI).href)));
149
1837
  var resolveLoaderPath2 = (basename) => {
150
1838
  try {
151
1839
  return resolveLoaderPath(basename, (typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('next.js', document.baseURI).href)));
152
1840
  } catch {
153
- const runtimeDir = resolveRuntimeDir();
1841
+ const runtimeDir = resolveRuntimeDir2();
154
1842
  const candidates = [
155
- path2__default.default.resolve(runtimeDir, `${basename}.mjs`),
156
- path2__default.default.resolve(runtimeDir, `${basename}.js`),
157
- path2__default.default.resolve(runtimeDir, `${basename}.cjs`)
1843
+ path5__namespace.default.resolve(runtimeDir, `${basename}.mjs`),
1844
+ path5__namespace.default.resolve(runtimeDir, `${basename}.js`),
1845
+ path5__namespace.default.resolve(runtimeDir, `${basename}.cjs`)
158
1846
  ];
159
1847
  for (const candidate of candidates) {
160
- if (fs2__default.default.existsSync(candidate)) {
1848
+ if (fs5__namespace.default.existsSync(candidate)) {
161
1849
  return candidate;
162
1850
  }
163
1851
  }
@@ -168,8 +1856,8 @@ var resolveLoaderPath2 = (basename) => {
168
1856
  };
169
1857
  function checkNextVersion() {
170
1858
  try {
171
- const pkgPath = require2.resolve("next/package.json");
172
- const { version } = require2(pkgPath);
1859
+ const pkgPath = require3.resolve("next/package.json");
1860
+ const { version } = require3(pkgPath);
173
1861
  const major = Number.parseInt(version.split(".")[0], 10);
174
1862
  if (major < 15) {
175
1863
  console.warn(
@@ -195,19 +1883,20 @@ var createLoaderOptions = (options) => {
195
1883
  preserveImports: true
196
1884
  };
197
1885
  if (options.verbose !== void 0) opts.verbose = options.verbose;
198
- opts.safelistPath = options.safelistPath ?? path2__default.default.join(process.cwd(), "__tw_safelist.css");
1886
+ opts.safelistPath = options.safelistPath ?? path5__namespace.default.join(process.cwd(), ".next", "tailwind-styled-safelist.css");
199
1887
  return Object.freeze(opts);
200
1888
  };
201
1889
  var buildTurbopackRules = (loaderPath, loaderOptions) => {
202
1890
  const extensions = ["js", "jsx", "ts", "tsx", "mjs", "cjs"];
203
1891
  return Object.fromEntries(
204
1892
  extensions.map((ext) => [
205
- `*.${ext}`,
1893
+ `**/*.${ext}`,
1894
+ // ← recursive glob: match semua subdirectory, bukan hanya root
206
1895
  { loaders: [{ loader: loaderPath, options: loaderOptions }] }
207
1896
  ])
208
1897
  );
209
1898
  };
210
- var normalizeLoaderPath = (loaderPath) => path2__default.default.resolve(loaderPath);
1899
+ var normalizeLoaderPath = (loaderPath) => path5__namespace.default.resolve(loaderPath);
211
1900
  var applyWebpackRule = (config, options, loaderPath) => {
212
1901
  const loaderOptions = createLoaderOptions(options);
213
1902
  const rules = config.module?.rules ?? [];
@@ -231,6 +1920,7 @@ var applyWebpackRule = (config, options, loaderPath) => {
231
1920
  rules: [...rules, tailwindStyledRule]
232
1921
  };
233
1922
  const externalPackages = [
1923
+ "tailwind-styled-v4",
234
1924
  "@tailwind-styled/shared",
235
1925
  "@tailwind-styled/compiler",
236
1926
  "@tailwind-styled/engine",
@@ -296,9 +1986,204 @@ function withTailwindStyled(options = {}) {
296
1986
  return function wrap(nextConfig = {}) {
297
1987
  const previousWebpack = nextConfig.webpack;
298
1988
  const loaderOptions = createLoaderOptions(normalizedOptions);
1989
+ try {
1990
+ const safelistPath = loaderOptions.safelistPath;
1991
+ if (safelistPath) {
1992
+ let extractUtilitiesLayer2 = function(fullCss) {
1993
+ const minified = fullCss.indexOf("@layer utilities{");
1994
+ const spaced = fullCss.indexOf("@layer utilities {");
1995
+ const startIdx = minified !== -1 ? minified : spaced !== -1 ? spaced : -1;
1996
+ if (startIdx === -1) return "";
1997
+ let depth = 0;
1998
+ let endIdx = startIdx;
1999
+ for (let i = startIdx; i < fullCss.length; i++) {
2000
+ if (fullCss[i] === "{") depth++;
2001
+ else if (fullCss[i] === "}") {
2002
+ depth--;
2003
+ if (depth === 0) {
2004
+ endIdx = i;
2005
+ break;
2006
+ }
2007
+ }
2008
+ }
2009
+ return fullCss.slice(startIdx, endIdx + 1);
2010
+ };
2011
+ var extractUtilitiesLayer = extractUtilitiesLayer2;
2012
+ const twClassesDir = path5__namespace.default.join(path5__namespace.default.dirname(safelistPath), "tw-classes");
2013
+ fs5__namespace.default.mkdirSync(twClassesDir, { recursive: true });
2014
+ fs5__namespace.default.writeFileSync(
2015
+ path5__namespace.default.join(twClassesDir, "_start.txt"),
2016
+ String(Date.now()),
2017
+ "utf-8"
2018
+ );
2019
+ if (!process.env.TW_NATIVE_PATH) {
2020
+ const runtimeDir = resolveRuntimeDir2();
2021
+ const nativePath = path5__namespace.default.resolve(runtimeDir, "..", "native", "tailwind-styled-native.node");
2022
+ if (fs5__namespace.default.existsSync(nativePath)) {
2023
+ process.env.TW_NATIVE_PATH = nativePath;
2024
+ }
2025
+ }
2026
+ const srcDir = path5__namespace.default.join(process.cwd(), "src");
2027
+ if (fs5__namespace.default.existsSync(srcDir)) {
2028
+ try {
2029
+ const result = scanWorkspace(srcDir);
2030
+ if (result.uniqueClasses.length > 0) {
2031
+ let atomicWriteFile2 = function(filePath, content) {
2032
+ const tmpPath = `${filePath}.tmp`;
2033
+ try {
2034
+ fs5__namespace.default.writeFileSync(tmpPath, content, "utf-8");
2035
+ fs5__namespace.default.renameSync(tmpPath, filePath);
2036
+ } catch {
2037
+ try {
2038
+ fs5__namespace.default.unlinkSync(tmpPath);
2039
+ } catch {
2040
+ }
2041
+ fs5__namespace.default.writeFileSync(filePath, content, "utf-8");
2042
+ }
2043
+ };
2044
+ var atomicWriteFile = atomicWriteFile2;
2045
+ const VALID_VARIANT_PREFIXES = /* @__PURE__ */ new Set([
2046
+ "hover",
2047
+ "focus",
2048
+ "active",
2049
+ "disabled",
2050
+ "visited",
2051
+ "checked",
2052
+ "first",
2053
+ "last",
2054
+ "odd",
2055
+ "even",
2056
+ "focus-within",
2057
+ "focus-visible",
2058
+ "placeholder",
2059
+ "before",
2060
+ "after",
2061
+ "dark",
2062
+ "sm",
2063
+ "md",
2064
+ "lg",
2065
+ "xl",
2066
+ "2xl",
2067
+ "motion-reduce",
2068
+ "motion-safe",
2069
+ "group",
2070
+ "peer",
2071
+ "aria",
2072
+ "data",
2073
+ "supports",
2074
+ "not",
2075
+ "has",
2076
+ "is",
2077
+ "where",
2078
+ "rtl",
2079
+ "ltr",
2080
+ "open",
2081
+ "print",
2082
+ "portrait",
2083
+ "landscape"
2084
+ ]);
2085
+ const filteredClasses = result.uniqueClasses.filter((cls) => {
2086
+ if (cls.includes(":")) {
2087
+ const prefix = cls.split(":")[0];
2088
+ if (!VALID_VARIANT_PREFIXES.has(prefix ?? "")) return false;
2089
+ }
2090
+ if (/\[[\d]+\.[\d]{2,}(?:px|rem|em|vh|vw|%)\]/.test(cls)) return false;
2091
+ if (/\[[\d]{5,}(?:px|rem|em)?\]/.test(cls)) return false;
2092
+ return true;
2093
+ });
2094
+ let cssEntryContent = null;
2095
+ const CSS_CANDIDATES = [
2096
+ "src/app/globals.css",
2097
+ "src/globals.css",
2098
+ "src/styles/globals.css",
2099
+ "src/tailwind.css",
2100
+ "src/index.css",
2101
+ "styles/globals.css"
2102
+ ];
2103
+ try {
2104
+ const twConfigPath = path5__namespace.default.join(process.cwd(), "tailwind-styled.config.json");
2105
+ if (fs5__namespace.default.existsSync(twConfigPath)) {
2106
+ const twConfig = JSON.parse(fs5__namespace.default.readFileSync(twConfigPath, "utf-8"));
2107
+ const cssEntry = twConfig.css?.entry;
2108
+ if (cssEntry) {
2109
+ const cssEntryPath = path5__namespace.default.join(process.cwd(), cssEntry);
2110
+ if (fs5__namespace.default.existsSync(cssEntryPath)) {
2111
+ cssEntryContent = fs5__namespace.default.readFileSync(cssEntryPath, "utf-8");
2112
+ }
2113
+ }
2114
+ }
2115
+ } catch {
2116
+ }
2117
+ if (!cssEntryContent) {
2118
+ for (const candidate of CSS_CANDIDATES) {
2119
+ const candidatePath = path5__namespace.default.join(process.cwd(), candidate);
2120
+ if (fs5__namespace.default.existsSync(candidatePath)) {
2121
+ cssEntryContent = fs5__namespace.default.readFileSync(candidatePath, "utf-8");
2122
+ break;
2123
+ }
2124
+ }
2125
+ }
2126
+ if (cssEntryContent) {
2127
+ cssEntryContent = cssEntryContent.replace(/@source\s+["'][^"']+["']\s*;?\s*/g, "").replace(/←[^\n]*/g, "").trim();
2128
+ }
2129
+ const initialScanPath = path5__namespace.default.join(twClassesDir, "_initial-scan.css");
2130
+ if (!fs5__namespace.default.existsSync(initialScanPath)) {
2131
+ atomicWriteFile2(
2132
+ initialScanPath,
2133
+ "/* tw-classes: initial scan \u2014 generating... */\n@layer utilities {}\n"
2134
+ );
2135
+ }
2136
+ void (async () => {
2137
+ try {
2138
+ const compiler = await Promise.resolve().then(() => (init_src2(), src_exports));
2139
+ const generateCssForClasses2 = compiler.generateCssForClasses;
2140
+ const css = await generateCssForClasses2(
2141
+ filteredClasses,
2142
+ {},
2143
+ process.cwd(),
2144
+ cssEntryContent ?? void 0,
2145
+ process.env.NODE_ENV === "production"
2146
+ // minify hanya di production
2147
+ );
2148
+ if (css) {
2149
+ const utilitiesOnly = extractUtilitiesLayer2(css);
2150
+ atomicWriteFile2(
2151
+ initialScanPath,
2152
+ `/* tw-classes: initial scan \u2014 auto-generated by withTailwindStyled */
2153
+ ${utilitiesOnly}`
2154
+ );
2155
+ }
2156
+ } catch (err) {
2157
+ console.warn("[tailwind-styled] generateCssForClasses gagal, fallback ke empty rules:", err.message?.split("\n")[0]);
2158
+ const css = [
2159
+ "/* tw-safelist: initial scan \u2014 auto-generated by withTailwindStyled (fallback) */",
2160
+ "@layer utilities {",
2161
+ filteredClasses.map((cls) => `.${cls.replace(/([^a-zA-Z0-9_-])/g, "\\$1")} {}`).join("\n"),
2162
+ "}"
2163
+ ].join("\n");
2164
+ atomicWriteFile2(initialScanPath, css);
2165
+ }
2166
+ })();
2167
+ }
2168
+ } catch (e) {
2169
+ console.warn("[tailwind-styled] Initial scan skipped:", e.message?.split("\n")[0]);
2170
+ }
2171
+ }
2172
+ }
2173
+ } catch {
2174
+ }
299
2175
  return {
300
2176
  ...nextConfig,
301
2177
  webpack(config, webpackOptions) {
2178
+ if (webpackOptions.dev) {
2179
+ if (typeof previousWebpack !== "function") return config;
2180
+ try {
2181
+ const r = previousWebpack(config, webpackOptions);
2182
+ return r instanceof Promise ? r : r;
2183
+ } catch {
2184
+ return config;
2185
+ }
2186
+ }
302
2187
  const apply = (resolvedConfig) => {
303
2188
  const finalConfig = applyWebpackRule(resolvedConfig, normalizedOptions, webpackLoaderPath);
304
2189
  if (!finalConfig.externals) {
@@ -327,6 +2212,20 @@ function withTailwindStyled(options = {}) {
327
2212
  });
328
2213
  }
329
2214
  },
2215
+ serverExternalPackages: [
2216
+ .../* @__PURE__ */ new Set([
2217
+ ...nextConfig.serverExternalPackages ?? [],
2218
+ "tailwind-styled-v4",
2219
+ "@tailwind-styled/core",
2220
+ "@tailwind-styled/shared",
2221
+ "@tailwind-styled/compiler",
2222
+ "@tailwind-styled/engine",
2223
+ "@tailwind-styled/analyzer",
2224
+ "@tailwind-styled/scanner",
2225
+ "@tailwind-styled/plugin",
2226
+ "@tailwind-styled/runtime-css"
2227
+ ])
2228
+ ],
330
2229
  turbopack: {
331
2230
  ...nextConfig.turbopack ?? {},
332
2231
  rules: mergeTurbopackRules(