@animus-ui/next-plugin 0.1.8 → 0.1.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.
package/dist/index.mjs CHANGED
@@ -1,1328 +1,8 @@
1
- import { S as __require, _ as replacementEpochPath, a as REPLACEMENT_EPOCH_ARTIFACT, b as stylesPath, c as SYSTEM_PROPS_ARTIFACT, f as envelopeCssArtifact, g as readJsonEnvelope, h as readCssEnvelope, i as MANIFEST_ARTIFACT, l as analysisCommitPath, n as ANALYSIS_INPUTS_ARTIFACT, o as SESSION_ASSETS_DIR, p as envelopeJsonArtifact, r as ANALYSIS_STATUS_ARTIFACT, s as STYLES_ARTIFACT, t as ANALYSIS_COMMIT_ARTIFACT, v as sessionArtifactDir, x as systemPropsPath, y as sessionsRootDir } from "./session-paths-DfYIPDcM.mjs";
2
- import { C as setWatchTransaction, S as setSharedSystemProps, _ as setSessionArtifactDir, b as setSharedExternalDirs, c as getSharedCss, d as getWatchTransaction, f as resetAnalysisPromise, g as setReplacementEpoch, h as setManifestJson, l as getSharedExternalDirs, m as setAnalyzedHashes, n as engineApi, o as getReplacementEpoch, p as setAnalysisPromise, r as getAnalysisPromise, t as claimProcessSessionId, u as getSharedExternalEntries, v as setSharedCss, x as setSharedExternalEntries, y as setSharedEngine } from "./singleton-372wiSRr.mjs";
3
- import { DEFAULT_EXTENSIONS, assembleStylesheet, assertNoRetiredEngineSelection, buildPathAliasesJson, buildSystemPropsModule, clearEngineCache, collectExternalPackageSources, contentHash, createSourceIdentity, discoverFiles, enforceExternalTokenContracts, excludeCollectedPackages, extractSystemFilePackages, findAssetSpecifiers, findPackageRoot, firstOwners, formatRustTimingWaterfall, hashReplacementPlans, isExcludedPackageRelativePath, isPathWithinRoot, loadSystemConfig, mergeExternalKeyframes, postProcessCss, preprocessMdx, readTsconfigAliasPairs, resolveAssetFile, resolveLightningTargets, runProjectAnalysis, serializeStaticCss, sharesVolumeRoot, snapshotFilePlans, staleDistIncludesMessage, substituteAssetPlaceholders, toWatchKeys, unresolvableIncludesMessage, walkPackageSources } from "@animus-ui/extract/pipeline";
4
- import { existsSync, mkdirSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, statSync, unlinkSync, watch, writeFileSync } from "fs";
5
- import { basename, dirname, extname, join, relative, resolve } from "path";
1
+ import { ENGINE_TRANSFORM_EXTENSIONS, assembleStylesheet, assertKnownOptionKeys, assertNoRetiredEngineSelection, buildPathAliasesJson, isPathWithinRoot, readTsconfigAliasPairs, resolveMode } from "@animus-ui/extract/pipeline";
2
+ import { ANIMUS_CSS_MODULE_ID, ANIMUS_CSS_MODULE_ID as ANIMUS_CSS_MODULE_ID$1, ExtractionSession, STYLES_ARTIFACT, SYSTEM_PROPS_ARTIFACT, TURBOPACK_SYSTEM_PROPS_ID, getAnalysisPromise, getReplacementEpoch, getSharedCss, getSharedExternalDirs, getSharedExternalEntries, replacementEpochPath, runSessionPipeline, sessionArtifactDir, setAnalysisPromise, setSharedEngine, startTurbopackWatcher, stylesPath, systemPropsPath } from "@animus-ui/extract/session";
3
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "fs";
4
+ import { dirname, join, relative, resolve } from "path";
6
5
  import { fileURLToPath } from "url";
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;
45
- }
46
- //#endregion
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)}`);
87
- }
88
- }
89
- //#endregion
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
- /** Retention window for sibling session directories (design D2). */
98
- const SESSION_DIR_MAX_AGE_MS = 1440 * 60 * 1e3;
99
- /** Watchdog added to the debounce ceiling for status deadlines (D3). */
100
- const STATUS_WATCHDOG_MS = 2e3;
101
- /** Flat legacy `.animus/` artifacts removed at session start — unreachable
102
- * by session-scoped loaders and no longer written by anyone. */
103
- const LEGACY_FLAT_ARTIFACTS = [
104
- MANIFEST_ARTIFACT,
105
- ANALYSIS_INPUTS_ARTIFACT,
106
- STYLES_ARTIFACT,
107
- SYSTEM_PROPS_ARTIFACT,
108
- REPLACEMENT_EPOCH_ARTIFACT,
109
- ANALYSIS_COMMIT_ARTIFACT,
110
- ANALYSIS_STATUS_ARTIFACT
111
- ];
112
- /** Default path fragments excluded from source discovery (full + watch). */
113
- const DEFAULT_EXCLUDE = [
114
- "node_modules",
115
- "dist",
116
- ".test.",
117
- ".spec.",
118
- ".next",
119
- ".animus"
120
- ];
121
- /**
122
- * Bundler-agnostic extraction pipeline: system loading, source discovery
123
- * and ingestion, external-package collection, analysis, stylesheet and
124
- * system-props emission, and watch-cycle diffing.
125
- *
126
- * The webpack adapter (plugin.ts) owns only bundler wiring: hook
127
- * registration, alias harvesting from the compiler config, in-memory asset
128
- * replacement, and translating watch events into `handleWatchUpdate`
129
- * change sets. Keeping this class free of webpack types is deliberate — a
130
- * future Turbopack integration must drive the same session from outside
131
- * the bundler (Turbopack has no compiler-hook surface), reusing everything
132
- * here unchanged.
133
- *
134
- * Outputs are published through the package singleton (shared CSS,
135
- * manifest, system props) and written to `.animus/` on disk.
136
- */
137
- var ExtractionSession = class {
138
- /** Set by the adapter before any pipeline run. */
139
- rootDir = null;
140
- /** Serialized path aliases, harvested by the adapter from bundler config. */
141
- pathAliasesJson = null;
142
- assetCopyCache = /* @__PURE__ */ new Map();
143
- /** Physical asset files registered with the host watcher. */
144
- assetDependencyPaths = /* @__PURE__ */ new Set();
145
- assetDependencyKeys = /* @__PURE__ */ new Set();
146
- /** Emitter identity override for the system-props module id. Webpack mode
147
- * (null) injects the absolute `.animus/system-props.js` path, resolved by
148
- * NormalModuleReplacement; Turbopack rejects absolute-path imports, so
149
- * its driver sets the virtual id that `resolveAlias` maps to disk. */
150
- systemPropsModuleId = null;
151
- /** Whether the analysis-inputs hydration corpus is serialized + written.
152
- * False (webpack mode): the loader shares the pipeline process and reads
153
- * the manifest from memory — the corpus is never persisted. True is set
154
- * by the Turbopack orchestration driver, whose isolated loader workers
155
- * replay it (spec: next-turbopack-integration, "Manifest disk artifact" /
156
- * "Webpack mode skips the hydration corpus"). */
157
- persistAnalysisInputs = false;
158
- /** Absolute directory prefixes for external DS packages (loader allowlisting). */
159
- externalPackageDirs = [];
160
- /** Absolute package dir → owning specifier (cross-source correlation). */
161
- externalDirOwners = {};
162
- /** rootDir-relative external file → owning specifier (correlation join). */
163
- externalFileOwners = {};
164
- /** External package specifier → absolute source entry path. */
165
- externalSourceEntries = /* @__PURE__ */ new Map();
166
- /** SourceId derivation authority for the current generation (openspec:
167
- * external-source-watch-ingestion, design D2) — canonical roots
168
- * realpath'd once per full pipeline; alias→SourceId associations
169
- * recorded while files exist so deletion resolves through the cache. */
170
- sourceIdentity = null;
171
- /** Canonical admitted external root → declared specifiers (set-valued
172
- * ownership, design D2; duplicate specifiers resolving to one canonical
173
- * root share it). Engine watch wiring and tests read this. */
174
- externalRootOwners = /* @__PURE__ */ new Map();
175
- /** Canonical admitted external watch roots — the engine-side watch
176
- * surface (webpack contextDependencies / Turbopack watchers). */
177
- externalWatchRoots = [];
178
- /** Canonical external root → (raw sourceKey → {raw content hash, recorded
179
- * abs spelling}): the previous-generation inventory a dirty-root rewalk
180
- * diffs against (design D3). Raw hashes — MDX preprocessing never skews
181
- * the diff; the recorded abs path is a registered deletion alias, so a
182
- * reconstructed deletion always resolves through cached identity. */
183
- externalInventory = /* @__PURE__ */ new Map();
184
- /** Sticky diagnostics (design D5/D7): stable key → message, re-surfaced
185
- * on every full pipeline until the underlying condition clears. */
186
- stickyDiagnostics = /* @__PURE__ */ new Map();
187
- /** Volume-membership predicate for the cross-volume gate (design D5).
188
- * Injected seam: the shared predicate only discriminates on Windows
189
- * (win32 semantics are unit-tested via path.win32), so runtime tests
190
- * drive the gate through this. */
191
- sharesProjectVolume = sharesVolumeRoot;
192
- /** Orchestrator seams (openspec: external-source-watch-ingestion, design
193
- * D4). `onExternalRootResolved` fires per volume-admitted external root
194
- * DURING collection — after resolution, BEFORE that root's sources are
195
- * walked — so a watching host can open its handle with no blind gap
196
- * between scan and watch. `onExternalRootsCommitted` fires once after a
197
- * successful full-pipeline publication with the complete admitted
198
- * canonical root set (the host's promote/replay/close-old phase; a
199
- * failed pipeline never fires it, so the host rolls back). */
200
- onExternalRootResolved = null;
201
- onExternalRootsCommitted = null;
202
- options;
203
- staticCssJson;
204
- system = null;
205
- /** Discovery-time keyframes diagnostics awaiting the shared surfacing pass. */
206
- externalKeyframesDiagnostics = [];
207
- /** Full package-resolution map from the last full pipeline — replayed by
208
- * incremental passes (sourceEntries alone omits dist-resolved packages). */
209
- lastPackageMap = {};
210
- fileCache = /* @__PURE__ */ new Map();
211
- systemDependencyKeys = /* @__PURE__ */ new Set();
212
- /** Loader-reported dependency paths for bundler watch registration. */
213
- systemDependencyPaths = [];
214
- systemDependencyHashes = /* @__PURE__ */ new Map();
215
- lastSystemPropsHash = null;
216
- /** Per-payload write guards: payloadHash gates rewrites (byte-identical
217
- * payloads leave disk untouched); diskHash is the hash of the CURRENT
218
- * disk bytes (envelope included) recorded in the analysis-commit. null =
219
- * not yet seeded (first publication reads the artifact's envelope so a
220
- * same-session restart never rewrites byte-identical artifacts). */
221
- artifactRecords = {
222
- manifest: null,
223
- inputs: null,
224
- styles: null
225
- };
226
- /** Last written analysis-commit; null = seeded from disk on first use. */
227
- lastCommit = null;
228
- /** Session identity — claimed once per PROCESS (one Next invocation),
229
- * adopted by every subsequent session instance so all compilers share
230
- * one artifact tree (design D2: `next dev`/`next build` co-writing are
231
- * separate processes and therefore separate sessions). */
232
- sessionId = claimProcessSessionId();
233
- /** Epoch value of the last published analysis; null = not yet known
234
- * (seeded from the session dir's artifact on first publication so a
235
- * same-session restart with unchanged plans never rewrites bytes). */
236
- lastEpochValue = null;
237
- /** Watcher debounce ceiling feeding status deadlines (design D3). */
238
- debounceCeilingMs = 75;
239
- /** Test seam: observes every session-artifact write (name, content)
240
- * post-rename — write ORDER is part of the transaction contract. */
241
- onArtifactWrite = null;
242
- /** Status attempt bookkeeping (design D3). */
243
- statusAttemptId = 0;
244
- statusAttemptOpen = false;
245
- /** Debounce-window observations pending analysis (sourceKey → hash). */
246
- debouncePending = /* @__PURE__ */ new Map();
247
- /** Session-start hygiene (pruning + legacy cleanup) runs once. */
248
- sessionStartHygieneDone = false;
249
- lcssTargets = null;
250
- constructor(options) {
251
- this.options = options;
252
- this.staticCssJson = serializeStaticCss(options.staticCss);
253
- }
254
- /** This session's artifact directory. Requires `rootDir` to be set. */
255
- get sessionDir() {
256
- return sessionArtifactDir(this.rootDir, this.sessionId);
257
- }
258
- get verbose() {
259
- return this.options.verbose === true || process.env.ANIMUS_DEBUG === "1" || process.env.ANIMUS_DEBUG === "true";
260
- }
261
- log(msg) {
262
- if (this.verbose) console.info(`[animus] ${msg}`);
263
- }
264
- warn(msg) {
265
- console.warn(`[animus] ${msg}`);
266
- }
267
- now() {
268
- return this.verbose ? performance.now() : 0;
269
- }
270
- elapsed(t) {
271
- return this.verbose ? Math.round(performance.now() - t) : 0;
272
- }
273
- /** Lazily-computed scan config (options are constructor-fixed, so the
274
- * derivation is stable for the session's lifetime). */
275
- scanConfigMemo = null;
276
- /** Resolve the scan configuration from options — the single source of the
277
- * exclude/extension policy shared by the full and incremental pipelines. */
278
- resolveScanConfig() {
279
- if (this.scanConfigMemo === null) {
280
- const extensionsSet = new Set(this.options.extensions ?? DEFAULT_EXTENSIONS);
281
- this.scanConfigMemo = {
282
- excludePatterns: this.options.exclude ?? DEFAULT_EXCLUDE,
283
- extensionsSet,
284
- shouldHandleMdx: extensionsSet.has(".mdx")
285
- };
286
- }
287
- return this.scanConfigMemo;
288
- }
289
- /**
290
- * Watch entry point: one single-flight analysis transaction per event
291
- * batch (openspec: next-webpack-served-transform-coherence, design D3).
292
- * The first entering session runs the transaction; every concurrent
293
- * entry — same session re-entered, or another compiler's session
294
- * (client/server/RSC each hold their own instance) — joins the in-flight
295
- * promise, so no compiler proceeds against a generation older than the
296
- * one the transaction publishes. A rejected transaction rejects every
297
- * joiner; the gate always clears.
298
- */
299
- async handleWatchUpdate(changes) {
300
- const inflight = getWatchTransaction();
301
- if (inflight) {
302
- await inflight;
303
- return;
304
- }
305
- if (!this.system) return;
306
- const transaction = this.processWatchUpdate(changes);
307
- setWatchTransaction(transaction);
308
- try {
309
- await transaction;
310
- } finally {
311
- setWatchTransaction(null);
312
- }
313
- }
314
- /**
315
- * Incremental watch pass: geological reset when the system file changed,
316
- * otherwise content-hash diffing restricted to the watcher's change sets
317
- * (falling back to a full discovery walk when no sets are provided).
318
- */
319
- async processWatchUpdate(changes) {
320
- const rootDir = this.rootDir;
321
- try {
322
- changes = this.reconcileExternalRoots(changes);
323
- } catch (err) {
324
- this.warn(`external root reconciliation failed: ${String(err)}`);
325
- }
326
- const changed = [...changes.modifiedFiles ?? [], ...changes.removedFiles ?? []];
327
- let assetChanged = false;
328
- try {
329
- let systemHit;
330
- if (!changes.modifiedFiles && !changes.removedFiles) for (const [dep, hash] of this.systemDependencyHashes) {
331
- let current = "";
332
- try {
333
- current = contentHash(readFileSync(dep, "utf-8"));
334
- } catch {}
335
- if (current !== hash) {
336
- systemHit = dep;
337
- break;
338
- }
339
- }
340
- else systemHit = changed.find((path) => toWatchKeys(path).some((key) => this.systemDependencyKeys.has(key)));
341
- if (systemHit) {
342
- this.log(`geological reset: system dependency changed (${relative(rootDir, systemHit)})`);
343
- this.resetForHmr();
344
- const promise = this.runFullPipeline(this.pendingFromBatch(changes));
345
- setAnalysisPromise(promise);
346
- await promise;
347
- return;
348
- }
349
- if (changed.some((path) => toWatchKeys(path).some((key) => this.assetDependencyKeys.has(key)))) {
350
- this.assetCopyCache.clear();
351
- assetChanged = true;
352
- }
353
- } catch (err) {
354
- this.warn(`HMR geological-reset check failed: ${String(err)}`);
355
- }
356
- const { excludePatterns, extensionsSet, shouldHandleMdx } = this.resolveScanConfig();
357
- const priorCacheEntries = /* @__PURE__ */ new Map();
358
- const recordPrior = (key) => {
359
- if (!priorCacheEntries.has(key)) priorCacheEntries.set(key, this.fileCache.get(key) ?? null);
360
- };
361
- const inventoryUpdates = [];
362
- let removedAny = false;
363
- if (changes.removedFiles) for (const removedPath of changes.removedFiles) {
364
- let key;
365
- let owningRoot = null;
366
- if (isPathWithinRoot(rootDir, removedPath)) key = relative(rootDir, removedPath);
367
- else {
368
- const resolved = this.sourceIdentity?.resolveDeletedSourceId(removedPath);
369
- if (!resolved) continue;
370
- key = resolved.sourceKey;
371
- owningRoot = resolved.owningRoot;
372
- }
373
- recordPrior(key);
374
- recordPrior(key + ".tsx");
375
- if (this.fileCache.delete(key) || this.fileCache.delete(key + ".tsx")) {
376
- removedAny = true;
377
- if (owningRoot) {
378
- inventoryUpdates.push({
379
- root: owningRoot,
380
- key,
381
- hash: null,
382
- abs: removedPath
383
- });
384
- delete this.externalFileOwners[key];
385
- delete this.externalFileOwners[key + ".tsx"];
386
- }
387
- }
388
- }
389
- let targets;
390
- if (changes.modifiedFiles) {
391
- targets = [];
392
- for (const modifiedPath of changes.modifiedFiles) {
393
- const classified = this.classifyWatchPath(modifiedPath, {
394
- excludePatterns,
395
- extensionsSet
396
- });
397
- if (classified) targets.push({
398
- abs: modifiedPath,
399
- ...classified
400
- });
401
- }
402
- } else targets = discoverFiles(rootDir, rootDir, excludePatterns, extensionsSet).map((abs) => ({
403
- abs,
404
- key: relative(rootDir, abs),
405
- owningRoot: null
406
- }));
407
- const changedPaths = [];
408
- for (const target of targets) {
409
- let relPath = target.key;
410
- let source;
411
- try {
412
- source = readFileSync(target.abs, "utf-8");
413
- } catch {
414
- continue;
415
- }
416
- const rawHash = contentHash(source);
417
- if (shouldHandleMdx && extname(target.abs) === ".mdx") {
418
- const processed = await this.preprocessMdxEntry(source, relPath, { warn: false });
419
- if (!processed) continue;
420
- source = processed.source;
421
- relPath = processed.relPath;
422
- }
423
- const cached = this.fileCache.get(relPath);
424
- const hash = relPath === target.key ? rawHash : contentHash(source);
425
- if (!cached || cached.hash !== hash) {
426
- changedPaths.push(relPath);
427
- recordPrior(relPath);
428
- this.fileCache.set(relPath, {
429
- hash,
430
- source
431
- });
432
- if (target.owningRoot) {
433
- const owner = this.externalRootOwners.get(target.owningRoot)?.values().next().value;
434
- if (owner !== void 0) this.externalFileOwners[relPath] ??= owner;
435
- inventoryUpdates.push({
436
- root: target.owningRoot,
437
- key: target.key,
438
- hash: rawHash,
439
- abs: target.abs
440
- });
441
- }
442
- }
443
- }
444
- if (changedPaths.length > 0 || removedAny || assetChanged) {
445
- const fileEntries = this.buildFileEntriesFromCache();
446
- const pending = changedPaths.map((rel) => [rel, this.fileCache.get(rel).hash]);
447
- resetAnalysisPromise();
448
- const promise = this.runIncrementalPipeline(fileEntries, pending);
449
- setAnalysisPromise(promise);
450
- try {
451
- await promise;
452
- } catch (err) {
453
- for (const [key, prior] of priorCacheEntries) if (prior === null) this.fileCache.delete(key);
454
- else this.fileCache.set(key, prior);
455
- throw err;
456
- }
457
- for (const update of inventoryUpdates) {
458
- let inventory = this.externalInventory.get(update.root);
459
- if (!inventory) {
460
- inventory = /* @__PURE__ */ new Map();
461
- this.externalInventory.set(update.root, inventory);
462
- }
463
- if (update.hash === null) inventory.delete(update.key);
464
- else inventory.set(update.key, {
465
- hash: update.hash,
466
- abs: update.abs
467
- });
468
- }
469
- } else if (this.statusAttemptOpen) {
470
- this.debouncePending.clear();
471
- this.writeAnalysisStatus("idle", []);
472
- }
473
- }
474
- /**
475
- * Preprocess one `.mdx` entry into scanner-consumable tsx. Returns the
476
- * rewritten source plus the `relPath + '.tsx'` path on success, or null
477
- * when the file must be skipped.
478
- *
479
- * `warn: false` (incremental watch pass) skips silently — the full
480
- * pipeline already surfaced the warning. `warn: true` (full pipeline)
481
- * warns ONCE for a missing @mdx-js/mdx dependency via the shared
482
- * `missingDepFlag` holder, and every time for a preprocessing error.
483
- */
484
- async preprocessMdxEntry(source, relPath, opts) {
485
- const result = await preprocessMdx(source, relPath);
486
- if (result.kind === "missing-dep") {
487
- if (opts.warn && opts.missingDepFlag && !opts.missingDepFlag.warned) {
488
- console.warn("[animus] ⚠ .mdx in extensions but @mdx-js/mdx not installed; MDX files skipped");
489
- opts.missingDepFlag.warned = true;
490
- }
491
- return null;
492
- }
493
- if (result.kind === "error") {
494
- if (opts.warn) console.warn(`[animus] ⚠ MDX preprocessing failed for ${relPath}: ${result.error}`);
495
- return null;
496
- }
497
- return {
498
- source: result.source,
499
- relPath: relPath + ".tsx"
500
- };
501
- }
502
- async runFullPipeline(pending = []) {
503
- const pipelineStart = this.now();
504
- const bt = {};
505
- this.runSessionStartHygiene();
506
- setSessionArtifactDir(this.sessionDir);
507
- clearEngineCache(engineApi);
508
- const rootDir = this.rootDir;
509
- const resolvedSystemPath = resolve(rootDir, this.options.system);
510
- let t = this.now();
511
- this.system = loadSystemConfig(engineApi, {
512
- systemPath: resolvedSystemPath,
513
- rootDir,
514
- prefix: this.options.prefix
515
- });
516
- this.assetCopyCache.clear();
517
- this.assetDependencyPaths.clear();
518
- this.assetDependencyKeys.clear();
519
- {
520
- const deps = this.system.dependencies ?? [];
521
- const keys = /* @__PURE__ */ new Set();
522
- for (const key of toWatchKeys(resolvedSystemPath)) keys.add(key);
523
- for (const dep of deps) for (const key of toWatchKeys(dep)) keys.add(key);
524
- this.systemDependencyKeys = keys;
525
- this.systemDependencyPaths = deps;
526
- const hashes = /* @__PURE__ */ new Map();
527
- for (const dep of deps.length > 0 ? deps : [resolvedSystemPath]) try {
528
- hashes.set(dep, contentHash(readFileSync(dep, "utf-8")));
529
- } catch {
530
- hashes.set(dep, "");
531
- }
532
- this.systemDependencyHashes = hashes;
533
- }
534
- bt.systemLoad = this.elapsed(t);
535
- t = this.now();
536
- const { excludePatterns, extensionsSet, shouldHandleMdx } = this.resolveScanConfig();
537
- const missingDepFlag = { warned: false };
538
- const files = discoverFiles(rootDir, rootDir, excludePatterns, extensionsSet);
539
- bt.fileDiscovery = this.elapsed(t);
540
- t = this.now();
541
- const fileEntries = [];
542
- for (const filePath of files) {
543
- let source = readFileSync(filePath, "utf-8");
544
- let relPath = relative(rootDir, filePath);
545
- if (shouldHandleMdx && extname(filePath) === ".mdx") {
546
- const processed = await this.preprocessMdxEntry(source, relPath, {
547
- warn: true,
548
- missingDepFlag
549
- });
550
- if (!processed) continue;
551
- source = processed.source;
552
- relPath = processed.relPath;
553
- }
554
- const hash = contentHash(source);
555
- this.fileCache.set(relPath, {
556
- hash,
557
- source
558
- });
559
- fileEntries.push({
560
- path: relPath,
561
- source,
562
- hash
563
- });
564
- }
565
- bt.fileRead = this.elapsed(t);
566
- bt.fileCount = fileEntries.length;
567
- t = this.now();
568
- const packageNames = extractSystemFilePackages(resolvedSystemPath);
569
- const preResolved = resolvePackagesByName(rootDir, packageNames);
570
- const rawExternalFiles = /* @__PURE__ */ new Map();
571
- const collected = await collectExternalPackageSources({
572
- specifiers: packageNames,
573
- resolveSpecifier: (name) => preResolved[name] ? resolve(rootDir, preResolved[name]) : null,
574
- rootDir,
575
- extensionsSet,
576
- hasEntry: (relPath) => fileEntries.some((e) => e.path === relPath),
577
- preprocessFile: async (source, relPath, absPath) => {
578
- rawExternalFiles.set(absPath, contentHash(source));
579
- if (shouldHandleMdx && extname(absPath) === ".mdx") return this.preprocessMdxEntry(source, relPath, {
580
- warn: true,
581
- missingDepFlag
582
- });
583
- return {
584
- source,
585
- relPath
586
- };
587
- },
588
- onUnreadable: (relPath, err) => this.warn(`skipped unreadable package file ${relPath}: ${String(err)}`),
589
- onPackageResolved: (_specifier, packageDir) => {
590
- if (!this.onExternalRootResolved) return;
591
- if (!this.sharesProjectVolume(rootDir, packageDir)) return;
592
- let canonical = packageDir;
593
- try {
594
- canonical = realpathSync(packageDir);
595
- } catch {}
596
- this.onExternalRootResolved(canonical);
597
- }
598
- });
599
- for (const record of collected.outcomes) if (record.outcome === "empty") this.warn(`include '${record.specifier}' resolved but discovered no component sources`);
600
- const unresolvableMessage = unresolvableIncludesMessage(collected.outcomes);
601
- if (unresolvableMessage !== null) {
602
- if (this.options.strict) throw new Error(unresolvableMessage);
603
- this.warn(unresolvableMessage);
604
- }
605
- const staleDistMessage = staleDistIncludesMessage(collected.outcomes);
606
- if (staleDistMessage !== null) {
607
- if (this.options.strict) throw new Error(staleDistMessage);
608
- this.warn(staleDistMessage);
609
- }
610
- const rejectedSpecifiers = /* @__PURE__ */ new Set();
611
- const crossVolumeDetails = [];
612
- for (const [dir, specifiers] of Object.entries(collected.dirOwnerSets)) {
613
- if (this.sharesProjectVolume(rootDir, dir)) continue;
614
- for (const specifier of specifiers) rejectedSpecifiers.add(specifier);
615
- crossVolumeDetails.push(`${specifiers.join(", ")} → ${dir}`);
616
- }
617
- this.stickyDiagnostics.delete("cross-volume");
618
- if (rejectedSpecifiers.size > 0) {
619
- const message = `ANIMUS_EXTERNAL_CROSS_VOLUME_UNSUPPORTED: external package source root(s) on a different volume than the project root (${rootDir}): ${crossVolumeDetails.join("; ")} — cross-volume workspace sources are unsupported; the package(s) are excluded from extraction and watching`;
620
- if (this.options.strict) throw new Error(`[animus-next] ${message}`);
621
- this.stickyDiagnostics.set("cross-volume", message);
622
- }
623
- for (const message of this.stickyDiagnostics.values()) this.warn(message);
624
- const admitted = excludeCollectedPackages(collected, rejectedSpecifiers, rootDir);
625
- const identity = createSourceIdentity(rootDir);
626
- this.externalRootOwners = /* @__PURE__ */ new Map();
627
- for (const [dir, specifiers] of Object.entries(admitted.dirOwnerSets)) {
628
- const canonical = identity.registerExternalRoot(dir);
629
- const owners = this.externalRootOwners.get(canonical) ?? /* @__PURE__ */ new Set();
630
- for (const specifier of specifiers) owners.add(specifier);
631
- this.externalRootOwners.set(canonical, owners);
632
- }
633
- this.sourceIdentity = identity;
634
- this.externalWatchRoots = identity.externalRoots();
635
- this.externalInventory = /* @__PURE__ */ new Map();
636
- for (const [absPath, rawHash] of rawExternalFiles) {
637
- const resolved = identity.resolveSourceId(absPath);
638
- if (!resolved?.owningRoot) continue;
639
- let inventory = this.externalInventory.get(resolved.owningRoot);
640
- if (!inventory) {
641
- inventory = /* @__PURE__ */ new Map();
642
- this.externalInventory.set(resolved.owningRoot, inventory);
643
- }
644
- inventory.set(resolved.sourceKey, {
645
- hash: rawHash,
646
- abs: absPath
647
- });
648
- }
649
- const packageMap = admitted.packageMap;
650
- this.lastPackageMap = packageMap;
651
- this.externalDirOwners = firstOwners(admitted.dirOwnerSets);
652
- this.externalFileOwners = admitted.fileOwners;
653
- this.externalSourceEntries = admitted.sourceEntries;
654
- for (const entry of admitted.entries) {
655
- const hash = contentHash(entry.source);
656
- this.fileCache.set(entry.path, {
657
- hash,
658
- source: entry.source
659
- });
660
- fileEntries.push({
661
- path: entry.path,
662
- source: entry.source,
663
- hash
664
- });
665
- }
666
- this.externalPackageDirs = admitted.packageDirs;
667
- setSharedExternalDirs(admitted.packageDirs);
668
- setSharedExternalEntries(admitted.sourceEntries);
669
- if (this.system && admitted.keyframesScanEntries.size > 0) {
670
- const api = engineApi();
671
- const merge = mergeExternalKeyframes((entry, root) => api.scanKeyframesExports(entry, root), this.system.keyframesJson, admitted.keyframesScanEntries.values(), this.rootDir);
672
- this.system.keyframesJson = merge.keyframesJson;
673
- this.externalKeyframesDiagnostics = merge.diagnostics;
674
- }
675
- bt.packageResolve = this.elapsed(t);
676
- const universe = new Set(fileEntries.map((entry) => entry.path));
677
- for (const key of [...this.fileCache.keys()]) if (!universe.has(key)) this.fileCache.delete(key);
678
- await this.analyzeAndEmit(fileEntries, packageMap, false, bt, pipelineStart, pending);
679
- this.onExternalRootsCommitted?.(this.externalWatchRoots);
680
- }
681
- /**
682
- * Reset analysis state for HMR geological reset. Payload write guards go
683
- * back to null so the next publication reseeds them from the disk
684
- * envelopes — a byte-identical post-reset artifact is still not
685
- * rewritten.
686
- */
687
- resetForHmr() {
688
- resetAnalysisPromise();
689
- this.artifactRecords = {
690
- manifest: null,
691
- inputs: null,
692
- styles: null
693
- };
694
- this.lastSystemPropsHash = null;
695
- clearEngineCache(engineApi);
696
- }
697
- /**
698
- * The (sourceKey, observedSourceHash) pairs of a watch batch — cheap
699
- * evidence for the status file's pending set on the geological-reset
700
- * path, where the batch's component edits ride along with the system
701
- * edit (design D3: loaders wait only on observed inputs).
702
- */
703
- pendingFromBatch(changes) {
704
- const { excludePatterns, extensionsSet } = this.resolveScanConfig();
705
- const pending = [];
706
- for (const path of changes.modifiedFiles ?? []) {
707
- const classified = this.classifyWatchPath(path, {
708
- excludePatterns,
709
- extensionsSet
710
- });
711
- if (!classified) continue;
712
- try {
713
- pending.push([classified.key, contentHash(readFileSync(path, "utf-8"))]);
714
- } catch {}
715
- }
716
- return pending;
717
- }
718
- /**
719
- * Root-dirty inventory reconciliation (design D3): partition the
720
- * watcher's change sets into explicit FILE events and external ROOT hits
721
- * (a reported path that IS an admitted root, or a directory inside one),
722
- * rewalk each dirty root through the shared discovery policy, diff the
723
- * SourceId+raw-hash inventory against the previous generation, and merge
724
- * the reconstructed created/edited/deleted deltas with the explicit
725
- * events (identity-level dedup happens downstream at the cache gate).
726
- * Deletion falls out of the inventory diff — webpack may report only the
727
- * directory (probe-proven).
728
- */
729
- reconcileExternalRoots(changes) {
730
- const identity = this.sourceIdentity;
731
- if (!identity) return changes;
732
- if (!changes.modifiedFiles && !changes.removedFiles) return changes;
733
- if (this.externalWatchRoots.length === 0) return changes;
734
- const { extensionsSet } = this.resolveScanConfig();
735
- const dirtyRoots = /* @__PURE__ */ new Set();
736
- const modified = /* @__PURE__ */ new Set();
737
- const removed = /* @__PURE__ */ new Set();
738
- const rootHitFor = (path) => {
739
- const containing = identity.containingExternalRoot(path);
740
- if (!containing) return null;
741
- try {
742
- return statSync(path).isDirectory() ? containing : null;
743
- } catch {
744
- return identity.resolveDeletedSourceId(path) ? null : containing;
745
- }
746
- };
747
- for (const path of changes.modifiedFiles ?? []) {
748
- const root = rootHitFor(path);
749
- if (root) dirtyRoots.add(root);
750
- else modified.add(path);
751
- }
752
- for (const path of changes.removedFiles ?? []) {
753
- const root = rootHitFor(path);
754
- if (root) dirtyRoots.add(root);
755
- else removed.add(path);
756
- }
757
- for (const root of dirtyRoots) {
758
- const previous = this.externalInventory.get(root) ?? /* @__PURE__ */ new Map();
759
- const seen = /* @__PURE__ */ new Set();
760
- const walked = walkPackageSources(root, extensionsSet);
761
- for (const abs of walked) {
762
- const resolved = identity.resolveSourceId(abs);
763
- if (!resolved || resolved.owningRoot !== root) continue;
764
- seen.add(resolved.sourceKey);
765
- let rawHash;
766
- try {
767
- rawHash = contentHash(readFileSync(abs, "utf-8"));
768
- } catch {
769
- continue;
770
- }
771
- if (previous.get(resolved.sourceKey)?.hash !== rawHash) modified.add(abs);
772
- }
773
- for (const [key, entry] of previous) if (!seen.has(key)) removed.add(entry.abs);
774
- }
775
- return {
776
- modifiedFiles: modified,
777
- removedFiles: removed
778
- };
779
- }
780
- /**
781
- * Route one watcher-reported path (design D1/D2): a project-root member
782
- * (lexical containment — existing local semantics preserved; consumer
783
- * exclude patterns apply) or an admitted external member (identity
784
- * resolution with symlink-escape rejection; package-relative excludes
785
- * mirror the collection walk's filters — guardrail G1, one policy).
786
- * Returns null for dropped paths.
787
- */
788
- classifyWatchPath(absPath, scan) {
789
- if (!scan.extensionsSet.has(extname(absPath))) return null;
790
- const rootDir = this.rootDir;
791
- if (isPathWithinRoot(rootDir, absPath)) {
792
- const rel = relative(rootDir, absPath);
793
- if (scan.excludePatterns.some((pattern) => absPath.includes(pattern) || rel.includes(pattern))) return null;
794
- return {
795
- key: rel,
796
- owningRoot: null
797
- };
798
- }
799
- const resolved = this.sourceIdentity?.resolveSourceId(absPath);
800
- if (!resolved) return null;
801
- if (resolved.owningRoot === null) {
802
- if (scan.excludePatterns.some((pattern) => resolved.sourceKey.includes(pattern))) return null;
803
- return {
804
- key: resolved.sourceKey,
805
- owningRoot: null
806
- };
807
- }
808
- if (isExcludedPackageRelativePath(resolved.pathInRoot)) return null;
809
- return {
810
- key: resolved.sourceKey,
811
- owningRoot: resolved.owningRoot
812
- };
813
- }
814
- /**
815
- * Build file entries from cache: every cached file rides with full source.
816
- * The v2 engine has NO Rust-side cache (arch-extract-v2-spine: uncached
817
- * re-analysis beats a cache-hit path), so it must always receive full sources
818
- * (openspec: retire-extract-v1 removed the v1 empty-source cache contract).
819
- */
820
- buildFileEntriesFromCache() {
821
- const entries = [];
822
- for (const [path, { hash, source }] of this.fileCache) entries.push({
823
- path,
824
- source,
825
- hash
826
- });
827
- return entries;
828
- }
829
- /**
830
- * Run incremental pipeline with cache-aware file entries.
831
- * Reuses system config from the last full pipeline run.
832
- */
833
- async runIncrementalPipeline(fileEntries, pending = []) {
834
- const bt = {};
835
- const pipelineStart = this.now();
836
- await this.analyzeAndEmit(fileEntries, this.lastPackageMap, true, bt, pipelineStart, pending);
837
- }
838
- /**
839
- * Shared analysis + emit core for both pipelines — the single call site
840
- * that routes every manifest through the shared `runProjectAnalysis`,
841
- * reachable from both runFullPipeline (production) and
842
- * runIncrementalPipeline (HMR).
843
- *
844
- * Owns diagnostic surfacing, CSS assembly + styles.css write guard,
845
- * system-props module emit, and the timing log. The `devMode` flag is the
846
- * ONLY behavioral fork:
847
- *
848
- * - `false` (production): computes bt.analysis + logs the extraction
849
- * report, and writes system-props.js UNCONDITIONALLY (no
850
- * lastSystemPropsHash guard).
851
- * - `true` (HMR): skips the report log, and guards the system-props.js
852
- * write by lastSystemPropsHash.
853
- *
854
- * The disk artifacts land under the session directory in transaction
855
- * order (design D1): manifest → analysis-inputs (Turbopack orchestration
856
- * only) → styles.css → system-props → analysis-commit →
857
- * replacements-epoch (last, only when moved). The analysis-status file walks starting → analyzing →
858
- * committing → idle around the attempt, landing in `failed` (with the
859
- * diagnostic) on any throw (design D3).
860
- */
861
- async analyzeAndEmit(fileEntries, packageMap, devMode, bt, pipelineStart, pending = []) {
862
- this.beginStatusAttempt();
863
- this.debouncePending.clear();
864
- this.writeAnalysisStatus("starting", pending);
865
- try {
866
- await this.analyzeAndEmitAttempt(fileEntries, packageMap, devMode, bt, pipelineStart, pending);
867
- this.writeAnalysisStatus("idle", []);
868
- } catch (err) {
869
- this.writeAnalysisStatus("failed", pending, String(err));
870
- throw err;
871
- }
872
- }
873
- async analyzeAndEmitAttempt(fileEntries, packageMap, devMode, bt, pipelineStart, pending) {
874
- const system = this.system;
875
- const analysisOptions = {
876
- fileEntries,
877
- packageMap,
878
- system,
879
- emitter: {
880
- runtimeImport: "@animus-ui/system/runtime",
881
- cssModuleId: ANIMUS_CSS_MODULE_ID,
882
- systemPropsModuleId: this.systemPropsModuleId ?? systemPropsPath(this.sessionDir)
883
- },
884
- pathAliasesJson: this.pathAliasesJson,
885
- staticCssJson: this.staticCssJson,
886
- externalDirs: this.externalPackageDirs.map((dir) => relative(this.rootDir, dir)),
887
- devMode
888
- };
889
- this.writeAnalysisStatus("analyzing", pending);
890
- const result = runProjectAnalysis(engineApi, {
891
- ...analysisOptions,
892
- warn: (message) => this.warn(message),
893
- strict: this.options.strict,
894
- extraDiagnostics: this.externalKeyframesDiagnostics
895
- });
896
- enforceExternalTokenContracts({
897
- diagnostics: result.manifest?.diagnostics,
898
- fileOwners: this.externalFileOwners,
899
- dirOwners: this.externalDirOwners,
900
- sourceThemeManifestsJson: system.sourceThemeManifestsJson,
901
- strict: this.options.strict,
902
- prefix: "[animus-next]",
903
- warn: (message) => this.warn(message)
904
- });
905
- bt.jsonSerialize = result.timings.serializeMs;
906
- bt.rustExtract = result.timings.extractMs;
907
- bt.jsonParse = result.timings.parseMs;
908
- const manifest = result.manifest;
909
- if (!devMode) {
910
- bt.analysis = (bt.jsonSerialize ?? 0) + (bt.rustExtract ?? 0) + (bt.jsonParse ?? 0);
911
- if (manifest?.report) this.log(`Extracted ${manifest.report.components_extracted ?? "?"}/${manifest.report.components_total ?? "?"} components (${bt.analysis}ms)`);
912
- }
913
- const globalCss = this.substituteAssetReferences(result.globalCss, devMode);
914
- const { declaration, variables, body } = assembleStylesheet({
915
- layers: this.options.layers,
916
- variableCss: system.variableCss,
917
- globalCss,
918
- componentCss: result.componentCss,
919
- split: true
920
- });
921
- if (this.lcssTargets === null) this.lcssTargets = resolveLightningTargets(this.options.targets, this.rootDir);
922
- const fullCss = [
923
- declaration,
924
- variables,
925
- postProcessCss(body, {
926
- minify: this.options.minify ?? process.env.NODE_ENV === "production",
927
- targets: this.lcssTargets,
928
- warnFn: (msg) => this.warn(msg)
929
- })
930
- ].filter(Boolean).join("\n");
931
- setSharedCss(fullCss);
932
- const systemPropsContent = buildSystemPropsModule({
933
- systemPropMapJson: JSON.stringify(manifest?.system_prop_map ?? {}),
934
- groupRegistryJson: system.groupRegistryJson,
935
- dynamicProps: manifest?.dynamic_props ?? {}
936
- });
937
- setSharedSystemProps(systemPropsContent);
938
- setManifestJson(result.manifestJson);
939
- setAnalyzedHashes(new Map(fileEntries.map((entry) => [entry.path, entry.hash])));
940
- this.writeAnalysisStatus("committing", pending);
941
- const epoch = hashReplacementPlans(snapshotFilePlans(manifest), systemPropsContent);
942
- if (this.lastCommit === null) this.lastCommit = this.seedCommitFromDisk();
943
- const generation = (this.lastCommit?.generation ?? 0) + 1;
944
- this.publishPayloadArtifact("manifest", MANIFEST_ARTIFACT, result.manifestJson, epoch, generation, envelopeJsonArtifact);
945
- if (this.persistAnalysisInputs) this.publishPayloadArtifact("inputs", ANALYSIS_INPUTS_ARTIFACT, JSON.stringify({
946
- analyzedHashes: Object.fromEntries(fileEntries.map((entry) => [entry.path, entry.hash])),
947
- ...result.inputs
948
- }), epoch, generation, envelopeJsonArtifact);
949
- this.publishPayloadArtifact("styles", STYLES_ARTIFACT, fullCss, epoch, generation, envelopeCssArtifact);
950
- if (devMode) {
951
- const systemPropsHash = contentHash(systemPropsContent);
952
- if (systemPropsHash !== this.lastSystemPropsHash) {
953
- this.writeSessionArtifact(SYSTEM_PROPS_ARTIFACT, systemPropsContent);
954
- this.lastSystemPropsHash = systemPropsHash;
955
- }
956
- } else this.writeSessionArtifact(SYSTEM_PROPS_ARTIFACT, systemPropsContent);
957
- this.publishAnalysisCommit(epoch, generation);
958
- this.publishReplacementEpoch(epoch);
959
- bt.total = this.elapsed(pipelineStart);
960
- logBuildTimings(bt, manifest?.timing, (msg) => this.log(msg), this.verbose);
961
- }
962
- /** Open a status attempt (attemptId increments once per burst — a
963
- * debouncing pre-write and the analysis that follows share one id). */
964
- beginStatusAttempt() {
965
- if (!this.statusAttemptOpen) {
966
- this.statusAttemptId += 1;
967
- this.statusAttemptOpen = true;
968
- }
969
- }
970
- /** Write the session's analysis-status artifact (design D3). Terminal
971
- * states (idle/failed) close the attempt. */
972
- writeAnalysisStatus(state, pending, diagnostic) {
973
- const status = {
974
- schema: 1,
975
- sessionId: this.sessionId,
976
- attemptId: this.statusAttemptId,
977
- state,
978
- pending,
979
- deadlineAt: Date.now() + this.debounceCeilingMs + STATUS_WATCHDOG_MS,
980
- ...diagnostic !== void 0 ? { diagnostic } : {}
981
- };
982
- this.writeSessionArtifact(ANALYSIS_STATUS_ARTIFACT, JSON.stringify(status));
983
- if (state === "idle" || state === "failed") this.statusAttemptOpen = false;
984
- }
985
- /**
986
- * Orchestrator seam (Turbopack watcher): record watch events observed
987
- * during the debounce window so a loader running ahead of the analysis
988
- * has positive evidence to wait on (design D3 'debouncing'). Paths are
989
- * filtered by the scan config and hashed at observation time.
990
- */
991
- noteDebouncedWatchEvents(absPaths) {
992
- if (!this.rootDir) return;
993
- const additions = this.pendingFromBatch({ modifiedFiles: new Set(absPaths) });
994
- if (additions.length === 0) return;
995
- this.beginStatusAttempt();
996
- for (const [key, hash] of additions) this.debouncePending.set(key, hash);
997
- if (this.debounceStatusWriteScheduled) return;
998
- this.debounceStatusWriteScheduled = true;
999
- queueMicrotask(() => {
1000
- this.debounceStatusWriteScheduled = false;
1001
- if (this.debouncePending.size === 0) return;
1002
- this.writeAnalysisStatus("debouncing", [...this.debouncePending.entries()]);
1003
- });
1004
- }
1005
- /** One pending microtask flushes a burst of debounce observations. */
1006
- debounceStatusWriteScheduled = false;
1007
- /**
1008
- * Write one payload artifact into the session directory, enveloped with
1009
- * `{sessionId, generation, replacementEpoch, payloadHash}` and rewritten
1010
- * only when the PAYLOAD bytes changed (byte-identical re-analyses leave
1011
- * disk untouched — spec: "Unchanged manifest is not rewritten"). The
1012
- * recorded diskHash (hash of the enveloped bytes) feeds the
1013
- * analysis-commit.
1014
- */
1015
- publishPayloadArtifact(key, name, payload, epoch, generation, wrap) {
1016
- const payloadHash = contentHash(payload);
1017
- if (this.artifactRecords[key] === null) this.artifactRecords[key] = this.seedPayloadRecord(key, name);
1018
- const record = this.artifactRecords[key];
1019
- if (record !== null && record.payloadHash === payloadHash) return;
1020
- const envelope = {
1021
- sessionId: this.sessionId,
1022
- generation,
1023
- replacementEpoch: epoch,
1024
- payloadHash
1025
- };
1026
- const bytes = wrap(payload, JSON.stringify(envelope));
1027
- this.writeSessionArtifact(name, bytes);
1028
- this.artifactRecords[key] = {
1029
- payloadHash,
1030
- diskHash: contentHash(bytes)
1031
- };
1032
- }
1033
- /** Reconstruct a payload write guard from the on-disk artifact's envelope
1034
- * (same-session restart: a byte-identical payload must not rewrite). */
1035
- seedPayloadRecord(key, name) {
1036
- let bytes;
1037
- try {
1038
- bytes = readFileSync(join(this.sessionDir, name), "utf-8");
1039
- } catch {
1040
- return null;
1041
- }
1042
- let envelope;
1043
- try {
1044
- envelope = key === "styles" ? readCssEnvelope(bytes) : readJsonEnvelope(bytes);
1045
- } catch {
1046
- return null;
1047
- }
1048
- if (!envelope || typeof envelope.payloadHash !== "string") return null;
1049
- return {
1050
- payloadHash: envelope.payloadHash,
1051
- diskHash: contentHash(bytes)
1052
- };
1053
- }
1054
- /** Last analysis-commit persisted in this session's directory, or null. */
1055
- seedCommitFromDisk() {
1056
- try {
1057
- const parsed = JSON.parse(readFileSync(analysisCommitPath(this.sessionDir), "utf-8"));
1058
- return parsed.schema === 1 && parsed.sessionId === this.sessionId && typeof parsed.generation === "number" ? parsed : null;
1059
- } catch {
1060
- return null;
1061
- }
1062
- }
1063
- /**
1064
- * Publish the analysis-commit — the transaction identity (design D1).
1065
- * Written AFTER every payload and BEFORE the epoch; skipped entirely when
1066
- * the payload set (disk hashes) and epoch are unchanged, so a no-op
1067
- * re-analysis neither re-keys loader-worker hydration nor burns a
1068
- * generation.
1069
- */
1070
- publishAnalysisCommit(epoch, generation) {
1071
- const manifestHash = this.artifactRecords.manifest?.diskHash ?? "";
1072
- const inputsHash = this.persistAnalysisInputs ? this.artifactRecords.inputs?.diskHash ?? "" : void 0;
1073
- const stylesHash = this.artifactRecords.styles?.diskHash ?? "";
1074
- const prev = this.lastCommit;
1075
- if (prev !== null && prev.manifestHash === manifestHash && prev.inputsHash === inputsHash && prev.stylesHash === stylesHash && prev.replacementEpoch === epoch) return;
1076
- const commit = {
1077
- schema: 1,
1078
- sessionId: this.sessionId,
1079
- generation,
1080
- replacementEpoch: epoch,
1081
- manifestHash,
1082
- ...inputsHash !== void 0 ? { inputsHash } : {},
1083
- stylesHash
1084
- };
1085
- this.writeSessionArtifact(ANALYSIS_COMMIT_ARTIFACT, JSON.stringify(commit));
1086
- this.lastCommit = commit;
1087
- }
1088
- /**
1089
- * Publish the canonical replacement epoch: maintain the session-scoped
1090
- * disk witness `{schema, sessionId, epoch}`, rewritten ONLY when the
1091
- * epoch VALUE changes so style-only analyses and same-session restarts
1092
- * leave bytes and mtime untouched, then expose the value through the
1093
- * singleton for the plugin's needBuild fan-out and the loader's catch-up
1094
- * re-check. Every VALUE move also reconciles sibling sessions' epoch
1095
- * artifacts (below) — the webpack cold-cache validity witness.
1096
- */
1097
- publishReplacementEpoch(epoch) {
1098
- if (this.lastEpochValue === null) this.lastEpochValue = this.diskEpochValue();
1099
- if (epoch !== this.lastEpochValue) {
1100
- this.writeSessionArtifact(REPLACEMENT_EPOCH_ARTIFACT, JSON.stringify({
1101
- schema: 1,
1102
- sessionId: this.sessionId,
1103
- epoch
1104
- }));
1105
- this.lastEpochValue = epoch;
1106
- this.reconcileSiblingEpochs(epoch);
1107
- }
1108
- setReplacementEpoch(epoch);
1109
- }
1110
- /**
1111
- * Sibling epoch reconciliation — the cross-session half of the webpack
1112
- * persistent-cache witness (spec: dev-served-transform-coherence,
1113
- * "Offline change invalidates restored modules"). Restored-module
1114
- * snapshots reference the epoch artifact of the session that BUILT them;
1115
- * with session-scoped trees that file would otherwise sit untouched
1116
- * forever, keeping stale snapshots valid. Whenever this session's epoch
1117
- * value moves, delete every sibling epoch artifact that disagrees (their
1118
- * snapshots must invalidate — restore-on-demand then rebuilds from the
1119
- * current generation) and leave agreeing siblings byte-untouched (warm
1120
- * restores stay valid). Deleting a stale artifact is pruning, not a
1121
- * foreign-session write; races with concurrent sessions are tolerated
1122
- * (S14).
1123
- */
1124
- /** Sibling ids already reconciled away (artifact deleted or absent) —
1125
- * nothing left to invalidate for them on later moves. */
1126
- reconciledSiblingIds = /* @__PURE__ */ new Set();
1127
- /** sessions-root listing memo, keyed by the root dir's mtime — a new or
1128
- * pruned sibling DIRECTORY moves it; agreeing siblings stay listed. */
1129
- siblingListing = null;
1130
- reconcileSiblingEpochs(epoch) {
1131
- const rootPath = sessionsRootDir(this.rootDir);
1132
- let entries;
1133
- try {
1134
- const mtimeMs = statSync(rootPath).mtimeMs;
1135
- if (this.siblingListing?.mtimeMs === mtimeMs) entries = this.siblingListing.entries;
1136
- else {
1137
- entries = readdirSync(rootPath);
1138
- this.siblingListing = {
1139
- mtimeMs,
1140
- entries
1141
- };
1142
- }
1143
- } catch {
1144
- return;
1145
- }
1146
- for (const entry of entries) {
1147
- if (entry === this.sessionId) continue;
1148
- if (this.reconciledSiblingIds.has(entry)) continue;
1149
- const siblingEpochPath = join(rootPath, entry, REPLACEMENT_EPOCH_ARTIFACT);
1150
- try {
1151
- if (JSON.parse(readFileSync(siblingEpochPath, "utf-8")).epoch === epoch) continue;
1152
- } catch (err) {
1153
- if (err?.code === "ENOENT") {
1154
- this.reconciledSiblingIds.add(entry);
1155
- continue;
1156
- }
1157
- }
1158
- try {
1159
- unlinkSync(siblingEpochPath);
1160
- } catch {}
1161
- this.reconciledSiblingIds.add(entry);
1162
- }
1163
- }
1164
- /** Epoch value held by this session's on-disk artifact, or null when
1165
- * absent, unreadable, or not the expected schema. */
1166
- diskEpochValue() {
1167
- try {
1168
- const parsed = JSON.parse(readFileSync(replacementEpochPath(this.sessionDir), "utf-8"));
1169
- return parsed.schema === 1 && typeof parsed.epoch === "string" ? parsed.epoch : null;
1170
- } catch {
1171
- return null;
1172
- }
1173
- }
1174
- /** Session-start hygiene (design D2): delete legacy flat artifacts
1175
- * (unreachable by session-scoped loaders) and prune sibling session
1176
- * directories older than the retention window — never the own dir,
1177
- * tolerating races with concurrently-pruning sessions (S14). */
1178
- runSessionStartHygiene() {
1179
- if (this.sessionStartHygieneDone) return;
1180
- this.sessionStartHygieneDone = true;
1181
- const animusDir = join(this.rootDir, ".animus");
1182
- for (const name of LEGACY_FLAT_ARTIFACTS) try {
1183
- unlinkSync(join(animusDir, name));
1184
- } catch {}
1185
- let entries;
1186
- try {
1187
- entries = readdirSync(sessionsRootDir(this.rootDir));
1188
- } catch {
1189
- return;
1190
- }
1191
- const cutoff = Date.now() - SESSION_DIR_MAX_AGE_MS;
1192
- for (const entry of entries) {
1193
- if (entry === this.sessionId) continue;
1194
- const dir = join(sessionsRootDir(this.rootDir), entry);
1195
- try {
1196
- if (statSync(dir).mtimeMs < cutoff) rmSync(dir, {
1197
- recursive: true,
1198
- force: true
1199
- });
1200
- } catch {}
1201
- }
1202
- }
1203
- /** Ensure the session directory exists and write one artifact into it.
1204
- * Write-then-rename so cross-process readers (Turbopack loader workers)
1205
- * can never observe a torn half-written file. The tmp name carries the
1206
- * pid — Next dev evaluates the config in more than one process, and two
1207
- * sessions writing the same artifact must not race on one tmp path. */
1208
- writeSessionArtifact(name, content) {
1209
- const dir = this.sessionDir;
1210
- mkdirSync(dir, { recursive: true });
1211
- const tmpPath = join(dir, `.${name}.${process.pid}.tmp`);
1212
- writeFileSync(tmpPath, content);
1213
- renameSync(tmpPath, join(dir, name));
1214
- this.onArtifactWrite?.(name, content);
1215
- }
1216
- /**
1217
- * asset() placeholder substitution (global-styles-system): resolve each
1218
- * referenced specifier through Node resolution, copy the bytes into the
1219
- * session directory's `assets/` under a content-hashed name, and
1220
- * substitute a RELATIVE url — relative to the session-scoped styles.css,
1221
- * which sits beside `assets/`, so the emitted `./assets/<file>` form is
1222
- * unchanged. The stylesheet is processed by Next's own CSS pipeline
1223
- * (webpack and Turbopack alike), which applies its native asset handling
1224
- * — publicPath and output hashing — to relative url() references.
1225
- * Unsubstitutable specifiers warn and emit literally in non-strict mode,
1226
- * fail the build under `strict: true`.
1227
- */
1228
- substituteAssetReferences(globalCss, devMode) {
1229
- const specifiers = findAssetSpecifiers(globalCss);
1230
- const assetsDir = join(this.sessionDir, SESSION_ASSETS_DIR);
1231
- const expected = /* @__PURE__ */ new Set();
1232
- this.assetDependencyPaths.clear();
1233
- this.assetDependencyKeys.clear();
1234
- const urlBySpecifier = /* @__PURE__ */ new Map();
1235
- for (const specifier of specifiers) {
1236
- const cached = this.assetCopyCache.get(specifier);
1237
- if (cached && existsSync(join(assetsDir, cached.fileName))) try {
1238
- const current = statSync(cached.sourcePath);
1239
- if (current.mtimeMs === cached.mtimeMs && current.size === cached.size) {
1240
- this.trackAssetDependency(cached.sourcePath);
1241
- expected.add(cached.fileName);
1242
- urlBySpecifier.set(specifier, cached.url);
1243
- continue;
1244
- }
1245
- } catch {}
1246
- const resolvedPath = this.resolveAssetSpecifier(specifier);
1247
- if (!resolvedPath) {
1248
- const message = `unresolvable asset() specifier: ${specifier}`;
1249
- if (this.options.strict) throw new Error(`[animus-next] ${message}`);
1250
- this.warn(message);
1251
- urlBySpecifier.set(specifier, specifier);
1252
- continue;
1253
- }
1254
- const bytes = readFileSync(resolvedPath);
1255
- const sourceStat = statSync(resolvedPath);
1256
- this.trackAssetDependency(resolvedPath);
1257
- const ext = extname(resolvedPath);
1258
- const fileName = `${basename(resolvedPath, ext)}.${contentHash(bytes).slice(0, 8)}${ext}`;
1259
- expected.add(fileName);
1260
- if (!existsSync(assetsDir)) mkdirSync(assetsDir, { recursive: true });
1261
- const assetPath = join(assetsDir, fileName);
1262
- if (!existsSync(assetPath)) writeFileSync(assetPath, bytes);
1263
- const url = `./assets/${fileName}`;
1264
- urlBySpecifier.set(specifier, url);
1265
- this.assetCopyCache.set(specifier, {
1266
- sourcePath: resolvedPath,
1267
- mtimeMs: sourceStat.mtimeMs,
1268
- size: sourceStat.size,
1269
- fileName,
1270
- url
1271
- });
1272
- }
1273
- if (!devMode) pruneStaleAssets(assetsDir, expected);
1274
- return substituteAssetPlaceholders(globalCss, urlBySpecifier);
1275
- }
1276
- trackAssetDependency(path) {
1277
- this.assetDependencyPaths.add(path);
1278
- for (const key of toWatchKeys(path)) this.assetDependencyKeys.add(key);
1279
- }
1280
- /**
1281
- * Resolve an asset specifier to an absolute file via the shared pipeline
1282
- * resolver (host aliases → Node resolution → package root), with one
1283
- * session-local last resort: an already-discovered source entry's package
1284
- * root (dist-less workspace kits the shared resolver cannot see).
1285
- */
1286
- resolveAssetSpecifier(specifier) {
1287
- const resolved = resolveAssetFile(specifier, this.rootDir, this.pathAliasesJson);
1288
- if (resolved) return resolved;
1289
- const segments = specifier.split("/");
1290
- const packageName = specifier.startsWith("@") ? segments.slice(0, 2).join("/") : segments[0];
1291
- const subpath = specifier.slice(packageName.length + 1);
1292
- if (!subpath) return null;
1293
- const sourceEntry = this.externalSourceEntries.get(packageName) ?? [...this.externalSourceEntries].find(([declared]) => declared === packageName || declared.startsWith(`${packageName}/`))?.[1];
1294
- if (sourceEntry) {
1295
- const candidate = join(findPackageRoot(sourceEntry), subpath);
1296
- if (existsSync(candidate)) return candidate;
1297
- }
1298
- return null;
1299
- }
1300
- };
1301
- /**
1302
- * Sync `.animus/assets/` to the current build's content-hashed file set:
1303
- * anything else in the directory is a superseded revision (the copies are
1304
- * content-addressed and never overwritten) or the leftover of an asset()
1305
- * reference that no longer exists. Failures are tolerated per entry — Next
1306
- * dev evaluates the config in more than one process, and a concurrent
1307
- * session may have removed (or be about to rewrite) the same file; every
1308
- * pass rewrites whatever of its own set is missing, so races self-heal.
1309
- */
1310
- function pruneStaleAssets(assetsDir, expected) {
1311
- if (!existsSync(assetsDir)) return;
1312
- let entries;
1313
- try {
1314
- entries = readdirSync(assetsDir);
1315
- } catch {
1316
- return;
1317
- }
1318
- for (const entry of entries) {
1319
- if (expected.has(entry)) continue;
1320
- try {
1321
- unlinkSync(join(assetsDir, entry));
1322
- } catch {}
1323
- }
1324
- }
1325
- //#endregion
1326
6
  //#region src/loader-path.ts
1327
7
  const __dirname$1 = dirname(fileURLToPath(import.meta.url));
1328
8
  /**
@@ -1431,7 +111,7 @@ var AnimusWebpackPlugin = class {
1431
111
  for (const [key, value] of Object.entries(rawAlias)) {
1432
112
  const target = Array.isArray(value) ? value[0] : value;
1433
113
  if (typeof target !== "string") continue;
1434
- if (key === ".animus/styles.css") continue;
114
+ if (key === ANIMUS_CSS_MODULE_ID) continue;
1435
115
  pairs.push({
1436
116
  pattern: key,
1437
117
  target
@@ -1481,11 +161,11 @@ var AnimusWebpackPlugin = class {
1481
161
  compilation.updateAsset(cssPath, new RawSource(css));
1482
162
  return;
1483
163
  }
1484
- if (compilation.getAsset(".animus/styles.css")) compilation.updateAsset(ANIMUS_CSS_MODULE_ID, new RawSource(css));
164
+ if (compilation.getAsset(ANIMUS_CSS_MODULE_ID)) compilation.updateAsset(ANIMUS_CSS_MODULE_ID, new RawSource(css));
1485
165
  });
1486
166
  });
1487
167
  compiler.hooks.run.tapPromise(PLUGIN_NAME, async (_compiler) => {
1488
- this.session.rootDir = _compiler.context;
168
+ this.adoptCompilerContext(_compiler);
1489
169
  this.extractAliases(_compiler);
1490
170
  const existing = getAnalysisPromise();
1491
171
  if (existing) {
@@ -1497,7 +177,7 @@ var AnimusWebpackPlugin = class {
1497
177
  await promise;
1498
178
  });
1499
179
  compiler.hooks.watchRun.tapPromise(PLUGIN_NAME, async (_compiler) => {
1500
- this.session.rootDir = _compiler.context;
180
+ this.adoptCompilerContext(_compiler);
1501
181
  this.extractAliases(_compiler);
1502
182
  if (!this.initialized) {
1503
183
  const existing = getAnalysisPromise();
@@ -1532,11 +212,34 @@ var AnimusWebpackPlugin = class {
1532
212
  return this.session.sessionId;
1533
213
  }
1534
214
  /** Set the project root at CONFIG time (with-animus) — the ONE root all
1535
- * session-path derivations use. The compiler hooks re-assert it from
1536
- * compiler.context (identical when compiler.context === cwd). */
215
+ * session-path derivations use. The compiler hooks ADOPT
216
+ * compiler.context only when no root was published (bare-apply
217
+ * harnesses); they never overwrite this. */
1537
218
  setRootDir(rootDir) {
1538
219
  this.session.rootDir = rootDir;
1539
220
  }
221
+ /** One warning per plugin instance for a context/root mismatch. */
222
+ warnedRootDivergence = false;
223
+ /** The run/watchRun taps' root handling: adopt compiler.context when no
224
+ * config-time root exists; otherwise KEEP the configured root — every
225
+ * frozen config-time derivation (stub path, css alias target,
226
+ * virtual:animus/system-props target, watch-ignore) came from it, and a
227
+ * silent overwrite re-keys sessionDir so the pipeline publishes
228
+ * artifacts where none of those consumers look. A disagreement is
229
+ * surfaced loudly instead (with-animus derives the root from Next's own
230
+ * `dir`, which equals compiler.context in real Next runs — a mismatch
231
+ * means a custom-webpack setup wired the plugin differently). */
232
+ adoptCompilerContext(compiler) {
233
+ const context = compiler.context;
234
+ if (!this.session.rootDir) {
235
+ this.session.rootDir = context;
236
+ return;
237
+ }
238
+ if (context && this.session.rootDir !== context && !this.warnedRootDivergence) {
239
+ this.warnedRootDivergence = true;
240
+ console.warn(`[animus-extract] compiler.context (${context}) differs from the configured project root (${this.session.rootDir}); keeping the configured root — run next against the app directory (or align your custom webpack context) so both agree`);
241
+ }
242
+ }
1540
243
  /** This session's artifact directory, derived from the one root. */
1541
244
  get sessionDir() {
1542
245
  return this.session.sessionDir;
@@ -1558,15 +261,13 @@ var AnimusWebpackPlugin = class {
1558
261
  };
1559
262
  //#endregion
1560
263
  //#region src/turbopack-config.ts
1561
- /** The single glob the Animus loader registers under. `.mjs` is included
1562
- * for webpack parity: an external package without `src/` is ingested via
1563
- * its resolved dist entry (often `dist/index.mjs`) and must still reach
1564
- * the loader — manifest lookup remains the file-level gate. */
1565
- const ANIMUS_TURBOPACK_RULE_GLOB = "*.{ts,tsx,js,jsx,mjs}";
1566
- /** Virtual system-props id emitted into transformed sources under Turbopack
1567
- * (absolute-path imports are rejected there); resolveAlias maps it to the
1568
- * on-disk artifact. */
1569
- const TURBOPACK_SYSTEM_PROPS_ID = "virtual:animus/system-props";
264
+ /** The single glob the Animus loader registers under — derived from the
265
+ * ONE shared engine extension set (also the unplugin transform gate's
266
+ * source), so the two bundler families cannot drift. `.mjs` is in that
267
+ * set for webpack parity: an external package without `src/` is ingested
268
+ * via its resolved dist entry (often `dist/index.mjs`) and must still
269
+ * reach the loader — manifest lookup remains the file-level gate. */
270
+ const ANIMUS_TURBOPACK_RULE_GLOB = `*.{${ENGINE_TRANSFORM_EXTENSIONS.join(",")}}`;
1570
271
  /**
1571
272
  * Resolve whether Turbopack wiring is active for this process. Default is
1572
273
  * `'auto'`: active exactly when the TURBOPACK environment variable is set
@@ -1627,211 +328,6 @@ function resolveTurbopackLoaderPath(pluginDir) {
1627
328
  return resolveLoaderPath(pluginDir, ["turbopack-loader.cjs", "turbopack-loader.mjs"], "turbopack-loader.ts");
1628
329
  }
1629
330
  //#endregion
1630
- //#region src/turbopack-orchestrator.ts
1631
- /**
1632
- * Out-of-band pipeline orchestration for Turbopack (spec:
1633
- * next-turbopack-integration). Turbopack exposes no compiler hooks, so the
1634
- * pipeline runs during next.config resolution and, in dev, from a
1635
- * filesystem watcher — the bundler only ever sees the `.animus/` disk
1636
- * artifacts.
1637
- */
1638
- /** Run the full pipeline with the Turbopack emitter identity: the virtual
1639
- * system-props id (Turbopack rejects the webpack path's absolute-path
1640
- * imports). Turbopack orchestration persists the analysis-inputs
1641
- * hydration corpus — its isolated loader workers replay it (spec:
1642
- * next-turbopack-integration, "Manifest disk artifact"; webpack mode
1643
- * skips the corpus). */
1644
- async function runTurbopackPipeline(session) {
1645
- session.systemPropsModuleId = TURBOPACK_SYSTEM_PROPS_ID;
1646
- session.persistAnalysisInputs = true;
1647
- await session.runFullPipeline();
1648
- }
1649
- const activeWatcherRoots = /* @__PURE__ */ new Set();
1650
- const IGNORED_SEGMENTS = new Set([
1651
- ".animus",
1652
- ".next",
1653
- "node_modules"
1654
- ]);
1655
- /**
1656
- * Start the dev watcher: fs.watch per eligible top-level directory (plus a
1657
- * non-recursive watch on the root itself), debounced into
1658
- * existence-partitioned modified/removed sets feeding
1659
- * `session.handleWatchUpdate` (serialized — updates never overlap).
1660
- * Generated and vendored trees (`.animus`, `.next`, node_modules) are never
1661
- * registered with the OS — recursive registration of those trees exhausts
1662
- * inotify/kqueue descriptors (EMFILE/ENOSPC) on large projects.
1663
- * Idempotent per project root; unref'd so it never holds the process open.
1664
- * Asynchronous FSWatcher errors degrade to no-watch with a warning instead
1665
- * of crashing the dev server. Returns a close handle, or null when this
1666
- * root is already watched or the platform lacks recursive fs.watch (Linux
1667
- * before Node 20 — degrades to no-watch with a warning).
1668
- */
1669
- function startTurbopackWatcher(session, rootDir, debounceMs = 75, watchFn = watch) {
1670
- if (activeWatcherRoots.has(rootDir)) return null;
1671
- activeWatcherRoots.add(rootDir);
1672
- if (typeof session.noteDebouncedWatchEvents === "function") session.debounceCeilingMs = debounceMs;
1673
- const pendingPaths = /* @__PURE__ */ new Set();
1674
- const watchers = /* @__PURE__ */ new Map();
1675
- let timer = null;
1676
- let updateChain = Promise.resolve();
1677
- let closed = false;
1678
- const externalWatchers = /* @__PURE__ */ new Map();
1679
- let pendingOpened = /* @__PURE__ */ new Map();
1680
- let capturedDuringSnapshot = [];
1681
- const externalDiagnosticKey = (root) => `external-watch:${root}`;
1682
- const failureReason = (err) => {
1683
- const code = err?.code;
1684
- if (code === "EMFILE" || code === "ENFILE" || code === "ENOSPC" || code === "EPERM") return `capacity(${code})`;
1685
- if (/inotify|too many/i.test(String(err))) return "capacity";
1686
- return code ?? "error";
1687
- };
1688
- const degradeExternalRoot = (root, err) => {
1689
- externalWatchers.get(root)?.close();
1690
- externalWatchers.delete(root);
1691
- pendingOpened.get(root)?.close();
1692
- pendingOpened.delete(root);
1693
- const message = `ANIMUS_EXTERNAL_WATCH_UNAVAILABLE root=${relative(rootDir, root)} reason=${failureReason(err)} effect=changes in this workspace source may require restart`;
1694
- session.stickyDiagnostics?.set(externalDiagnosticKey(root), message);
1695
- console.warn(`[animus-extract] ${message}`);
1696
- };
1697
- const flush = () => {
1698
- timer = null;
1699
- const modifiedFiles = /* @__PURE__ */ new Set();
1700
- const removedFiles = /* @__PURE__ */ new Set();
1701
- for (const path of pendingPaths) (existsSync(path) ? modifiedFiles : removedFiles).add(path);
1702
- pendingPaths.clear();
1703
- updateChain = updateChain.then(() => session.handleWatchUpdate({
1704
- modifiedFiles,
1705
- removedFiles
1706
- }).catch((err) => {
1707
- console.warn(`[animus-extract] Turbopack watch update failed: ${String(err)}`);
1708
- }).then(() => {
1709
- if (pendingOpened.size > 0 || capturedDuringSnapshot.length > 0) rollbackPendingExternal();
1710
- }));
1711
- };
1712
- const rollbackPendingExternal = () => {
1713
- for (const watcher of pendingOpened.values()) watcher.close();
1714
- pendingOpened = /* @__PURE__ */ new Map();
1715
- capturedDuringSnapshot = [];
1716
- };
1717
- const closeAll = () => {
1718
- if (closed) return;
1719
- closed = true;
1720
- if (timer) clearTimeout(timer);
1721
- timer = null;
1722
- for (const watcher of watchers.values()) watcher.close();
1723
- watchers.clear();
1724
- for (const watcher of externalWatchers.values()) watcher.close();
1725
- externalWatchers.clear();
1726
- rollbackPendingExternal();
1727
- session.onExternalRootResolved = null;
1728
- session.onExternalRootsCommitted = null;
1729
- activeWatcherRoots.delete(rootDir);
1730
- };
1731
- const onWatcherError = (err) => {
1732
- closeAll();
1733
- console.warn(`[animus-extract] Turbopack dev watcher failed (${String(err)}); source edits require a dev-server restart`);
1734
- };
1735
- const enqueuePath = (abs) => {
1736
- pendingPaths.add(abs);
1737
- try {
1738
- session.noteDebouncedWatchEvents?.([abs]);
1739
- } catch (err) {
1740
- console.warn(`[animus-extract] Turbopack debounce status update failed: ${String(err)}`);
1741
- }
1742
- if (!timer) {
1743
- timer = setTimeout(flush, debounceMs);
1744
- timer.unref?.();
1745
- }
1746
- };
1747
- const onEvent = (baseDir, filename) => {
1748
- if (closed || !filename) return;
1749
- const rel = filename.toString();
1750
- if (rel.split(/[\\/]/).some((segment) => IGNORED_SEGMENTS.has(segment))) return;
1751
- const abs = join(baseDir, rel);
1752
- if (baseDir === rootDir && !watchers.has(abs)) try {
1753
- if (statSync(abs).isDirectory()) addWatcher(abs, true);
1754
- } catch {}
1755
- enqueuePath(abs);
1756
- };
1757
- /** External-root event path: fenced by watcher identity ({watcherRootId,
1758
- * generation} — a handle that is neither current nor pending belongs to
1759
- * a retired generation and its events are rejected), `filename == null`
1760
- * marks the ROOT dirty for rediscovery, and events observed while the
1761
- * root's generation is still snapshotting are buffered for replay. */
1762
- const onExternalEvent = (root, self, filename) => {
1763
- if (closed) return;
1764
- const watcher = self();
1765
- const active = watcher !== void 0 && externalWatchers.get(root) === watcher;
1766
- const isPending = watcher !== void 0 && pendingOpened.get(root) === watcher;
1767
- if (!active && !isPending) return;
1768
- let abs;
1769
- if (filename == null) abs = root;
1770
- else {
1771
- const rel = filename.toString();
1772
- if (rel.split(/[\\/]/).some((segment) => IGNORED_SEGMENTS.has(segment))) return;
1773
- abs = rel === "" ? root : join(root, rel);
1774
- }
1775
- if (isPending && !active) {
1776
- capturedDuringSnapshot.push(abs);
1777
- return;
1778
- }
1779
- enqueuePath(abs);
1780
- };
1781
- /** Open one external-root watcher into `into` (the committed set at
1782
- * startup, the pending set during reset reconciliation). Failures
1783
- * degrade ONLY this root (design D7); node_modules-resident roots are
1784
- * documented unwatchable and never registered (guardrail G2). */
1785
- const openExternalWatcher = (root, into) => {
1786
- if (root.split(/[\\/]/).includes("node_modules")) return;
1787
- try {
1788
- let watcher;
1789
- watcher = watchFn(root, { recursive: true }, (_event, filename) => onExternalEvent(root, () => watcher, filename));
1790
- watcher.on("error", (err) => degradeExternalRoot(root, err));
1791
- watcher.unref?.();
1792
- into.set(root, watcher);
1793
- session.stickyDiagnostics?.delete(externalDiagnosticKey(root));
1794
- } catch (err) {
1795
- degradeExternalRoot(root, err);
1796
- }
1797
- };
1798
- const addWatcher = (dir, recursive) => {
1799
- const watcher = watchFn(dir, { recursive }, (_event, filename) => onEvent(dir, filename));
1800
- watcher.on("error", onWatcherError);
1801
- watcher.unref?.();
1802
- watchers.set(dir, watcher);
1803
- };
1804
- try {
1805
- addWatcher(rootDir, false);
1806
- for (const entry of readdirSync(rootDir, { withFileTypes: true })) {
1807
- if (!entry.isDirectory() || IGNORED_SEGMENTS.has(entry.name)) continue;
1808
- addWatcher(join(rootDir, entry.name), true);
1809
- }
1810
- } catch (err) {
1811
- closeAll();
1812
- console.warn(`[animus-extract] Turbopack dev watcher unavailable (${String(err)}); source edits require a dev-server restart`);
1813
- return null;
1814
- }
1815
- for (const root of session.externalWatchRoots ?? []) openExternalWatcher(root, externalWatchers);
1816
- session.onExternalRootResolved = (root) => {
1817
- if (closed) return;
1818
- if (externalWatchers.has(root) || pendingOpened.has(root)) return;
1819
- openExternalWatcher(root, pendingOpened);
1820
- };
1821
- session.onExternalRootsCommitted = (roots) => {
1822
- if (closed) return;
1823
- const admitted = new Set(roots);
1824
- for (const [root, watcher] of pendingOpened) externalWatchers.set(root, watcher);
1825
- pendingOpened = /* @__PURE__ */ new Map();
1826
- for (const [root, watcher] of [...externalWatchers]) if (!admitted.has(root)) {
1827
- watcher.close();
1828
- externalWatchers.delete(root);
1829
- }
1830
- for (const abs of capturedDuringSnapshot.splice(0)) enqueuePath(abs);
1831
- };
1832
- return { close: closeAll };
1833
- }
1834
- //#endregion
1835
331
  //#region src/with-animus.ts
1836
332
  const __dirname = dirname(fileURLToPath(import.meta.url));
1837
333
  let warnedGitignore = false;
@@ -1847,6 +343,18 @@ let warnedUnstableTurbopack = false;
1847
343
  */
1848
344
  function withAnimus(options) {
1849
345
  if (!options.system) throw new Error("[animus-extract] Missing required option `system`. Provide the path to your SystemInstance module: withAnimus({ system: \"./src/ds.ts\" })");
346
+ assertKnownOptionKeys(options, [
347
+ "cssImportTarget",
348
+ "turbopack",
349
+ "unstable_turbopack",
350
+ "loaderPath"
351
+ ], [{
352
+ key: "root",
353
+ reason: "the Next driver's root is Next's `dir` at config time"
354
+ }], {
355
+ onUnknownKey: "warn",
356
+ warn: (message) => console.warn(`[animus-extract] ${message}`)
357
+ });
1850
358
  if (options.unstable_turbopack && !options.turbopack && !warnedUnstableTurbopack) {
1851
359
  warnedUnstableTurbopack = true;
1852
360
  console.warn("[animus-extract] `unstable_turbopack` is deprecated — rename it to `turbopack` (same shape)");
@@ -1858,7 +366,7 @@ function withAnimus(options) {
1858
366
  ...nextConfig,
1859
367
  webpack(config, context) {
1860
368
  if (typeof existingWebpack === "function") config = existingWebpack(config, context);
1861
- const rootDir = process.cwd();
369
+ const rootDir = typeof context.dir === "string" && context.dir.length > 0 ? context.dir : process.cwd();
1862
370
  const plugin = new AnimusWebpackPlugin(options);
1863
371
  plugin.setRootDir(rootDir);
1864
372
  const sessionDir = plugin.sessionDir;
@@ -1886,10 +394,10 @@ function withAnimus(options) {
1886
394
  config.plugins = config.plugins || [];
1887
395
  config.plugins.push(plugin);
1888
396
  const { DefinePlugin } = context.webpack ?? {};
1889
- if (typeof DefinePlugin === "function") config.plugins.push(new DefinePlugin({ __ANIMUS_DEV__: JSON.stringify(context.dev === true) }));
397
+ if (typeof DefinePlugin === "function") config.plugins.push(new DefinePlugin({ __ANIMUS_DEV__: JSON.stringify(resolveMode(options.mode, () => context.dev === true ? "development" : "production").mode === "development") }));
1890
398
  config.resolve = config.resolve || {};
1891
399
  config.resolve.alias = config.resolve.alias || {};
1892
- config.resolve.alias[ANIMUS_CSS_MODULE_ID] = stylesPath(sessionDir);
400
+ config.resolve.alias[ANIMUS_CSS_MODULE_ID$1] = stylesPath(sessionDir);
1893
401
  const sessionSystemPropsPath = systemPropsPath(sessionDir);
1894
402
  config.plugins.push({ apply(compiler) {
1895
403
  compiler.hooks.normalModuleFactory.tap("AnimusVirtualResolve", (nmf) => {
@@ -1939,7 +447,7 @@ async function wireTurbopack(nextConfig, options) {
1939
447
  session.rootDir = rootDir;
1940
448
  const builtAliases = buildPathAliasesJson(readTsconfigAliasPairs(rootDir), rootDir);
1941
449
  if (builtAliases) session.pathAliasesJson = builtAliases.json;
1942
- await runTurbopackPipeline(session);
450
+ await runSessionPipeline(session);
1943
451
  if (process.env.NODE_ENV === "development") startTurbopackWatcher(session, rootDir);
1944
452
  const fragment = buildTurbopackConfig({
1945
453
  rootDir,
@@ -1950,7 +458,7 @@ async function wireTurbopack(nextConfig, options) {
1950
458
  sessionDir: session.sessionDir
1951
459
  });
1952
460
  const existing = nextConfig.turbopack ?? {};
1953
- 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`);
461
+ if (existing.rules && ANIMUS_TURBOPACK_RULE_GLOB 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`);
1954
462
  return {
1955
463
  ...nextConfig,
1956
464
  turbopack: {