@animus-ui/next-plugin 0.1.1-beta.2 → 0.1.2

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 (42) hide show
  1. package/README.md +83 -4
  2. package/dist/chunk-y_GBKt04.mjs +5 -0
  3. package/dist/extraction-session.d.ts +138 -0
  4. package/dist/extraction-session.d.ts.map +1 -0
  5. package/dist/index.cjs +762 -541
  6. package/dist/index.mjs +762 -540
  7. package/dist/loader-core-CbaYNhBu.cjs +71 -0
  8. package/dist/loader-core-D6Tm_b8F.mjs +66 -0
  9. package/dist/loader-core.d.ts +26 -0
  10. package/dist/loader-core.d.ts.map +1 -0
  11. package/dist/loader.cjs +12 -43
  12. package/dist/loader.d.ts +5 -9
  13. package/dist/loader.d.ts.map +1 -1
  14. package/dist/loader.mjs +12 -43
  15. package/dist/plugin.d.ts +24 -42
  16. package/dist/plugin.d.ts.map +1 -1
  17. package/dist/resolve-packages.d.ts +8 -0
  18. package/dist/resolve-packages.d.ts.map +1 -0
  19. package/dist/singleton-BKALu7Mk.mjs +108 -0
  20. package/dist/{singleton-CttvA4Rg.cjs → singleton-DH7yeWZa.cjs} +29 -60
  21. package/dist/singleton.d.ts +1 -8
  22. package/dist/singleton.d.ts.map +1 -1
  23. package/dist/timing.d.ts +7 -0
  24. package/dist/timing.d.ts.map +1 -0
  25. package/dist/turbopack-config.d.ts +55 -0
  26. package/dist/turbopack-config.d.ts.map +1 -0
  27. package/dist/turbopack-loader.cjs +90 -0
  28. package/dist/turbopack-loader.d.ts +16 -0
  29. package/dist/turbopack-loader.d.ts.map +1 -0
  30. package/dist/turbopack-loader.mjs +91 -0
  31. package/dist/turbopack-orchestrator.d.ts +31 -0
  32. package/dist/turbopack-orchestrator.d.ts.map +1 -0
  33. package/dist/types.d.ts +67 -10
  34. package/dist/types.d.ts.map +1 -1
  35. package/dist/with-animus.d.ts +1 -1
  36. package/dist/with-animus.d.ts.map +1 -1
  37. package/package.json +5 -5
  38. package/dist/analyze-project-args.d.ts +0 -33
  39. package/dist/analyze-project-args.d.ts.map +0 -1
  40. package/dist/manifest-diagnostics.d.ts +0 -10
  41. package/dist/manifest-diagnostics.d.ts.map +0 -1
  42. package/dist/singleton-CmwFBCJ5.mjs +0 -136
package/dist/index.mjs CHANGED
@@ -1,67 +1,161 @@
1
- import { a as getSharedEngine, c as resetAnalysisPromise, d as setSharedCss, f as setSharedEngine, g as __require, h as setSharedSystemProps, i as getSharedCss, l as setAnalysisPromise, m as setSharedExternalEntries, n as getAnalysisPromise, o as getSharedExternalDirs, p as setSharedExternalDirs, s as getSharedExternalEntries, t as engineApi, u as setManifestJson } from "./singleton-CmwFBCJ5.mjs";
2
- import { existsSync, mkdirSync, readFileSync, readdirSync, statSync, writeFileSync } from "fs";
1
+ import { t as __require } from "./chunk-y_GBKt04.mjs";
2
+ import { a as getSharedExternalDirs, c as setAnalysisPromise, d as setSharedEngine, f as setSharedExternalDirs, i as getSharedCss, l as setManifestJson, m as setSharedSystemProps, n as getAnalysisPromise, o as getSharedExternalEntries, p as setSharedExternalEntries, s as resetAnalysisPromise, t as engineApi, u as setSharedCss } from "./singleton-BKALu7Mk.mjs";
3
+ import { DEFAULT_EXTENSIONS, assembleStylesheet, assertNoRetiredEngineSelection, buildPathAliasesJson, buildSystemPropsModule, clearEngineCache, collectExternalPackageSources, contentHash, discoverFiles, extractSystemFilePackages, formatRustTimingWaterfall, loadSystemConfig, postProcessCss, preprocessMdx, readTsconfigAliasPairs, resolveLightningTargets, runProjectAnalysis, serializeStaticCss, toWatchKeys } from "@animus-ui/extract/pipeline";
4
+ import { existsSync, mkdirSync, readFileSync, readdirSync, renameSync, statSync, watch, writeFileSync } from "fs";
3
5
  import { dirname, extname, join, relative, resolve, sep } from "path";
4
6
  import { fileURLToPath } from "url";
5
- import { DEFAULT_EXTENSIONS, applyPrefix, applyUnitFallback, assembleStylesheet, extractSystemFilePackages, preprocessMdx } from "@animus-ui/extract/pipeline";
6
- import { createHash } from "crypto";
7
- //#region src/analyze-project-args.ts
8
- function buildAnalyzeProjectArgs(inputs, devMode) {
9
- return [
10
- inputs.filesJson,
11
- inputs.scalesJson,
12
- inputs.variableMapJson,
13
- inputs.contextualVarsJson,
14
- inputs.propConfigJson,
15
- inputs.groupRegistryJson,
16
- inputs.packageResolutionJson,
17
- devMode,
18
- inputs.emitterConfigJson,
19
- inputs.selectorAliasesJson,
20
- null,
21
- inputs.globalStyleBlocksJson,
22
- inputs.pathAliasesJson,
23
- inputs.keyframesJson
24
- ];
25
- }
26
- function buildProductionAnalyzeProjectArgs(inputs) {
27
- return buildAnalyzeProjectArgs(inputs, false);
28
- }
29
- function buildHmrAnalyzeProjectArgs(inputs) {
30
- return buildAnalyzeProjectArgs(inputs, true);
7
+ //#region src/resolve-packages.ts
8
+ /**
9
+ * Resolve external DS package specifiers to rootDir-relative entry paths.
10
+ * Node-generic (no webpack APIs): Pass 1 walks the consumer's workspaces for
11
+ * matching package names; Pass 2 falls back to `require.resolve`. Specifiers
12
+ * that resolve nowhere are simply omitted (spec: silent skip).
13
+ */
14
+ function resolvePackagesByName(rootDir, names) {
15
+ if (names.length === 0) return {};
16
+ const nameSet = new Set(names);
17
+ const resolved = /* @__PURE__ */ new Set();
18
+ const packageMap = {};
19
+ try {
20
+ const rootPkg = JSON.parse(readFileSync(join(rootDir, "package.json"), "utf-8"));
21
+ const workspaces = Array.isArray(rootPkg.workspaces) ? rootPkg.workspaces : rootPkg.workspaces?.packages ?? [];
22
+ for (const ws of workspaces) {
23
+ const wsDir = resolve(rootDir, ws);
24
+ if (!existsSync(wsDir)) continue;
25
+ try {
26
+ const pkg = JSON.parse(readFileSync(join(wsDir, "package.json"), "utf-8"));
27
+ const name = pkg.name || "";
28
+ if (nameSet.has(name)) {
29
+ const entryPath = resolve(wsDir, pkg.main || pkg.module || "index.ts");
30
+ if (existsSync(entryPath)) {
31
+ packageMap[name] = relative(rootDir, entryPath);
32
+ resolved.add(name);
33
+ }
34
+ }
35
+ } catch {}
36
+ }
37
+ } catch {}
38
+ for (const name of nameSet) {
39
+ if (resolved.has(name)) continue;
40
+ try {
41
+ packageMap[name] = relative(rootDir, __require.resolve(name, { paths: [rootDir] }));
42
+ } catch {}
43
+ }
44
+ return packageMap;
31
45
  }
32
46
  //#endregion
33
- //#region src/manifest-diagnostics.ts
34
- function surfaceManifestDiagnostics(manifest, warn) {
35
- for (const diagnostic of manifest.diagnostics ?? []) {
36
- if (diagnostic.kind !== "warn") continue;
37
- warn(`⚠ ${diagnostic.file}: ${diagnostic.component}: ${diagnostic.message}`);
47
+ //#region src/timing.ts
48
+ /**
49
+ * Verbose build-timing waterfall: JS phases, analysis sub-phases, and the
50
+ * shared Rust phase table. `ANIMUS_TIMING_JSON=1` additionally dumps a
51
+ * machine-readable merged record.
52
+ */
53
+ function logBuildTimings(bt, rustTiming, log, verbose) {
54
+ if (!verbose) return;
55
+ const pad = (label, width) => label + " ".repeat(Math.max(0, width - label.length));
56
+ for (const [key, label] of [
57
+ ["systemLoad", "system-load"],
58
+ ["fileDiscovery", "file-discovery"],
59
+ ["fileRead", "file-read+hash"],
60
+ ["packageResolve", "pkg-resolve"],
61
+ ["analysis", "analysis"]
62
+ ]) {
63
+ const ms = bt[key] ?? 0;
64
+ if (ms === 0 && !Object.hasOwn(bt, key)) continue;
65
+ log(` ${pad(label, 17)}${String(ms).padStart(5)}ms`);
66
+ if (key === "analysis") for (const [sk, sl] of [
67
+ ["jsonSerialize", "json-serialize"],
68
+ ["rustExtract", "rust-extract"],
69
+ ["jsonParse", "json-parse"]
70
+ ]) {
71
+ const sms = bt[sk] ?? 0;
72
+ log(` ${pad(sl, 15)}${String(sms).padStart(5)}ms`);
73
+ if (sk === "rustExtract" && rustTiming) for (const line of formatRustTimingWaterfall(rustTiming, {
74
+ indent: " ",
75
+ labelWidth: 13
76
+ })) log(line);
77
+ }
78
+ }
79
+ log(` total ${String(bt.total).padStart(5)}ms`);
80
+ if (process.env.ANIMUS_TIMING_JSON === "1") {
81
+ const merged = {};
82
+ for (const [k, v] of Object.entries(bt)) merged[`buildStart.${k}`] = v;
83
+ if (rustTiming) {
84
+ for (const [k, v] of Object.entries(rustTiming)) if (typeof v === "number") merged[`rust.${k}`] = v;
85
+ }
86
+ console.info(`[animus:timing] ${JSON.stringify(merged)}`);
38
87
  }
39
88
  }
40
89
  //#endregion
41
- //#region src/plugin.ts
42
- const PLUGIN_NAME = "AnimusWebpackPlugin";
43
- var AnimusWebpackPlugin = class {
44
- options;
90
+ //#region src/extraction-session.ts
91
+ /**
92
+ * Module id the Rust emitter injects for the extracted stylesheet — also the
93
+ * exact resolve.alias key with-animus registers for it, which the adapter's
94
+ * alias harvesting must skip.
95
+ */
96
+ const ANIMUS_CSS_MODULE_ID = ".animus/styles.css";
97
+ /** Default path fragments excluded from source discovery (full + watch). */
98
+ const DEFAULT_EXCLUDE = [
99
+ "node_modules",
100
+ "dist",
101
+ ".test.",
102
+ ".spec.",
103
+ ".next",
104
+ ".animus"
105
+ ];
106
+ /**
107
+ * Bundler-agnostic extraction pipeline: system loading, source discovery
108
+ * and ingestion, external-package collection, analysis, stylesheet and
109
+ * system-props emission, and watch-cycle diffing.
110
+ *
111
+ * The webpack adapter (plugin.ts) owns only bundler wiring: hook
112
+ * registration, alias harvesting from the compiler config, in-memory asset
113
+ * replacement, and translating watch events into `handleWatchUpdate`
114
+ * change sets. Keeping this class free of webpack types is deliberate — a
115
+ * future Turbopack integration must drive the same session from outside
116
+ * the bundler (Turbopack has no compiler-hook surface), reusing everything
117
+ * here unchanged.
118
+ *
119
+ * Outputs are published through the package singleton (shared CSS,
120
+ * manifest, system props) and written to `.animus/` on disk.
121
+ */
122
+ var ExtractionSession = class {
123
+ /** Set by the adapter before any pipeline run. */
45
124
  rootDir = null;
46
- configJson = "";
47
- groupRegistryJson = "";
48
- themeJson = "";
49
- variableMapJson = "";
50
- variableCss = "";
51
- contextualVarsJson = null;
52
- selectorAliasesJson = null;
53
- globalCss = "";
54
- globalStyleBlocksJson = null;
55
- keyframesBlocksJson = null;
125
+ /** Serialized path aliases, harvested by the adapter from bundler config. */
56
126
  pathAliasesJson = null;
127
+ /** When set (Turbopack orchestration), every analysis also persists
128
+ * `.animus/analysis-inputs.json` so isolated loader workers can hydrate.
129
+ * Webpack mode leaves this off — its loader shares the process. */
130
+ persistAnalysisInputs = false;
131
+ /** Emitter identity override for the system-props module id. Webpack mode
132
+ * (null) injects the absolute `.animus/system-props.js` path, resolved by
133
+ * NormalModuleReplacement; Turbopack rejects absolute-path imports, so
134
+ * its driver sets the virtual id that `resolveAlias` maps to disk. */
135
+ systemPropsModuleId = null;
136
+ /** Absolute directory prefixes for external DS packages (loader allowlisting). */
137
+ externalPackageDirs = [];
138
+ /** External package specifier → absolute source entry path. */
139
+ externalSourceEntries = /* @__PURE__ */ new Map();
140
+ options;
141
+ staticCssJson;
142
+ system = null;
143
+ /** Full package-resolution map from the last full pipeline — replayed by
144
+ * incremental passes (sourceEntries alone omits dist-resolved packages). */
145
+ lastPackageMap = {};
57
146
  fileCache = /* @__PURE__ */ new Map();
147
+ systemDependencyKeys = /* @__PURE__ */ new Set();
148
+ /** Loader-reported dependency paths for bundler watch registration. */
149
+ systemDependencyPaths = [];
150
+ systemDependencyHashes = /* @__PURE__ */ new Map();
58
151
  lastCssHash = null;
59
152
  lastSystemPropsHash = null;
60
- externalPackageDirs = [];
61
- externalSourceEntries = /* @__PURE__ */ new Map();
153
+ lastManifestHash = null;
154
+ lastAnalysisInputsHash = null;
155
+ lcssTargets = null;
62
156
  constructor(options) {
63
157
  this.options = options;
64
- setSharedEngine(options.engine ?? "v2");
158
+ this.staticCssJson = serializeStaticCss(options.staticCss);
65
159
  }
66
160
  get verbose() {
67
161
  return this.options.verbose === true || process.env.ANIMUS_DEBUG === "1" || process.env.ANIMUS_DEBUG === "true";
@@ -78,176 +172,82 @@ var AnimusWebpackPlugin = class {
78
172
  elapsed(t) {
79
173
  return this.verbose ? Math.round(performance.now() - t) : 0;
80
174
  }
81
- logBuildTimings(bt, rustTiming) {
82
- if (!this.verbose) return;
83
- for (const [key, label] of [
84
- ["systemLoad", "system-load"],
85
- ["fileDiscovery", "file-discovery"],
86
- ["fileRead", "file-read+hash"],
87
- ["packageResolve", "pkg-resolve"],
88
- ["analysis", "analysis"]
89
- ]) {
90
- const ms = bt[key] ?? 0;
91
- if (ms === 0 && !Object.hasOwn(bt, key)) continue;
92
- const pad = " ".repeat(Math.max(0, 17 - label.length));
93
- this.log(` ${label}${pad}${String(ms).padStart(5)}ms`);
94
- if (key === "analysis") for (const [sk, sl] of [
95
- ["jsonSerialize", "json-serialize"],
96
- ["rustExtract", "rust-extract"],
97
- ["jsonParse", "json-parse"]
98
- ]) {
99
- const sms = bt[sk] ?? 0;
100
- const spad = " ".repeat(Math.max(0, 15 - sl.length));
101
- this.log(` ${sl}${spad}${String(sms).padStart(5)}ms`);
102
- if (sk === "rustExtract" && rustTiming) for (const [rk, rl] of [
103
- ["parseAndWalk", "parse+walk"],
104
- ["importResolution", "imports"],
105
- ["extensionProvenance", "provenance"],
106
- ["topologicalSort", "topo-sort"],
107
- ["chainEvaluation", "chains"],
108
- ["jsxScanning", "jsx-scan"],
109
- ["systemPropAggregation", "sys-props"],
110
- ["usageLedger", "usage"],
111
- ["reconciliation", "reconcile"],
112
- ["cssGeneration", "css-gen"],
113
- ["manifestSerialization", "serialize"]
114
- ]) {
115
- const rms = rustTiming[rk] ?? 0;
116
- const rpad = " ".repeat(Math.max(0, 13 - rl.length));
117
- const rextra = rk === "parseAndWalk" ? ` (${rustTiming.fileCount ?? 0} files, ${rustTiming.cacheHits ?? 0} cached)` : "";
118
- this.log(` ${rl}${rpad}${String(rms).padStart(5)}ms${rextra}`);
119
- }
120
- }
121
- }
122
- this.log(` total ${String(bt.total).padStart(5)}ms`);
123
- if (process.env.ANIMUS_TIMING_JSON === "1") {
124
- const merged = {};
125
- for (const [k, v] of Object.entries(bt)) merged[`buildStart.${k}`] = v;
126
- if (rustTiming) {
127
- for (const [k, v] of Object.entries(rustTiming)) if (typeof v === "number") merged[`rust.${k}`] = v;
128
- }
129
- console.info(`[animus:timing] ${JSON.stringify(merged)}`);
130
- }
131
- }
132
- initialized = false;
133
- /** Extract path aliases from webpack's resolve.alias config. */
134
- extractAliases(compiler) {
135
- const rootDir = compiler.context;
136
- const rawAlias = compiler.options?.resolve?.alias;
137
- if (!rawAlias || typeof rawAlias !== "object") return;
138
- const entries = [];
139
- for (const [key, value] of Object.entries(rawAlias)) {
140
- const target = Array.isArray(value) ? value[0] : value;
141
- if (typeof target !== "string") continue;
142
- if (key.includes(".animus")) continue;
143
- const replacement = target.startsWith(rootDir) ? target.slice(rootDir.length + 1) : target;
144
- if (/\.\w+$/.test(replacement)) entries.push({
145
- pattern: key,
146
- replacement,
147
- type: "exact"
148
- });
149
- else entries.push({
150
- pattern: key.endsWith("/") ? key : key + "/",
151
- replacement: replacement.endsWith("/") ? replacement : replacement + "/",
152
- type: "prefix"
153
- });
154
- }
155
- entries.sort((a, b) => b.pattern.length - a.pattern.length);
156
- if (entries.length > 0) this.pathAliasesJson = JSON.stringify({ aliases: entries });
157
- }
158
- apply(compiler) {
159
- if (compiler.options?.name === "edge-server") return;
160
- compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation) => {
161
- const stage = compiler.webpack?.Compilation.PROCESS_ASSETS_STAGE_ADDITIONAL ?? -2e3;
162
- const RawSource = compiler.webpack?.sources.RawSource;
163
- compilation.hooks.processAssets.tap({
164
- name: PLUGIN_NAME,
165
- stage
166
- }, () => {
167
- const css = getSharedCss();
168
- if (!css || !RawSource) return;
169
- const cssPath = join(this.rootDir || compiler.context, ".animus", "styles.css");
170
- if (compilation.getAsset(cssPath)) {
171
- compilation.updateAsset(cssPath, new RawSource(css));
172
- return;
173
- }
174
- const relPath = ".animus/styles.css";
175
- if (compilation.getAsset(relPath)) compilation.updateAsset(relPath, new RawSource(css));
176
- });
177
- });
178
- compiler.hooks.run.tapPromise(PLUGIN_NAME, async (_compiler) => {
179
- this.rootDir = _compiler.context;
180
- this.extractAliases(_compiler);
181
- const existing = getAnalysisPromise();
182
- if (existing) {
183
- await existing;
184
- return;
185
- }
186
- const promise = this.runFullPipeline();
187
- setAnalysisPromise(promise);
188
- await promise;
189
- });
190
- compiler.hooks.watchRun.tapPromise(PLUGIN_NAME, async (_compiler) => {
191
- this.rootDir = _compiler.context;
192
- this.extractAliases(_compiler);
193
- if (!this.initialized) {
194
- const existing = getAnalysisPromise();
195
- if (existing) {
196
- await existing;
197
- this.initialized = true;
198
- return;
199
- }
200
- const promise = this.runFullPipeline();
201
- setAnalysisPromise(promise);
202
- await promise;
203
- this.initialized = true;
204
- return;
205
- }
206
- await this.handleWatchUpdate();
207
- });
175
+ /** Resolve the scan configuration from options — the single source of the
176
+ * exclude/extension policy shared by the full and incremental pipelines. */
177
+ resolveScanConfig() {
178
+ const extensionsSet = new Set(this.options.extensions ?? DEFAULT_EXTENSIONS);
179
+ return {
180
+ excludePatterns: this.options.exclude ?? DEFAULT_EXCLUDE,
181
+ extensionsSet,
182
+ shouldHandleMdx: extensionsSet.has(".mdx")
183
+ };
208
184
  }
209
- async handleWatchUpdate() {
210
- if (this.configJson === "") return;
185
+ /**
186
+ * Incremental watch pass: geological reset when the system file changed,
187
+ * otherwise content-hash diffing restricted to the watcher's change sets
188
+ * (falling back to a full discovery walk when no sets are provided).
189
+ */
190
+ async handleWatchUpdate(changes) {
191
+ if (!this.system) return;
211
192
  const rootDir = this.rootDir;
212
- const resolvedSystemPath = resolve(rootDir, this.options.system);
213
193
  try {
214
- const systemSource = readFileSync(resolvedSystemPath, "utf-8");
215
- const systemRelPath = relative(rootDir, resolvedSystemPath);
216
- const cached = this.fileCache.get(systemRelPath);
217
- const currentHash = createHash("md5").update(systemSource).digest("hex");
218
- if (cached && cached.hash !== currentHash) {
194
+ let systemHit;
195
+ if (!changes.modifiedFiles && !changes.removedFiles) for (const [dep, hash] of this.systemDependencyHashes) {
196
+ let current = "";
197
+ try {
198
+ current = contentHash(readFileSync(dep, "utf-8"));
199
+ } catch {}
200
+ if (current !== hash) {
201
+ systemHit = dep;
202
+ break;
203
+ }
204
+ }
205
+ else systemHit = [...changes.modifiedFiles ?? [], ...changes.removedFiles ?? []].find((path) => toWatchKeys(path).some((key) => this.systemDependencyKeys.has(key)));
206
+ if (systemHit) {
207
+ this.log(`geological reset: system dependency changed (${relative(rootDir, systemHit)})`);
219
208
  this.resetForHmr();
220
- this.initialized = false;
221
209
  const promise = this.runFullPipeline();
222
210
  setAnalysisPromise(promise);
223
211
  await promise;
224
- this.initialized = true;
225
212
  return;
226
213
  }
227
- } catch {}
228
- const excludePatterns = this.options.exclude ?? [
229
- "node_modules",
230
- "dist",
231
- ".test.",
232
- ".spec.",
233
- ".next",
234
- ".animus"
235
- ];
236
- const extensionsSet = new Set(this.options.extensions ?? DEFAULT_EXTENSIONS);
237
- const shouldHandleMdx = extensionsSet.has(".mdx");
238
- const files = this.discoverFiles(rootDir, rootDir, excludePatterns, extensionsSet);
214
+ } catch (err) {
215
+ this.warn(`HMR geological-reset check failed: ${String(err)}`);
216
+ }
217
+ const { excludePatterns, extensionsSet, shouldHandleMdx } = this.resolveScanConfig();
218
+ let removedAny = false;
219
+ if (changes.removedFiles) for (const removedPath of changes.removedFiles) {
220
+ const rel = relative(rootDir, removedPath);
221
+ if (this.fileCache.delete(rel) || this.fileCache.delete(rel + ".tsx")) removedAny = true;
222
+ }
223
+ let files;
224
+ if (changes.modifiedFiles) {
225
+ files = [];
226
+ for (const modifiedPath of changes.modifiedFiles) {
227
+ if (!extensionsSet.has(extname(modifiedPath))) continue;
228
+ const rel = relative(rootDir, modifiedPath);
229
+ if (rel.startsWith("..")) continue;
230
+ if (excludePatterns.some((pattern) => modifiedPath.includes(pattern) || rel.includes(pattern))) continue;
231
+ files.push(modifiedPath);
232
+ }
233
+ } else files = discoverFiles(rootDir, rootDir, excludePatterns, extensionsSet);
239
234
  const changedPaths = [];
240
235
  for (const filePath of files) {
241
236
  let relPath = relative(rootDir, filePath);
242
- let source = readFileSync(filePath, "utf-8");
237
+ let source;
238
+ try {
239
+ source = readFileSync(filePath, "utf-8");
240
+ } catch {
241
+ continue;
242
+ }
243
243
  if (shouldHandleMdx && extname(filePath) === ".mdx") {
244
- const result = await preprocessMdx(source, relPath);
245
- if (result.kind !== "ok") continue;
246
- source = result.source;
247
- relPath = relPath + ".tsx";
244
+ const processed = await this.preprocessMdxEntry(source, relPath, { warn: false });
245
+ if (!processed) continue;
246
+ source = processed.source;
247
+ relPath = processed.relPath;
248
248
  }
249
249
  const cached = this.fileCache.get(relPath);
250
- const hash = createHash("md5").update(source).digest("hex");
250
+ const hash = contentHash(source);
251
251
  if (!cached || cached.hash !== hash) {
252
252
  changedPaths.push(relPath);
253
253
  this.fileCache.set(relPath, {
@@ -256,39 +256,74 @@ var AnimusWebpackPlugin = class {
256
256
  });
257
257
  }
258
258
  }
259
- if (changedPaths.length > 0) {
260
- const fileEntries = this.buildFileEntriesFromCache(changedPaths);
259
+ if (changedPaths.length > 0 || removedAny) {
260
+ const fileEntries = this.buildFileEntriesFromCache();
261
261
  resetAnalysisPromise();
262
262
  const promise = this.runIncrementalPipeline(fileEntries);
263
263
  setAnalysisPromise(promise);
264
264
  await promise;
265
265
  }
266
266
  }
267
+ /**
268
+ * Preprocess one `.mdx` entry into scanner-consumable tsx. Returns the
269
+ * rewritten source plus the `relPath + '.tsx'` path on success, or null
270
+ * when the file must be skipped.
271
+ *
272
+ * `warn: false` (incremental watch pass) skips silently — the full
273
+ * pipeline already surfaced the warning. `warn: true` (full pipeline)
274
+ * warns ONCE for a missing @mdx-js/mdx dependency via the shared
275
+ * `missingDepFlag` holder, and every time for a preprocessing error.
276
+ */
277
+ async preprocessMdxEntry(source, relPath, opts) {
278
+ const result = await preprocessMdx(source, relPath);
279
+ if (result.kind === "missing-dep") {
280
+ if (opts.warn && opts.missingDepFlag && !opts.missingDepFlag.warned) {
281
+ console.warn("[animus] ⚠ .mdx in extensions but @mdx-js/mdx not installed; MDX files skipped");
282
+ opts.missingDepFlag.warned = true;
283
+ }
284
+ return null;
285
+ }
286
+ if (result.kind === "error") {
287
+ if (opts.warn) console.warn(`[animus] ⚠ MDX preprocessing failed for ${relPath}: ${result.error}`);
288
+ return null;
289
+ }
290
+ return {
291
+ source: result.source,
292
+ relPath: relPath + ".tsx"
293
+ };
294
+ }
267
295
  async runFullPipeline() {
268
296
  const pipelineStart = this.now();
269
297
  const bt = {};
270
- try {
271
- const { clearAnalysisCache } = engineApi();
272
- clearAnalysisCache();
273
- } catch {}
298
+ clearEngineCache(engineApi);
274
299
  const rootDir = this.rootDir;
275
300
  const resolvedSystemPath = resolve(rootDir, this.options.system);
276
301
  let t = this.now();
277
- this.loadSystem(rootDir, resolvedSystemPath);
302
+ this.system = loadSystemConfig(engineApi, {
303
+ systemPath: resolvedSystemPath,
304
+ rootDir,
305
+ prefix: this.options.prefix
306
+ });
307
+ {
308
+ const deps = this.system.dependencies ?? [];
309
+ const keys = /* @__PURE__ */ new Set();
310
+ for (const key of toWatchKeys(resolvedSystemPath)) keys.add(key);
311
+ for (const dep of deps) for (const key of toWatchKeys(dep)) keys.add(key);
312
+ this.systemDependencyKeys = keys;
313
+ this.systemDependencyPaths = deps;
314
+ const hashes = /* @__PURE__ */ new Map();
315
+ for (const dep of deps.length > 0 ? deps : [resolvedSystemPath]) try {
316
+ hashes.set(dep, contentHash(readFileSync(dep, "utf-8")));
317
+ } catch {
318
+ hashes.set(dep, "");
319
+ }
320
+ this.systemDependencyHashes = hashes;
321
+ }
278
322
  bt.systemLoad = this.elapsed(t);
279
323
  t = this.now();
280
- const excludePatterns = this.options.exclude ?? [
281
- "node_modules",
282
- "dist",
283
- ".test.",
284
- ".spec.",
285
- ".next",
286
- ".animus"
287
- ];
288
- const extensionsSet = new Set(this.options.extensions ?? DEFAULT_EXTENSIONS);
289
- const shouldHandleMdx = extensionsSet.has(".mdx");
290
- let mdxMissingDepWarned = false;
291
- const files = this.discoverFiles(rootDir, rootDir, excludePatterns, extensionsSet);
324
+ const { excludePatterns, extensionsSet, shouldHandleMdx } = this.resolveScanConfig();
325
+ const missingDepFlag = { warned: false };
326
+ const files = discoverFiles(rootDir, rootDir, excludePatterns, extensionsSet);
292
327
  bt.fileDiscovery = this.elapsed(t);
293
328
  t = this.now();
294
329
  const fileEntries = [];
@@ -296,22 +331,15 @@ var AnimusWebpackPlugin = class {
296
331
  let source = readFileSync(filePath, "utf-8");
297
332
  let relPath = relative(rootDir, filePath);
298
333
  if (shouldHandleMdx && extname(filePath) === ".mdx") {
299
- const result = await preprocessMdx(source, relPath);
300
- if (result.kind === "missing-dep") {
301
- if (!mdxMissingDepWarned) {
302
- console.warn("[animus] ⚠ .mdx in extensions but @mdx-js/mdx not installed; MDX files skipped");
303
- mdxMissingDepWarned = true;
304
- }
305
- continue;
306
- }
307
- if (result.kind === "error") {
308
- console.warn(`[animus] ⚠ MDX preprocessing failed for ${relPath}: ${result.error}`);
309
- continue;
310
- }
311
- source = result.source;
312
- relPath = relPath + ".tsx";
334
+ const processed = await this.preprocessMdxEntry(source, relPath, {
335
+ warn: true,
336
+ missingDepFlag
337
+ });
338
+ if (!processed) continue;
339
+ source = processed.source;
340
+ relPath = processed.relPath;
313
341
  }
314
- const hash = createHash("md5").update(source).digest("hex");
342
+ const hash = contentHash(source);
315
343
  this.fileCache.set(relPath, {
316
344
  hash,
317
345
  source
@@ -326,216 +354,46 @@ var AnimusWebpackPlugin = class {
326
354
  bt.fileCount = fileEntries.length;
327
355
  t = this.now();
328
356
  const packageNames = extractSystemFilePackages(resolvedSystemPath);
329
- const packageMap = this.resolvePackagesByName(rootDir, packageNames);
330
- const excludePatternsForPkgs = [
331
- "dist",
332
- ".test.",
333
- ".spec."
334
- ];
335
- const collectedPkgDirs = [];
336
- this.externalSourceEntries.clear();
337
- for (const [specifier, entryRelPath] of Object.entries(packageMap)) {
338
- const absEntry = resolve(rootDir, entryRelPath);
339
- let pkgRoot = dirname(absEntry);
340
- while (pkgRoot !== dirname(pkgRoot) && !existsSync(join(pkgRoot, "package.json"))) pkgRoot = dirname(pkgRoot);
341
- const srcDir = join(pkgRoot, "src");
342
- if (existsSync(srcDir)) {
343
- collectedPkgDirs.push(srcDir);
344
- const srcEntry = join(srcDir, "index.ts");
345
- if (existsSync(srcEntry)) {
346
- packageMap[specifier] = relative(rootDir, srcEntry);
347
- this.externalSourceEntries.set(specifier, srcEntry);
348
- }
349
- const pkgFiles = this.discoverFiles(srcDir, rootDir, excludePatternsForPkgs, extensionsSet);
350
- for (const pkgFile of pkgFiles) {
351
- let pkgRelPath = relative(rootDir, pkgFile);
352
- if (!fileEntries.some((e) => e.path === pkgRelPath)) try {
353
- let pkgSource = readFileSync(pkgFile, "utf-8");
354
- if (shouldHandleMdx && extname(pkgFile) === ".mdx") {
355
- const result = await preprocessMdx(pkgSource, pkgRelPath);
356
- if (result.kind === "missing-dep") {
357
- if (!mdxMissingDepWarned) {
358
- console.warn("[animus] ⚠ .mdx in extensions but @mdx-js/mdx not installed; MDX files skipped");
359
- mdxMissingDepWarned = true;
360
- }
361
- continue;
362
- }
363
- if (result.kind === "error") {
364
- console.warn(`[animus] ⚠ MDX preprocessing failed for ${pkgRelPath}: ${result.error}`);
365
- continue;
366
- }
367
- pkgSource = result.source;
368
- pkgRelPath = pkgRelPath + ".tsx";
369
- }
370
- const pkgHash = createHash("md5").update(pkgSource).digest("hex");
371
- this.fileCache.set(pkgRelPath, {
372
- hash: pkgHash,
373
- source: pkgSource
374
- });
375
- fileEntries.push({
376
- path: pkgRelPath,
377
- source: pkgSource,
378
- hash: pkgHash
379
- });
380
- } catch {}
381
- }
382
- } else collectedPkgDirs.push(dirname(absEntry));
383
- }
384
- this.externalPackageDirs = collectedPkgDirs;
385
- setSharedExternalDirs(collectedPkgDirs);
386
- setSharedExternalEntries(this.externalSourceEntries);
387
- bt.packageResolve = this.elapsed(t);
388
- const { analyzeProject } = engineApi();
389
- const animusDirPath = join(rootDir, ".animus");
390
- const emitterConfig = JSON.stringify({
391
- runtime_import: "@animus-ui/system/runtime",
392
- css_module_id: ".animus/styles.css",
393
- system_props_module_id: join(animusDirPath, "system-props.js")
394
- });
395
- t = this.now();
396
- const fileEntriesJson = JSON.stringify(fileEntries);
397
- const packageMapJson = JSON.stringify(packageMap);
398
- bt.jsonSerialize = this.elapsed(t);
399
- t = this.now();
400
- const manifestJson = analyzeProject(...buildProductionAnalyzeProjectArgs({
401
- filesJson: fileEntriesJson,
402
- scalesJson: this.themeJson,
403
- variableMapJson: this.variableMapJson,
404
- contextualVarsJson: this.contextualVarsJson || null,
405
- propConfigJson: this.configJson,
406
- groupRegistryJson: this.groupRegistryJson,
407
- packageResolutionJson: packageMapJson,
408
- emitterConfigJson: emitterConfig,
409
- selectorAliasesJson: this.selectorAliasesJson,
410
- globalStyleBlocksJson: this.globalStyleBlocksJson,
411
- pathAliasesJson: this.pathAliasesJson,
412
- keyframesJson: this.keyframesBlocksJson
413
- }));
414
- bt.rustExtract = this.elapsed(t);
415
- t = this.now();
416
- const manifest = JSON.parse(manifestJson);
417
- surfaceManifestDiagnostics(manifest, (message) => this.warn(message));
418
- bt.jsonParse = this.elapsed(t);
419
- bt.analysis = (bt.jsonSerialize ?? 0) + (bt.rustExtract ?? 0) + (bt.jsonParse ?? 0);
420
- if (manifest?.report) this.log(`Extracted ${manifest.report.components_extracted ?? "?"}/${manifest.report.components_total ?? "?"} components (${bt.analysis}ms)`);
421
- this.globalCss = manifest?.sheets?.global || "";
422
- let componentCss = manifest?.css || "";
423
- componentCss = applyUnitFallback(componentCss);
424
- const { declaration, variables, body } = assembleStylesheet({
425
- layers: this.options.layers,
426
- variableCss: this.variableCss,
427
- globalCss: this.globalCss,
428
- componentCss,
429
- split: true
357
+ const preResolved = resolvePackagesByName(rootDir, packageNames);
358
+ const collected = await collectExternalPackageSources({
359
+ specifiers: packageNames,
360
+ resolveSpecifier: (name) => preResolved[name] ? resolve(rootDir, preResolved[name]) : null,
361
+ rootDir,
362
+ extensionsSet,
363
+ hasEntry: (relPath) => fileEntries.some((e) => e.path === relPath),
364
+ preprocessFile: async (source, relPath, absPath) => {
365
+ if (shouldHandleMdx && extname(absPath) === ".mdx") return this.preprocessMdxEntry(source, relPath, {
366
+ warn: true,
367
+ missingDepFlag
368
+ });
369
+ return {
370
+ source,
371
+ relPath
372
+ };
373
+ },
374
+ onUnreadable: (relPath, err) => this.warn(`skipped unreadable package file ${relPath}: ${String(err)}`)
430
375
  });
431
- const fullCss = [
432
- declaration,
433
- variables,
434
- body
435
- ].filter(Boolean).join("\n");
436
- setSharedCss(fullCss);
437
- const cssHash = createHash("md5").update(fullCss).digest("hex");
438
- if (cssHash !== this.lastCssHash) {
439
- const animusDir = join(rootDir, ".animus");
440
- if (!existsSync(animusDir)) mkdirSync(animusDir, { recursive: true });
441
- writeFileSync(join(animusDir, "styles.css"), fullCss);
442
- this.lastCssHash = cssHash;
443
- }
444
- const systemPropMap = JSON.stringify(manifest?.system_prop_map ?? {});
445
- const dynamicProps = manifest?.dynamic_props ?? {};
446
- const dynamicPropConfig = {};
447
- for (const [propName, meta] of Object.entries(dynamicProps)) dynamicPropConfig[propName] = {
448
- varName: meta.var_name,
449
- slotClass: meta.slot_class,
450
- ...meta.transform_name ? { transformName: meta.transform_name } : {},
451
- ...meta.scale_values && Object.keys(meta.scale_values).length > 0 ? { scaleValues: meta.scale_values } : {}
452
- };
453
- const transformsSource = "{}";
454
- const animusDir = join(rootDir, ".animus");
455
- if (!existsSync(animusDir)) mkdirSync(animusDir, { recursive: true });
456
- const systemPropsContent = `export const systemPropMap = ${systemPropMap};\nexport const systemPropGroups = ${this.groupRegistryJson};\nexport const dynamicPropConfig = ${JSON.stringify(dynamicPropConfig)};\nexport const transforms = ${transformsSource};\n`;
457
- setSharedSystemProps(systemPropsContent);
458
- writeFileSync(join(animusDir, "system-props.js"), systemPropsContent);
459
- setManifestJson(manifestJson);
460
- bt.total = this.elapsed(pipelineStart);
461
- this.logBuildTimings(bt, manifest?.timing);
462
- }
463
- loadSystem(rootDir, systemPath) {
464
- const { loadSystemModule } = engineApi();
465
- const config = loadSystemModule(systemPath, rootDir);
466
- this.configJson = config.propConfig;
467
- this.groupRegistryJson = config.groupRegistry;
468
- this.themeJson = config.scalesJson;
469
- this.variableMapJson = config.variableMapJson;
470
- this.variableCss = config.variableCss;
471
- this.contextualVarsJson = config.contextualVarsJson;
472
- this.selectorAliasesJson = config.selectorAliases || null;
473
- if (this.options.prefix) {
474
- const prefixed = applyPrefix(this.options.prefix, this.variableMapJson, this.variableCss, this.themeJson, this.contextualVarsJson || void 0);
475
- this.variableMapJson = prefixed.variableMapJson;
476
- this.variableCss = prefixed.variableCss;
477
- if (prefixed.themeJson) this.themeJson = prefixed.themeJson;
478
- if (prefixed.contextualVarsJson) this.contextualVarsJson = prefixed.contextualVarsJson;
479
- }
480
- this.globalStyleBlocksJson = config.globalStyleBlocks || null;
481
- this.keyframesBlocksJson = config.keyframesBlocks || null;
482
- }
483
- discoverFiles(dir, rootDir, excludePatterns, extensionsSet) {
484
- const results = [];
485
- const walk = (currentDir) => {
486
- let entries;
487
- try {
488
- entries = readdirSync(currentDir);
489
- } catch {
490
- return;
491
- }
492
- for (const entry of entries) {
493
- const fullPath = join(currentDir, entry);
494
- const relPath = relative(rootDir, fullPath);
495
- if (excludePatterns.some((p) => relPath.includes(p))) continue;
496
- let stat;
497
- try {
498
- stat = statSync(fullPath);
499
- } catch {
500
- continue;
501
- }
502
- if (stat.isDirectory()) walk(fullPath);
503
- else if (extensionsSet.has(extname(entry))) results.push(fullPath);
504
- }
505
- };
506
- walk(dir);
507
- return results;
508
- }
509
- resolvePackagesByName(rootDir, names) {
510
- if (names.length === 0) return {};
511
- const nameSet = new Set(names);
512
- const resolved = /* @__PURE__ */ new Set();
513
- const packageMap = {};
514
- try {
515
- const workspaces = JSON.parse(readFileSync(join(rootDir, "package.json"), "utf-8")).workspaces || [];
516
- for (const ws of workspaces) {
517
- const wsDir = resolve(rootDir, ws);
518
- if (!existsSync(wsDir)) continue;
519
- try {
520
- const pkg = JSON.parse(readFileSync(join(wsDir, "package.json"), "utf-8"));
521
- const name = pkg.name || "";
522
- if (nameSet.has(name)) {
523
- const entryPath = resolve(wsDir, pkg.main || pkg.module || "index.ts");
524
- if (existsSync(entryPath)) {
525
- packageMap[name] = relative(rootDir, entryPath);
526
- resolved.add(name);
527
- }
528
- }
529
- } catch {}
530
- }
531
- } catch {}
532
- for (const name of nameSet) {
533
- if (resolved.has(name)) continue;
534
- try {
535
- packageMap[name] = relative(rootDir, __require.resolve(name, { paths: [rootDir] }));
536
- } catch {}
376
+ for (const record of collected.outcomes) if (record.outcome === "empty") this.warn(`include '${record.specifier}' resolved but discovered no component sources`);
377
+ const packageMap = collected.packageMap;
378
+ this.lastPackageMap = packageMap;
379
+ this.externalSourceEntries = collected.sourceEntries;
380
+ for (const entry of collected.entries) {
381
+ const hash = contentHash(entry.source);
382
+ this.fileCache.set(entry.path, {
383
+ hash,
384
+ source: entry.source
385
+ });
386
+ fileEntries.push({
387
+ path: entry.path,
388
+ source: entry.source,
389
+ hash
390
+ });
537
391
  }
538
- return packageMap;
392
+ this.externalPackageDirs = collected.packageDirs;
393
+ setSharedExternalDirs(collected.packageDirs);
394
+ setSharedExternalEntries(collected.sourceEntries);
395
+ bt.packageResolve = this.elapsed(t);
396
+ await this.analyzeAndEmit(fileEntries, packageMap, false, bt, pipelineStart);
539
397
  }
540
398
  /**
541
399
  * Reset analysis state for HMR geological reset.
@@ -544,22 +402,21 @@ var AnimusWebpackPlugin = class {
544
402
  resetAnalysisPromise();
545
403
  this.lastCssHash = null;
546
404
  this.lastSystemPropsHash = null;
547
- try {
548
- const { clearAnalysisCache } = engineApi();
549
- clearAnalysisCache();
550
- } catch {}
405
+ this.lastManifestHash = null;
406
+ this.lastAnalysisInputsHash = null;
407
+ clearEngineCache(engineApi);
551
408
  }
552
409
  /**
553
- * Build cache-aware file entries: full source for changed files,
554
- * empty source + hash for unchanged (Rust cache-hit path skips these).
410
+ * Build file entries from cache: every cached file rides with full source.
411
+ * The v2 engine has NO Rust-side cache (extract-v2-spine DEF-7: uncached
412
+ * re-analysis beats a cache-hit path), so it must always receive full sources
413
+ * (openspec: retire-extract-v1 removed the v1 empty-source cache contract).
555
414
  */
556
- buildFileEntriesFromCache(changedPaths) {
557
- const changedSet = new Set(changedPaths);
558
- const fullSources = getSharedEngine() === "v2";
415
+ buildFileEntriesFromCache() {
559
416
  const entries = [];
560
417
  for (const [path, { hash, source }] of this.fileCache) entries.push({
561
418
  path,
562
- source: fullSources || changedSet.has(path) ? source : "",
419
+ source,
563
420
  hash
564
421
  });
565
422
  return entries;
@@ -569,88 +426,238 @@ var AnimusWebpackPlugin = class {
569
426
  * Reuses system config from the last full pipeline run.
570
427
  */
571
428
  async runIncrementalPipeline(fileEntries) {
572
- const rootDir = this.rootDir;
573
429
  const bt = {};
574
430
  const pipelineStart = this.now();
575
- const { analyzeProject } = engineApi();
576
- const animusDirPath = join(rootDir, ".animus");
577
- const emitterConfig = JSON.stringify({
578
- runtime_import: "@animus-ui/system/runtime",
579
- css_module_id: ".animus/styles.css",
580
- system_props_module_id: join(animusDirPath, "system-props.js")
581
- });
582
- const packageMapJson = JSON.stringify(Object.fromEntries(Array.from(this.externalSourceEntries).map(([spec, entry]) => [spec, relative(rootDir, entry)])));
583
- let t = this.now();
584
- const fileEntriesJson = JSON.stringify(fileEntries);
585
- bt.jsonSerialize = this.elapsed(t);
586
- t = this.now();
587
- const manifestJson = analyzeProject(...buildHmrAnalyzeProjectArgs({
588
- filesJson: fileEntriesJson,
589
- scalesJson: this.themeJson,
590
- variableMapJson: this.variableMapJson,
591
- contextualVarsJson: this.contextualVarsJson || null,
592
- propConfigJson: this.configJson,
593
- groupRegistryJson: this.groupRegistryJson,
594
- packageResolutionJson: packageMapJson,
595
- emitterConfigJson: emitterConfig,
596
- selectorAliasesJson: this.selectorAliasesJson,
597
- globalStyleBlocksJson: this.globalStyleBlocksJson,
431
+ await this.analyzeAndEmit(fileEntries, this.lastPackageMap, true, bt, pipelineStart);
432
+ }
433
+ /**
434
+ * Shared analysis + emit core for both pipelines — the single call site
435
+ * that routes every manifest through the shared `runProjectAnalysis`,
436
+ * reachable from both runFullPipeline (production) and
437
+ * runIncrementalPipeline (HMR).
438
+ *
439
+ * Owns diagnostic surfacing, CSS assembly + styles.css write guard,
440
+ * system-props module emit, and the timing log. The `devMode` flag is the
441
+ * ONLY behavioral fork:
442
+ *
443
+ * - `false` (production): computes bt.analysis + logs the extraction
444
+ * report, and writes system-props.js UNCONDITIONALLY (no
445
+ * lastSystemPropsHash guard).
446
+ * - `true` (HMR): skips the report log, and guards the system-props.js
447
+ * write by lastSystemPropsHash.
448
+ *
449
+ * The styles.css write guard (lastCssHash) is identical on both paths.
450
+ */
451
+ async analyzeAndEmit(fileEntries, packageMap, devMode, bt, pipelineStart) {
452
+ const system = this.system;
453
+ const result = runProjectAnalysis(engineApi, {
454
+ fileEntries,
455
+ packageMap,
456
+ system,
457
+ emitter: {
458
+ runtimeImport: "@animus-ui/system/runtime",
459
+ cssModuleId: ANIMUS_CSS_MODULE_ID,
460
+ systemPropsModuleId: this.systemPropsModuleId ?? join(this.rootDir, ".animus", "system-props.js")
461
+ },
598
462
  pathAliasesJson: this.pathAliasesJson,
599
- keyframesJson: this.keyframesBlocksJson
600
- }));
601
- bt.rustExtract = this.elapsed(t);
602
- t = this.now();
603
- const manifest = JSON.parse(manifestJson);
604
- surfaceManifestDiagnostics(manifest, (message) => this.warn(message));
605
- bt.jsonParse = this.elapsed(t);
606
- this.globalCss = manifest?.sheets?.global || "";
607
- let componentCss = manifest?.css || "";
608
- componentCss = applyUnitFallback(componentCss);
609
- const { declaration: hmrDecl, variables: hmrVars, body: hmrBody } = assembleStylesheet({
463
+ staticCssJson: this.staticCssJson,
464
+ devMode,
465
+ warn: (message) => this.warn(message)
466
+ });
467
+ bt.jsonSerialize = result.timings.serializeMs;
468
+ bt.rustExtract = result.timings.extractMs;
469
+ bt.jsonParse = result.timings.parseMs;
470
+ const manifest = result.manifest;
471
+ if (!devMode) {
472
+ bt.analysis = (bt.jsonSerialize ?? 0) + (bt.rustExtract ?? 0) + (bt.jsonParse ?? 0);
473
+ if (manifest?.report) this.log(`Extracted ${manifest.report.components_extracted ?? "?"}/${manifest.report.components_total ?? "?"} components (${bt.analysis}ms)`);
474
+ }
475
+ const { declaration, variables, body } = assembleStylesheet({
610
476
  layers: this.options.layers,
611
- variableCss: this.variableCss,
612
- globalCss: this.globalCss,
613
- componentCss,
477
+ variableCss: system.variableCss,
478
+ globalCss: result.globalCss,
479
+ componentCss: result.componentCss,
614
480
  split: true
615
481
  });
482
+ if (this.lcssTargets === null) this.lcssTargets = resolveLightningTargets(this.options.targets, this.rootDir);
616
483
  const fullCss = [
617
- hmrDecl,
618
- hmrVars,
619
- hmrBody
484
+ declaration,
485
+ variables,
486
+ postProcessCss(body, {
487
+ minify: this.options.minify ?? process.env.NODE_ENV === "production",
488
+ targets: this.lcssTargets,
489
+ warnFn: (msg) => this.warn(msg)
490
+ })
620
491
  ].filter(Boolean).join("\n");
621
492
  setSharedCss(fullCss);
622
- const cssHash = createHash("md5").update(fullCss).digest("hex");
493
+ const cssHash = contentHash(fullCss);
623
494
  if (cssHash !== this.lastCssHash) {
624
- const animusDir = join(rootDir, ".animus");
625
- if (!existsSync(animusDir)) mkdirSync(animusDir, { recursive: true });
626
- writeFileSync(join(animusDir, "styles.css"), fullCss);
495
+ this.writeAnimusFile("styles.css", fullCss);
627
496
  this.lastCssHash = cssHash;
628
497
  }
629
- const systemPropMap = JSON.stringify(manifest?.system_prop_map ?? {});
630
- const dynamicProps = manifest?.dynamic_props ?? {};
631
- const dynamicPropConfig = {};
632
- for (const [propName, meta] of Object.entries(dynamicProps)) dynamicPropConfig[propName] = {
633
- varName: meta.var_name,
634
- slotClass: meta.slot_class,
635
- ...meta.transform_name ? { transformName: meta.transform_name } : {},
636
- ...meta.scale_values && Object.keys(meta.scale_values).length > 0 ? { scaleValues: meta.scale_values } : {}
637
- };
638
- const systemPropsContent = `export const systemPropMap = ${systemPropMap};\nexport const systemPropGroups = ${this.groupRegistryJson};\nexport const dynamicPropConfig = ${JSON.stringify(dynamicPropConfig)};\nexport const transforms = {};\n`;
498
+ const systemPropsContent = buildSystemPropsModule({
499
+ systemPropMapJson: JSON.stringify(manifest?.system_prop_map ?? {}),
500
+ groupRegistryJson: system.groupRegistryJson,
501
+ dynamicProps: manifest?.dynamic_props ?? {}
502
+ });
639
503
  setSharedSystemProps(systemPropsContent);
640
- const systemPropsHash = createHash("md5").update(systemPropsContent).digest("hex");
641
- if (systemPropsHash !== this.lastSystemPropsHash) {
642
- const spDir = join(rootDir, ".animus");
643
- if (!existsSync(spDir)) mkdirSync(spDir, { recursive: true });
644
- writeFileSync(join(spDir, "system-props.js"), systemPropsContent);
645
- this.lastSystemPropsHash = systemPropsHash;
504
+ if (devMode) {
505
+ const systemPropsHash = contentHash(systemPropsContent);
506
+ if (systemPropsHash !== this.lastSystemPropsHash) {
507
+ this.writeAnimusFile("system-props.js", systemPropsContent);
508
+ this.lastSystemPropsHash = systemPropsHash;
509
+ }
510
+ } else this.writeAnimusFile("system-props.js", systemPropsContent);
511
+ setManifestJson(result.manifestJson);
512
+ const manifestHash = contentHash(result.manifestJson);
513
+ if (this.lastManifestHash === null) this.lastManifestHash = this.diskArtifactHash("manifest.json");
514
+ if (manifestHash !== this.lastManifestHash) {
515
+ this.writeAnimusFile("manifest.json", result.manifestJson);
516
+ this.lastManifestHash = manifestHash;
517
+ }
518
+ if (this.persistAnalysisInputs) {
519
+ const inputsJson = JSON.stringify(result.inputs);
520
+ const inputsHash = contentHash(inputsJson);
521
+ if (this.lastAnalysisInputsHash === null) this.lastAnalysisInputsHash = this.diskArtifactHash("analysis-inputs.json");
522
+ if (inputsHash !== this.lastAnalysisInputsHash) {
523
+ this.writeAnimusFile("analysis-inputs.json", inputsJson);
524
+ this.lastAnalysisInputsHash = inputsHash;
525
+ }
646
526
  }
647
- setManifestJson(manifestJson);
648
527
  bt.total = this.elapsed(pipelineStart);
649
- this.logBuildTimings(bt, manifest?.timing);
528
+ logBuildTimings(bt, manifest?.timing, (msg) => this.log(msg), this.verbose);
529
+ }
530
+ /** Content hash of an existing `.animus/` artifact, or null when absent or
531
+ * unreadable. Seeds a null write guard so a FRESH session never rewrites a
532
+ * byte-identical artifact (spec: next-turbopack-integration — a rewrite
533
+ * changes mtime/inode and needlessly re-keys Turbopack loader-worker
534
+ * hydration). */
535
+ diskArtifactHash(name) {
536
+ try {
537
+ return contentHash(readFileSync(join(this.rootDir, ".animus", name), "utf-8"));
538
+ } catch {
539
+ return null;
540
+ }
541
+ }
542
+ /** Ensure `.animus/` exists and write one generated artifact into it.
543
+ * Write-then-rename so cross-process readers (Turbopack loader workers)
544
+ * can never observe a torn half-written file. The tmp name carries the
545
+ * pid — Next dev evaluates the config in more than one process, and two
546
+ * sessions writing the same artifact must not race on one tmp path. */
547
+ writeAnimusFile(name, content) {
548
+ const dir = join(this.rootDir, ".animus");
549
+ if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
550
+ const tmpPath = join(dir, `.${name}.${process.pid}.tmp`);
551
+ writeFileSync(tmpPath, content);
552
+ renameSync(tmpPath, join(dir, name));
553
+ }
554
+ };
555
+ //#endregion
556
+ //#region src/plugin.ts
557
+ const PLUGIN_NAME = "AnimusWebpackPlugin";
558
+ /**
559
+ * Webpack adapter for the extraction pipeline. All pipeline logic lives in
560
+ * the bundler-agnostic ExtractionSession — this class owns only the webpack
561
+ * wiring: hook registration, cross-compiler analysis dedup, alias
562
+ * harvesting from the compiler config, watch-event translation, and
563
+ * in-memory CSS asset replacement.
564
+ */
565
+ var AnimusWebpackPlugin = class {
566
+ options;
567
+ session;
568
+ initialized = false;
569
+ aliasesExtracted = false;
570
+ constructor(options) {
571
+ this.options = options;
572
+ assertNoRetiredEngineSelection(options.engine);
573
+ setSharedEngine(options.engine ?? "v2");
574
+ this.session = new ExtractionSession(options);
575
+ }
576
+ /** Extract path aliases from webpack's resolve.alias config. Runs once per
577
+ * plugin instance — the resolve config is immutable after apply. */
578
+ extractAliases(compiler) {
579
+ if (this.aliasesExtracted) return;
580
+ this.aliasesExtracted = true;
581
+ const rootDir = compiler.context;
582
+ const rawAlias = compiler.options?.resolve?.alias;
583
+ if (!rawAlias || typeof rawAlias !== "object") return;
584
+ const pairs = [];
585
+ for (const [key, value] of Object.entries(rawAlias)) {
586
+ const target = Array.isArray(value) ? value[0] : value;
587
+ if (typeof target !== "string") continue;
588
+ if (key === ".animus/styles.css") continue;
589
+ pairs.push({
590
+ pattern: key,
591
+ target
592
+ });
593
+ }
594
+ const built = buildPathAliasesJson(pairs, rootDir);
595
+ if (built) this.session.pathAliasesJson = built.json;
596
+ }
597
+ apply(compiler) {
598
+ if (compiler.options?.name === "edge-server") return;
599
+ compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation) => {
600
+ const registerSystemDependencies = () => {
601
+ for (const dep of this.session.systemDependencyPaths) if (existsSync(dep)) compilation.fileDependencies.add(dep);
602
+ else compilation.missingDependencies.add(dep);
603
+ };
604
+ registerSystemDependencies();
605
+ const stage = compiler.webpack?.Compilation.PROCESS_ASSETS_STAGE_ADDITIONAL ?? -2e3;
606
+ const RawSource = compiler.webpack?.sources.RawSource;
607
+ compilation.hooks.processAssets.tap({
608
+ name: PLUGIN_NAME,
609
+ stage
610
+ }, () => {
611
+ registerSystemDependencies();
612
+ const css = getSharedCss();
613
+ if (!css || !RawSource) return;
614
+ const cssPath = join(this.session.rootDir || compiler.context, ".animus", "styles.css");
615
+ if (compilation.getAsset(cssPath)) {
616
+ compilation.updateAsset(cssPath, new RawSource(css));
617
+ return;
618
+ }
619
+ if (compilation.getAsset(".animus/styles.css")) compilation.updateAsset(ANIMUS_CSS_MODULE_ID, new RawSource(css));
620
+ });
621
+ });
622
+ compiler.hooks.run.tapPromise(PLUGIN_NAME, async (_compiler) => {
623
+ this.session.rootDir = _compiler.context;
624
+ this.extractAliases(_compiler);
625
+ const existing = getAnalysisPromise();
626
+ if (existing) {
627
+ await existing;
628
+ return;
629
+ }
630
+ const promise = this.session.runFullPipeline();
631
+ setAnalysisPromise(promise);
632
+ await promise;
633
+ });
634
+ compiler.hooks.watchRun.tapPromise(PLUGIN_NAME, async (_compiler) => {
635
+ this.session.rootDir = _compiler.context;
636
+ this.extractAliases(_compiler);
637
+ if (!this.initialized) {
638
+ const existing = getAnalysisPromise();
639
+ if (existing) {
640
+ await existing;
641
+ this.initialized = true;
642
+ return;
643
+ }
644
+ const promise = this.session.runFullPipeline();
645
+ setAnalysisPromise(promise);
646
+ await promise;
647
+ this.initialized = true;
648
+ return;
649
+ }
650
+ await this.session.handleWatchUpdate({
651
+ modifiedFiles: _compiler.modifiedFiles,
652
+ removedFiles: _compiler.removedFiles
653
+ });
654
+ });
650
655
  }
651
- /** Expose file cache for HMR change detection */
652
- getFileCache() {
653
- return this.fileCache;
656
+ /**
657
+ * Reset analysis state for HMR geological reset.
658
+ */
659
+ resetForHmr() {
660
+ this.session.resetForHmr();
654
661
  }
655
662
  /** Expose options for the loader */
656
663
  getOptions() {
@@ -659,18 +666,187 @@ var AnimusWebpackPlugin = class {
659
666
  /** Expose external package directories for webpack loader allowlisting.
660
667
  * Falls back to shared globalThis state for non-owning compiler instances. */
661
668
  getExternalPackageDirs() {
662
- return this.externalPackageDirs.length > 0 ? this.externalPackageDirs : getSharedExternalDirs();
669
+ return this.session.externalPackageDirs.length > 0 ? this.session.externalPackageDirs : getSharedExternalDirs();
663
670
  }
664
671
  /** Expose external package source entries for webpack resolve alias.
665
672
  * Falls back to shared globalThis state for non-owning compiler instances. */
666
673
  getExternalSourceEntries() {
667
- return this.externalSourceEntries.size > 0 ? this.externalSourceEntries : getSharedExternalEntries();
674
+ return this.session.externalSourceEntries.size > 0 ? this.session.externalSourceEntries : getSharedExternalEntries();
668
675
  }
669
676
  };
670
677
  //#endregion
678
+ //#region src/turbopack-config.ts
679
+ /** The single glob the Animus loader registers under. `.mjs` is included
680
+ * for webpack parity: an external package without `src/` is ingested via
681
+ * its resolved dist entry (often `dist/index.mjs`) and must still reach
682
+ * the loader — manifest lookup remains the file-level gate. */
683
+ const ANIMUS_TURBOPACK_RULE_GLOB = "*.{ts,tsx,js,jsx,mjs}";
684
+ /** Virtual system-props id emitted into transformed sources under Turbopack
685
+ * (absolute-path imports are rejected there); resolveAlias maps it to the
686
+ * on-disk artifact. */
687
+ const TURBOPACK_SYSTEM_PROPS_ID = "virtual:animus/system-props";
688
+ /**
689
+ * Resolve whether Turbopack wiring is active for this process. Default is
690
+ * `'auto'`: active exactly when the TURBOPACK environment variable is set
691
+ * (Next sets it for every Turbopack dev/build). The stable `turbopack`
692
+ * option wins over the deprecated `unstable_turbopack` alias.
693
+ */
694
+ function resolveTurbopackMode(options, env = process.env) {
695
+ const mode = options.turbopack?.mode ?? options.unstable_turbopack?.mode ?? "auto";
696
+ if (mode === "on") return true;
697
+ if (mode === "auto") return env.TURBOPACK !== void 0;
698
+ return false;
699
+ }
700
+ /**
701
+ * Build the `turbopack` config fragment: one glob-keyed loader rule
702
+ * (file-level allowlisting lives in the loader via manifest lookup — Next 15
703
+ * rules have no condition algebra) plus resolve aliases for the virtual
704
+ * system-props id, the emitter's stylesheet id, and each collected external
705
+ * package specifier redirected to its source entry.
706
+ */
707
+ function buildTurbopackConfig(args) {
708
+ const { rootDir, loaderPath, options, externalSourceEntries } = args;
709
+ const loaderOptions = {
710
+ rootDir,
711
+ ...options.strict !== void 0 ? { strict: options.strict } : {},
712
+ ...options.cssImportTarget !== void 0 ? { cssImportTarget: options.cssImportTarget } : {}
713
+ };
714
+ const resolveAlias = {
715
+ [TURBOPACK_SYSTEM_PROPS_ID]: "./.animus/system-props.js",
716
+ ".animus/styles.css": "./.animus/styles.css"
717
+ };
718
+ for (const [specifier, srcEntry] of externalSourceEntries) resolveAlias[specifier] = `./${relative(rootDir, srcEntry).replace(/\\/g, "/")}`;
719
+ return {
720
+ rules: { [ANIMUS_TURBOPACK_RULE_GLOB]: { loaders: [{
721
+ loader: loaderPath,
722
+ options: loaderOptions
723
+ }] } },
724
+ resolveAlias
725
+ };
726
+ }
727
+ /**
728
+ * Locate the Turbopack loader module: built dist first, source fallback for
729
+ * in-repo development. CJS preferred — Turbopack's loader-runner follows
730
+ * the webpack loader contract (`module.exports = fn`), and the .cjs build
731
+ * is loadable by every runner version; ESM default-export acceptance is
732
+ * not guaranteed.
733
+ */
734
+ function resolveTurbopackLoaderPath(pluginDir) {
735
+ for (const candidate of ["turbopack-loader.cjs", "turbopack-loader.mjs"]) {
736
+ const distPath = resolve(pluginDir, candidate);
737
+ if (existsSync(distPath)) return distPath;
738
+ }
739
+ return resolve(pluginDir, "turbopack-loader.ts");
740
+ }
741
+ //#endregion
742
+ //#region src/turbopack-orchestrator.ts
743
+ /**
744
+ * Out-of-band pipeline orchestration for Turbopack (spec:
745
+ * next-turbopack-integration). Turbopack exposes no compiler hooks, so the
746
+ * pipeline runs during next.config resolution and, in dev, from a
747
+ * filesystem watcher — the bundler only ever sees the `.animus/` disk
748
+ * artifacts.
749
+ */
750
+ /** Run the full pipeline with the Turbopack emitter identity: hydration
751
+ * artifacts persisted, and the virtual system-props id (Turbopack rejects
752
+ * the webpack path's absolute-path imports). */
753
+ async function runTurbopackPipeline(session) {
754
+ session.persistAnalysisInputs = true;
755
+ session.systemPropsModuleId = TURBOPACK_SYSTEM_PROPS_ID;
756
+ await session.runFullPipeline();
757
+ }
758
+ const activeWatcherRoots = /* @__PURE__ */ new Set();
759
+ const IGNORED_SEGMENTS = new Set([
760
+ ".animus",
761
+ ".next",
762
+ "node_modules"
763
+ ]);
764
+ /**
765
+ * Start the dev watcher: fs.watch per eligible top-level directory (plus a
766
+ * non-recursive watch on the root itself), debounced into
767
+ * existence-partitioned modified/removed sets feeding
768
+ * `session.handleWatchUpdate` (serialized — updates never overlap).
769
+ * Generated and vendored trees (`.animus`, `.next`, node_modules) are never
770
+ * registered with the OS — recursive registration of those trees exhausts
771
+ * inotify/kqueue descriptors (EMFILE/ENOSPC) on large projects.
772
+ * Idempotent per project root; unref'd so it never holds the process open.
773
+ * Asynchronous FSWatcher errors degrade to no-watch with a warning instead
774
+ * of crashing the dev server. Returns a close handle, or null when this
775
+ * root is already watched or the platform lacks recursive fs.watch (Linux
776
+ * before Node 20 — degrades to no-watch with a warning).
777
+ */
778
+ function startTurbopackWatcher(session, rootDir, debounceMs = 75, watchFn = watch) {
779
+ if (activeWatcherRoots.has(rootDir)) return null;
780
+ activeWatcherRoots.add(rootDir);
781
+ const pendingPaths = /* @__PURE__ */ new Set();
782
+ const watchers = /* @__PURE__ */ new Map();
783
+ let timer = null;
784
+ let updateChain = Promise.resolve();
785
+ let closed = false;
786
+ const flush = () => {
787
+ timer = null;
788
+ const modifiedFiles = /* @__PURE__ */ new Set();
789
+ const removedFiles = /* @__PURE__ */ new Set();
790
+ for (const path of pendingPaths) (existsSync(path) ? modifiedFiles : removedFiles).add(path);
791
+ pendingPaths.clear();
792
+ updateChain = updateChain.then(() => session.handleWatchUpdate({
793
+ modifiedFiles,
794
+ removedFiles
795
+ }).catch((err) => {
796
+ console.warn(`[animus-extract] Turbopack watch update failed: ${String(err)}`);
797
+ }));
798
+ };
799
+ const closeAll = () => {
800
+ if (closed) return;
801
+ closed = true;
802
+ if (timer) clearTimeout(timer);
803
+ timer = null;
804
+ for (const watcher of watchers.values()) watcher.close();
805
+ watchers.clear();
806
+ activeWatcherRoots.delete(rootDir);
807
+ };
808
+ const onWatcherError = (err) => {
809
+ closeAll();
810
+ console.warn(`[animus-extract] Turbopack dev watcher failed (${String(err)}); source edits require a dev-server restart`);
811
+ };
812
+ const onEvent = (baseDir, filename) => {
813
+ if (closed || !filename) return;
814
+ const rel = filename.toString();
815
+ if (rel.split(/[\\/]/).some((segment) => IGNORED_SEGMENTS.has(segment))) return;
816
+ const abs = join(baseDir, rel);
817
+ if (baseDir === rootDir && !watchers.has(abs)) try {
818
+ if (statSync(abs).isDirectory()) addWatcher(abs, true);
819
+ } catch {}
820
+ pendingPaths.add(abs);
821
+ if (!timer) {
822
+ timer = setTimeout(flush, debounceMs);
823
+ timer.unref?.();
824
+ }
825
+ };
826
+ const addWatcher = (dir, recursive) => {
827
+ const watcher = watchFn(dir, { recursive }, (_event, filename) => onEvent(dir, filename));
828
+ watcher.on("error", onWatcherError);
829
+ watcher.unref?.();
830
+ watchers.set(dir, watcher);
831
+ };
832
+ try {
833
+ addWatcher(rootDir, false);
834
+ for (const entry of readdirSync(rootDir, { withFileTypes: true })) {
835
+ if (!entry.isDirectory() || IGNORED_SEGMENTS.has(entry.name)) continue;
836
+ addWatcher(join(rootDir, entry.name), true);
837
+ }
838
+ } catch (err) {
839
+ closeAll();
840
+ console.warn(`[animus-extract] Turbopack dev watcher unavailable (${String(err)}); source edits require a dev-server restart`);
841
+ return null;
842
+ }
843
+ return { close: closeAll };
844
+ }
845
+ //#endregion
671
846
  //#region src/with-animus.ts
672
847
  const __dirname = dirname(fileURLToPath(import.meta.url));
673
848
  let warnedGitignore = false;
849
+ let warnedUnstableTurbopack = false;
674
850
  /**
675
851
  * Wrap a Next.js config to enable Animus static CSS extraction.
676
852
  *
@@ -682,16 +858,30 @@ let warnedGitignore = false;
682
858
  */
683
859
  function withAnimus(options) {
684
860
  if (!options.system) throw new Error("[animus-extract] Missing required option `system`. Provide the path to your SystemInstance module: withAnimus({ system: \"./src/ds.ts\" })");
861
+ if (options.unstable_turbopack && !options.turbopack && !warnedUnstableTurbopack) {
862
+ warnedUnstableTurbopack = true;
863
+ console.warn("[animus-extract] `unstable_turbopack` is deprecated — rename it to `turbopack` (same shape)");
864
+ }
685
865
  return (nextConfig) => {
866
+ if (resolveTurbopackMode(options)) return wireTurbopack(nextConfig, options);
686
867
  const existingWebpack = nextConfig.webpack;
687
868
  return {
688
869
  ...nextConfig,
689
870
  webpack(config, context) {
871
+ if (typeof existingWebpack === "function") config = existingWebpack(config, context);
690
872
  const rootDir = process.cwd();
691
873
  const animusDir = join(rootDir, ".animus");
692
874
  if (!existsSync(animusDir)) mkdirSync(animusDir, { recursive: true });
693
875
  const stubCssPath = join(animusDir, "styles.css");
694
- if (!existsSync(stubCssPath)) writeFileSync(stubCssPath, "@layer anm-global, anm-base, anm-variants, anm-compounds, anm-states, anm-system, anm-custom;\n");
876
+ if (!existsSync(stubCssPath)) {
877
+ const { declaration } = assembleStylesheet({
878
+ layers: options.layers,
879
+ variableCss: "",
880
+ globalCss: "",
881
+ split: true
882
+ });
883
+ writeFileSync(stubCssPath, declaration);
884
+ }
695
885
  if (!warnedGitignore) {
696
886
  warnedGitignore = true;
697
887
  try {
@@ -701,19 +891,13 @@ function withAnimus(options) {
701
891
  }
702
892
  } catch {}
703
893
  }
704
- const plugin = new AnimusWebpackPlugin({
705
- system: options.system,
706
- exclude: options.exclude,
707
- strict: options.strict,
708
- verbose: options.verbose,
709
- prefix: options.prefix,
710
- engine: options.engine
711
- });
894
+ const plugin = new AnimusWebpackPlugin(options);
895
+ const isExternalPackageFile = (filePath) => plugin.getExternalPackageDirs().some((dir) => filePath.startsWith(dir + sep) || filePath === dir);
712
896
  config.plugins = config.plugins || [];
713
897
  config.plugins.push(plugin);
714
898
  config.resolve = config.resolve || {};
715
899
  config.resolve.alias = config.resolve.alias || {};
716
- config.resolve.alias[".animus/styles.css"] = join(rootDir, ".animus", "styles.css");
900
+ config.resolve.alias[ANIMUS_CSS_MODULE_ID] = join(rootDir, ".animus", "styles.css");
717
901
  const systemPropsPath = join(rootDir, ".animus", "system-props.js");
718
902
  config.plugins.push({ apply(compiler) {
719
903
  compiler.hooks.normalModuleFactory.tap("AnimusVirtualResolve", (nmf) => {
@@ -732,24 +916,62 @@ function withAnimus(options) {
732
916
  config.module.rules.push({
733
917
  test: (filePath) => {
734
918
  if (/\.[jt]sx?$/.test(filePath)) return true;
735
- if (/\.mjs$/.test(filePath)) return plugin.getExternalPackageDirs().some((dir) => filePath.startsWith(dir + sep) || filePath === dir);
736
- return false;
919
+ return /\.mjs$/.test(filePath) && isExternalPackageFile(filePath);
737
920
  },
738
921
  exclude: (filePath) => {
739
922
  if (!filePath.includes("node_modules")) return false;
740
- return !plugin.getExternalPackageDirs().some((dir) => filePath.startsWith(dir + sep) || filePath === dir);
923
+ return !isExternalPackageFile(filePath);
741
924
  },
742
925
  enforce: "pre",
743
926
  use: [{
744
927
  loader: actualLoaderPath,
745
- options: { strict: options.strict }
928
+ options: {
929
+ strict: options.strict,
930
+ cssImportTarget: options.cssImportTarget
931
+ }
746
932
  }]
747
933
  });
748
- if (typeof existingWebpack === "function") return existingWebpack(config, context);
749
934
  return config;
750
935
  }
751
936
  };
752
937
  };
753
938
  }
939
+ /**
940
+ * Turbopack wiring: run the full extraction now (artifacts on disk before
941
+ * bundling), start the dev watcher, and merge the generated rules/aliases
942
+ * into `nextConfig.turbopack`. Consumer-managed rules for the same glob are
943
+ * a hard error — silently stacking loaders would be undebuggable.
944
+ */
945
+ async function wireTurbopack(nextConfig, options) {
946
+ const rootDir = process.cwd();
947
+ const session = new ExtractionSession(options);
948
+ session.rootDir = rootDir;
949
+ const builtAliases = buildPathAliasesJson(readTsconfigAliasPairs(rootDir), rootDir);
950
+ if (builtAliases) session.pathAliasesJson = builtAliases.json;
951
+ await runTurbopackPipeline(session);
952
+ if (process.env.NODE_ENV === "development") startTurbopackWatcher(session, rootDir);
953
+ const fragment = buildTurbopackConfig({
954
+ rootDir,
955
+ loaderPath: resolveTurbopackLoaderPath(__dirname),
956
+ options,
957
+ externalSourceEntries: session.externalSourceEntries
958
+ });
959
+ const existing = nextConfig.turbopack ?? {};
960
+ if (existing.rules && "*.{ts,tsx,js,jsx,mjs}" in existing.rules) throw new Error(`[animus-extract] turbopack.rules['${ANIMUS_TURBOPACK_RULE_GLOB}'] is already configured — remove the consumer rule or disable unstable_turbopack`);
961
+ return {
962
+ ...nextConfig,
963
+ turbopack: {
964
+ ...existing,
965
+ rules: {
966
+ ...existing.rules,
967
+ ...fragment.rules
968
+ },
969
+ resolveAlias: {
970
+ ...existing.resolveAlias,
971
+ ...fragment.resolveAlias
972
+ }
973
+ }
974
+ };
975
+ }
754
976
  //#endregion
755
977
  export { withAnimus };