@animus-ui/extract 0.1.9 → 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.
Files changed (126) hide show
  1. package/README.md +1 -1
  2. package/crates/extract-v2/animus-extract-v2.darwin-arm64.node +0 -0
  3. package/crates/extract-v2/animus-extract-v2.linux-arm64-gnu.node +0 -0
  4. package/crates/extract-v2/animus-extract-v2.linux-x64-gnu.node +0 -0
  5. package/dist/index.cjs +73 -2101
  6. package/dist/index.mjs +2 -2026
  7. package/dist/pipeline/analyze-project-args.d.ts.map +1 -0
  8. package/dist/pipeline/assemble-stylesheet.d.ts.map +1 -0
  9. package/dist/pipeline/asset-placeholders.d.ts.map +1 -0
  10. package/dist/pipeline/content-hash.d.ts.map +1 -0
  11. package/dist/pipeline/core-options.d.ts +162 -0
  12. package/dist/pipeline/core-options.d.ts.map +1 -0
  13. package/dist/pipeline/correlate-external-tokens.d.ts.map +1 -0
  14. package/dist/pipeline/discover-files.d.ts +12 -0
  15. package/dist/pipeline/discover-files.d.ts.map +1 -0
  16. package/dist/{discover-packages.d.ts → pipeline/discover-packages.d.ts} +7 -8
  17. package/dist/pipeline/discover-packages.d.ts.map +1 -0
  18. package/dist/pipeline/dynamic-prop-config.d.ts.map +1 -0
  19. package/dist/{engine-adapter.d.ts → pipeline/engine-adapter.d.ts} +2 -0
  20. package/dist/pipeline/engine-adapter.d.ts.map +1 -0
  21. package/dist/pipeline/engine-retirement.d.ts.map +1 -0
  22. package/dist/pipeline/error-diagnostics.d.ts.map +1 -0
  23. package/dist/pipeline/external-keyframes.d.ts.map +1 -0
  24. package/dist/{index.d.ts → pipeline/index.d.ts} +10 -1
  25. package/dist/pipeline/index.d.ts.map +1 -0
  26. package/dist/pipeline/manifest-diagnostics.d.ts.map +1 -0
  27. package/dist/{mdx-preprocessor.d.ts → pipeline/mdx-preprocessor.d.ts} +10 -0
  28. package/dist/pipeline/mdx-preprocessor.d.ts.map +1 -0
  29. package/dist/pipeline/path-aliases.d.ts.map +1 -0
  30. package/dist/pipeline/post-process-css.d.ts.map +1 -0
  31. package/dist/pipeline/prefix.d.ts.map +1 -0
  32. package/dist/pipeline/replacement-plans.d.ts.map +1 -0
  33. package/dist/pipeline/resolve-asset.d.ts.map +1 -0
  34. package/dist/pipeline/run-analysis.d.ts.map +1 -0
  35. package/dist/pipeline/source-identity.d.ts.map +1 -0
  36. package/dist/pipeline/source-ingestion.d.ts +173 -0
  37. package/dist/pipeline/source-ingestion.d.ts.map +1 -0
  38. package/dist/pipeline/static-css.d.ts.map +1 -0
  39. package/dist/pipeline/structural-self-check.d.ts +32 -0
  40. package/dist/pipeline/structural-self-check.d.ts.map +1 -0
  41. package/dist/pipeline/svelte-source-adapter.d.ts +88 -0
  42. package/dist/pipeline/svelte-source-adapter.d.ts.map +1 -0
  43. package/dist/pipeline/system-config.d.ts.map +1 -0
  44. package/dist/{system-props-module.d.ts → pipeline/system-props-module.d.ts} +4 -3
  45. package/dist/pipeline/system-props-module.d.ts.map +1 -0
  46. package/dist/pipeline/timing-waterfall.d.ts.map +1 -0
  47. package/dist/pipeline/tsconfig-paths.d.ts.map +1 -0
  48. package/dist/pipeline/unit-fallback.d.ts.map +1 -0
  49. package/dist/pipeline/utils.d.ts.map +1 -0
  50. package/dist/pipeline/watch-keys.d.ts.map +1 -0
  51. package/dist/pipeline-lkbOoyAr.mjs +3228 -0
  52. package/dist/pipeline-ojNeABi0.cjs +3685 -0
  53. package/dist/session/extraction-session.d.ts +446 -0
  54. package/dist/session/extraction-session.d.ts.map +1 -0
  55. package/dist/session/index.d.ts +24 -0
  56. package/dist/session/index.d.ts.map +1 -0
  57. package/dist/session/published-set.d.ts +32 -0
  58. package/dist/session/published-set.d.ts.map +1 -0
  59. package/dist/session/resolve-packages.d.ts +8 -0
  60. package/dist/session/resolve-packages.d.ts.map +1 -0
  61. package/dist/session/session-paths.d.ts +131 -0
  62. package/dist/session/session-paths.d.ts.map +1 -0
  63. package/dist/session/singleton.d.ts +124 -0
  64. package/dist/session/singleton.d.ts.map +1 -0
  65. package/dist/session/timing.d.ts +7 -0
  66. package/dist/session/timing.d.ts.map +1 -0
  67. package/dist/session/turbopack-orchestrator.d.ts +43 -0
  68. package/dist/session/turbopack-orchestrator.d.ts.map +1 -0
  69. package/dist/session.cjs +2146 -0
  70. package/dist/session.mjs +2110 -0
  71. package/package.json +18 -6
  72. package/dist/analyze-project-args.d.ts.map +0 -1
  73. package/dist/assemble-stylesheet.d.ts.map +0 -1
  74. package/dist/asset-placeholders.d.ts.map +0 -1
  75. package/dist/content-hash.d.ts.map +0 -1
  76. package/dist/correlate-external-tokens.d.ts.map +0 -1
  77. package/dist/discover-files.d.ts +0 -10
  78. package/dist/discover-files.d.ts.map +0 -1
  79. package/dist/discover-packages.d.ts.map +0 -1
  80. package/dist/dynamic-prop-config.d.ts.map +0 -1
  81. package/dist/engine-adapter.d.ts.map +0 -1
  82. package/dist/engine-retirement.d.ts.map +0 -1
  83. package/dist/error-diagnostics.d.ts.map +0 -1
  84. package/dist/external-keyframes.d.ts.map +0 -1
  85. package/dist/index.d.ts.map +0 -1
  86. package/dist/manifest-diagnostics.d.ts.map +0 -1
  87. package/dist/mdx-preprocessor.d.ts.map +0 -1
  88. package/dist/path-aliases.d.ts.map +0 -1
  89. package/dist/post-process-css.d.ts.map +0 -1
  90. package/dist/prefix.d.ts.map +0 -1
  91. package/dist/replacement-plans.d.ts.map +0 -1
  92. package/dist/resolve-asset.d.ts.map +0 -1
  93. package/dist/run-analysis.d.ts.map +0 -1
  94. package/dist/source-identity.d.ts.map +0 -1
  95. package/dist/static-css.d.ts.map +0 -1
  96. package/dist/system-config.d.ts.map +0 -1
  97. package/dist/system-props-module.d.ts.map +0 -1
  98. package/dist/timing-waterfall.d.ts.map +0 -1
  99. package/dist/tsconfig-paths.d.ts.map +0 -1
  100. package/dist/unit-fallback.d.ts.map +0 -1
  101. package/dist/utils.d.ts.map +0 -1
  102. package/dist/watch-keys.d.ts.map +0 -1
  103. /package/dist/{analyze-project-args.d.ts → pipeline/analyze-project-args.d.ts} +0 -0
  104. /package/dist/{assemble-stylesheet.d.ts → pipeline/assemble-stylesheet.d.ts} +0 -0
  105. /package/dist/{asset-placeholders.d.ts → pipeline/asset-placeholders.d.ts} +0 -0
  106. /package/dist/{content-hash.d.ts → pipeline/content-hash.d.ts} +0 -0
  107. /package/dist/{correlate-external-tokens.d.ts → pipeline/correlate-external-tokens.d.ts} +0 -0
  108. /package/dist/{dynamic-prop-config.d.ts → pipeline/dynamic-prop-config.d.ts} +0 -0
  109. /package/dist/{engine-retirement.d.ts → pipeline/engine-retirement.d.ts} +0 -0
  110. /package/dist/{error-diagnostics.d.ts → pipeline/error-diagnostics.d.ts} +0 -0
  111. /package/dist/{external-keyframes.d.ts → pipeline/external-keyframes.d.ts} +0 -0
  112. /package/dist/{manifest-diagnostics.d.ts → pipeline/manifest-diagnostics.d.ts} +0 -0
  113. /package/dist/{path-aliases.d.ts → pipeline/path-aliases.d.ts} +0 -0
  114. /package/dist/{post-process-css.d.ts → pipeline/post-process-css.d.ts} +0 -0
  115. /package/dist/{prefix.d.ts → pipeline/prefix.d.ts} +0 -0
  116. /package/dist/{replacement-plans.d.ts → pipeline/replacement-plans.d.ts} +0 -0
  117. /package/dist/{resolve-asset.d.ts → pipeline/resolve-asset.d.ts} +0 -0
  118. /package/dist/{run-analysis.d.ts → pipeline/run-analysis.d.ts} +0 -0
  119. /package/dist/{source-identity.d.ts → pipeline/source-identity.d.ts} +0 -0
  120. /package/dist/{static-css.d.ts → pipeline/static-css.d.ts} +0 -0
  121. /package/dist/{system-config.d.ts → pipeline/system-config.d.ts} +0 -0
  122. /package/dist/{timing-waterfall.d.ts → pipeline/timing-waterfall.d.ts} +0 -0
  123. /package/dist/{tsconfig-paths.d.ts → pipeline/tsconfig-paths.d.ts} +0 -0
  124. /package/dist/{unit-fallback.d.ts → pipeline/unit-fallback.d.ts} +0 -0
  125. /package/dist/{utils.d.ts → pipeline/utils.d.ts} +0 -0
  126. /package/dist/{watch-keys.d.ts → pipeline/watch-keys.d.ts} +0 -0
@@ -0,0 +1,2110 @@
1
+ import { A as createSourceIngestor, B as extractSystemFilePackages, C as resolveLightningTargets, E as resolveAssetFile, G as staleDistIncludesMessage, H as firstOwners, J as createSourceIdentity, K as unresolvableIncludesMessage, N as withoutInvalidOriginals, O as findAssetSpecifiers, P as DEFAULT_EXTENSIONS, R as collectExternalPackageSources, S as postProcessCss, T as enforceExternalTokenContracts, U as isExcludedPackageRelativePath, V as findPackageRoot, X as sharesVolumeRoot, Y as isPathWithinRoot, Z as discoverFiles, _ as runProjectAnalysis, a as snapshotFilePlans, at as createExcludeMatcher, c as formatRustTimingWaterfall, f as loadSystemConfig, g as clearEngineCache, gt as assembleStylesheet, i as hashReplacementPlans, k as substituteAssetPlaceholders, l as buildSystemPropsModule, lt as mergeExternalKeyframes, m as serializeStaticCss, o as assertNoErrorDiagnostics, ot as resolveMode, pt as createV2EngineApi, q as walkPackageSources, t as toWatchKeys, ut as contentHash, yt as __require, z as excludeCollectedPackages } from "./pipeline-lkbOoyAr.mjs";
2
+ import { randomUUID } from "crypto";
3
+ import { existsSync, mkdirSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, statSync, unlinkSync, watch, writeFileSync } from "fs";
4
+ import { basename, extname, join, relative, resolve } from "path";
5
+ //#region session/session-paths.ts
6
+ /**
7
+ * Session-scoped artifact names, path derivations, and the analysis-status
8
+ * shape (openspec: next-turbopack-served-transform-coherence, design D1–D3)
9
+ * — shared by the session writer (extraction-session), the webpack
10
+ * plugin/loader, and the Turbopack loader.
11
+ *
12
+ * Deliberately free of singleton/session imports: the Turbopack loader
13
+ * executes in isolated worker processes and its module graph must stay
14
+ * worker-local (guardrail G1) — this module is pure path/shape vocabulary.
15
+ */
16
+ /** Session-dir-relative name of the replacement-epoch disk witness
17
+ * (openspec: next-webpack-served-transform-coherence, design D2;
18
+ * session-scoped by next-turbopack-served-transform-coherence D2). */
19
+ const REPLACEMENT_EPOCH_ARTIFACT = "replacements-epoch";
20
+ /** Virtual module id of the emitted system-props module — session
21
+ * vocabulary shared by the orchestrator and the Turbopack config
22
+ * assembly (hoisted here so the session home stays framework-free). */
23
+ const TURBOPACK_SYSTEM_PROPS_ID = "virtual:animus/system-props";
24
+ /** Session-dir-relative name of the analysis-commit transaction artifact
25
+ * (design D1). */
26
+ const ANALYSIS_COMMIT_ARTIFACT = "analysis-commit";
27
+ /** Session-dir-relative name of the analysis-status artifact (design D3). */
28
+ const ANALYSIS_STATUS_ARTIFACT = "analysis-status.json";
29
+ /** Session-dir-relative name of the manifest payload artifact. */
30
+ const MANIFEST_ARTIFACT = "manifest.json";
31
+ /** Session-dir-relative name of the analysis-inputs payload artifact
32
+ * (Turbopack loader-worker hydration corpus). */
33
+ const ANALYSIS_INPUTS_ARTIFACT = "analysis-inputs.json";
34
+ /** Session-dir-relative name of the emitted stylesheet artifact. */
35
+ const STYLES_ARTIFACT = "styles.css";
36
+ /** Session-dir-relative name of the emitted system-props module. */
37
+ const SYSTEM_PROPS_ARTIFACT = "system-props.js";
38
+ /** Session-dir-relative directory holding copied asset() files. */
39
+ const SESSION_ASSETS_DIR = "assets";
40
+ /** The standalone CLI's published-set commit record, written into the flat
41
+ * `.animus/` tree (openspec: standalone-extraction-cli D3). Shared here so
42
+ * the CLI writer and the session's start hygiene agree on ONE name — the
43
+ * hygiene confinement gate keys on this record, and a renamed literal on
44
+ * either side would silently re-arm deletion of the CLI's published output. */
45
+ const CLI_COMMIT_ARTIFACT = "commit.json";
46
+ /** The standalone CLI's single-writer advisory lock in the flat `.animus/`
47
+ * tree. A live holder means a CLI invocation owns that tree right now. */
48
+ const CLI_LOCK_ARTIFACT = "lock.json";
49
+ /** Root of every session-scoped artifact tree for a project. */
50
+ function sessionsRootDir(rootDir) {
51
+ return join(rootDir, ".animus", "sessions");
52
+ }
53
+ /** One session's artifact directory (design D2: session-scoped trees,
54
+ * no global pointer). */
55
+ function sessionArtifactDir(rootDir, sessionId) {
56
+ return join(sessionsRootDir(rootDir), sessionId);
57
+ }
58
+ /** Absolute path of a session's replacement-epoch artifact — the single
59
+ * derivation shared by the session writer, the webpack plugin's
60
+ * watch-ignore entry, and both loaders' file dependencies. Takes the
61
+ * SESSION directory (not the project root) since the artifact was
62
+ * relocated into the session tree. */
63
+ function replacementEpochPath(sessionDir) {
64
+ return join(sessionDir, REPLACEMENT_EPOCH_ARTIFACT);
65
+ }
66
+ /** Absolute path of a session's analysis-commit artifact. */
67
+ function analysisCommitPath(sessionDir) {
68
+ return join(sessionDir, ANALYSIS_COMMIT_ARTIFACT);
69
+ }
70
+ /** Absolute path of a session's analysis-status artifact. */
71
+ function analysisStatusPath(sessionDir) {
72
+ return join(sessionDir, ANALYSIS_STATUS_ARTIFACT);
73
+ }
74
+ /** Absolute path of a session's manifest artifact. */
75
+ function manifestPath(sessionDir) {
76
+ return join(sessionDir, MANIFEST_ARTIFACT);
77
+ }
78
+ /** Absolute path of a session's analysis-inputs artifact. */
79
+ function analysisInputsPath(sessionDir) {
80
+ return join(sessionDir, ANALYSIS_INPUTS_ARTIFACT);
81
+ }
82
+ /** Absolute path of a session's stylesheet artifact. */
83
+ function stylesPath(sessionDir) {
84
+ return join(sessionDir, STYLES_ARTIFACT);
85
+ }
86
+ /** Absolute path of a session's system-props module artifact. */
87
+ function systemPropsPath(sessionDir) {
88
+ return join(sessionDir, SYSTEM_PROPS_ARTIFACT);
89
+ }
90
+ /** Splice the session envelope into a JSON-object payload as a leading
91
+ * `__animusSession` field, byte-preserving the payload's own content
92
+ * (parse/re-stringify could reformat engine-emitted JSON). */
93
+ function envelopeJsonArtifact(payload, envelopeJson) {
94
+ const trimmed = payload.trimStart();
95
+ if (!trimmed.startsWith("{")) return payload;
96
+ if (trimmed.slice(1).trimStart().startsWith("}")) return `{"__animusSession":${envelopeJson}}`;
97
+ return `{"__animusSession":${envelopeJson},${trimmed.slice(1)}`;
98
+ }
99
+ /** Trailing-comment side-band for the CSS artifact (a leading comment
100
+ * would displace the @layer declaration consumers pin at offset 0). */
101
+ function envelopeCssArtifact(payload, envelopeJson) {
102
+ return `${payload}\n/* __animusSession ${envelopeJson} */\n`;
103
+ }
104
+ /** Matches the CSS artifact's envelope side-band. */
105
+ const ENVELOPE_CSS_COMMENT_RE = /\/\* __animusSession (\{.*\}) \*\//;
106
+ /** Envelope of a JSON artifact's bytes, or undefined when the artifact
107
+ * carries none. THROWS on unparseable bytes — callers decide whether a
108
+ * torn artifact fails closed or degrades. */
109
+ function readJsonEnvelope(bytes) {
110
+ return JSON.parse(bytes).__animusSession;
111
+ }
112
+ /** Envelope of the CSS artifact's side-band comment, or undefined when the
113
+ * side-band is absent. THROWS on an unparseable envelope body. */
114
+ function readCssEnvelope(bytes) {
115
+ const match = bytes.match(ENVELOPE_CSS_COMMENT_RE);
116
+ return match ? JSON.parse(match[1]) : void 0;
117
+ }
118
+ //#endregion
119
+ //#region session/published-set.ts
120
+ /**
121
+ * The CLI published-set contract, shared logic (openspec:
122
+ * standalone-extraction-cli D3): ONE implementation of "does this flat
123
+ * artifact set verify against its commit record" and ONE collector for the
124
+ * session's copied asset() files — consumed by the CLI writer
125
+ * (staging/verification) and the session's start hygiene (confinement
126
+ * gate). Two copies of either had already drifted once: the hygiene copy
127
+ * verified payloads as UTF-8 strings while the writer hashed raw bytes, so
128
+ * any asset-carrying set (fonts are not UTF-8) could never verify and a
129
+ * legitimately published set was classified as debris.
130
+ */
131
+ /**
132
+ * Recompute every payload hash recorded in the directory's commit record
133
+ * and compare — raw bytes on both sides, matching the writer's hashing
134
+ * domain. Returns failure lines; empty means the set verifies. An absent
135
+ * or unparsable record is itself a failure (the record is written LAST, so
136
+ * a torn or aborted publish cannot verify).
137
+ */
138
+ function verifyCommitRecord(dir) {
139
+ let record;
140
+ try {
141
+ record = JSON.parse(readFileSync(join(dir, CLI_COMMIT_ARTIFACT), "utf-8"));
142
+ } catch (error) {
143
+ return [`commit record unreadable: ${String(error)}`];
144
+ }
145
+ if (record.schema !== 1 || typeof record.payloads !== "object" || record.payloads === null) return ["commit record is not a schema-1 payload record"];
146
+ const failures = [];
147
+ for (const [name, entry] of Object.entries(record.payloads)) try {
148
+ if (contentHash(readFileSync(join(dir, name))) !== entry?.hash) failures.push(`${name}: bytes do not match the commit record`);
149
+ } catch (error) {
150
+ failures.push(`${name}: unreadable (${String(error)})`);
151
+ }
152
+ return failures;
153
+ }
154
+ /**
155
+ * Snapshot the session's copied asset() files (sorted by name) — read
156
+ * BEFORE the session tree is disposed. The emitted stylesheet references
157
+ * them as `./assets/<name>`, so every driver must publish them beside its
158
+ * stylesheet or the urls dangle.
159
+ */
160
+ function collectSessionAssets(sessionDir) {
161
+ if (!sessionDir) return [];
162
+ const dir = join(sessionDir, SESSION_ASSETS_DIR);
163
+ if (!existsSync(dir)) return [];
164
+ return readdirSync(dir).sort().map((name) => ({
165
+ name,
166
+ bytes: readFileSync(join(dir, name))
167
+ }));
168
+ }
169
+ //#endregion
170
+ //#region session/resolve-packages.ts
171
+ /**
172
+ * Resolve external DS package specifiers to rootDir-relative entry paths.
173
+ * Node-generic (no webpack APIs): Pass 1 walks the consumer's workspaces for
174
+ * matching package names; Pass 2 falls back to `require.resolve`. Specifiers
175
+ * that resolve nowhere are simply omitted (spec: silent skip).
176
+ */
177
+ function resolvePackagesByName(rootDir, names) {
178
+ if (names.length === 0) return {};
179
+ const nameSet = new Set(names);
180
+ const resolved = /* @__PURE__ */ new Set();
181
+ const packageMap = {};
182
+ try {
183
+ const rootPkg = JSON.parse(readFileSync(join(rootDir, "package.json"), "utf-8"));
184
+ const workspaces = Array.isArray(rootPkg.workspaces) ? rootPkg.workspaces : rootPkg.workspaces?.packages ?? [];
185
+ for (const ws of workspaces) {
186
+ const wsDir = resolve(rootDir, ws);
187
+ if (!existsSync(wsDir)) continue;
188
+ try {
189
+ const pkg = JSON.parse(readFileSync(join(wsDir, "package.json"), "utf-8"));
190
+ const name = pkg.name || "";
191
+ if (nameSet.has(name)) {
192
+ const entryPath = resolve(wsDir, pkg.main || pkg.module || "index.ts");
193
+ if (existsSync(entryPath)) {
194
+ packageMap[name] = relative(rootDir, entryPath);
195
+ resolved.add(name);
196
+ }
197
+ }
198
+ } catch {}
199
+ }
200
+ } catch {}
201
+ for (const name of nameSet) {
202
+ if (resolved.has(name)) continue;
203
+ try {
204
+ packageMap[name] = relative(rootDir, __require.resolve(name, { paths: [rootDir] }));
205
+ } catch {}
206
+ }
207
+ return packageMap;
208
+ }
209
+ //#endregion
210
+ //#region session/singleton.ts
211
+ /**
212
+ * Module-scope singleton for sharing analysis state between the webpack plugin and loader.
213
+ *
214
+ * Uses globalThis to survive the ESM/CJS module boundary: the plugin is loaded via ESM
215
+ * (next.config.ts import) while the loader is loaded by webpack via require(). Without
216
+ * globalThis, each module system gets its own singleton instance.
217
+ */
218
+ const MANIFEST_KEY = "__animus_manifest_json__";
219
+ const PROMISE_KEY = "__animus_analysis_promise__";
220
+ const SHARED_CSS_KEY = "__animus_shared_css__";
221
+ const SHARED_SYSTEM_PROPS_KEY = "__animus_shared_system_props__";
222
+ const SHARED_EXTERNAL_DIRS_KEY = "__animus_external_pkg_dirs__";
223
+ const SHARED_EXTERNAL_ENTRIES_KEY = "__animus_external_source_entries__";
224
+ function getManifestJson() {
225
+ return globalThis[MANIFEST_KEY];
226
+ }
227
+ function setManifestJson(json) {
228
+ globalThis[MANIFEST_KEY] = json;
229
+ }
230
+ function getAnalysisPromise() {
231
+ return globalThis[PROMISE_KEY];
232
+ }
233
+ function setAnalysisPromise(promise) {
234
+ globalThis[PROMISE_KEY] = promise;
235
+ }
236
+ function resetAnalysisPromise() {
237
+ globalThis[PROMISE_KEY] = null;
238
+ }
239
+ function getSharedCss() {
240
+ return globalThis[SHARED_CSS_KEY] || "";
241
+ }
242
+ function setSharedCss(css) {
243
+ globalThis[SHARED_CSS_KEY] = css;
244
+ }
245
+ function getSharedSystemProps() {
246
+ return globalThis[SHARED_SYSTEM_PROPS_KEY] || "";
247
+ }
248
+ function setSharedSystemProps(content) {
249
+ globalThis[SHARED_SYSTEM_PROPS_KEY] = content;
250
+ }
251
+ function getSharedExternalDirs() {
252
+ return globalThis[SHARED_EXTERNAL_DIRS_KEY] || [];
253
+ }
254
+ function setSharedExternalDirs(dirs) {
255
+ globalThis[SHARED_EXTERNAL_DIRS_KEY] = dirs;
256
+ }
257
+ function getSharedExternalEntries() {
258
+ return globalThis[SHARED_EXTERNAL_ENTRIES_KEY] || /* @__PURE__ */ new Map();
259
+ }
260
+ function setSharedExternalEntries(entries) {
261
+ globalThis[SHARED_EXTERNAL_ENTRIES_KEY] = entries;
262
+ }
263
+ /** One typed globalThis slot — the single accessor shape every
264
+ * singleton-published value shares (null when unset). */
265
+ function globalSlot(key) {
266
+ const store = globalThis;
267
+ return {
268
+ get: () => store[key] ?? null,
269
+ set: (value) => {
270
+ store[key] = value;
271
+ }
272
+ };
273
+ }
274
+ const ANALYZED_HASHES_KEY = "__animus_analyzed_hashes__";
275
+ const REPLACEMENT_EPOCH_KEY = "__animus_replacement_epoch__";
276
+ const WATCH_TRANSACTION_KEY = "__animus_watch_transaction__";
277
+ const PROCESS_SESSION_ID_KEY = "__animus_process_session_id__";
278
+ const SESSION_ARTIFACT_DIR_KEY = "__animus_session_artifact_dir__";
279
+ const OWNING_WATCH_SESSION_KEY = "__animus_owning_watch_session__";
280
+ const EXCLUSIVE_SESSION_OWNER_KEY = "__animus_exclusive_session_owner__";
281
+ const analyzedHashesSlot = globalSlot(ANALYZED_HASHES_KEY);
282
+ const replacementEpochSlot = globalSlot(REPLACEMENT_EPOCH_KEY);
283
+ const watchTransactionSlot = globalSlot(WATCH_TRANSACTION_KEY);
284
+ const sessionArtifactDirSlot = globalSlot(SESSION_ARTIFACT_DIR_KEY);
285
+ const owningWatchSessionSlot = globalSlot(OWNING_WATCH_SESSION_KEY);
286
+ /**
287
+ * The session that completed the full pipeline and holds system state — the
288
+ * only instance that can run watch analysis. Each MultiCompiler child holds
289
+ * its own session AND its own watcher with its own modified set; a
290
+ * non-owning session forwards its batch here instead of dropping it (a file
291
+ * only that compiler watches would otherwise never be analyzed).
292
+ */
293
+ function getOwningWatchSession() {
294
+ return owningWatchSessionSlot.get();
295
+ }
296
+ function setOwningWatchSession(session) {
297
+ owningWatchSessionSlot.set(session);
298
+ }
299
+ /**
300
+ * Per-file analyzed content hashes of the last published analysis (relPath →
301
+ * contentHash of the exact bytes analyzed) — the loader's witness for the
302
+ * unconditional catching-up guard (openspec:
303
+ * next-webpack-served-transform-coherence, design D4). Includes files
304
+ * analyzed with ZERO animus entries: analyzed identity is membership in the
305
+ * analysis input set, not manifest entry count.
306
+ */
307
+ function getAnalyzedHashes() {
308
+ return analyzedHashesSlot.get();
309
+ }
310
+ function setAnalyzedHashes(hashes) {
311
+ analyzedHashesSlot.set(hashes);
312
+ }
313
+ /**
314
+ * Session identity is per Next INVOCATION — one process, however many
315
+ * compiler instances it holds (openspec:
316
+ * next-turbopack-served-transform-coherence, design D2). The first
317
+ * ExtractionSession constructed in a process claims a fresh randomUUID;
318
+ * every later instance (client/server/RSC compilers each construct one)
319
+ * adopts it, so all compilers alias, watch-ignore, and publish ONE
320
+ * session-scoped artifact tree. Separate invocations (`next dev` +
321
+ * `next build` co-writing) are separate processes and therefore separate
322
+ * sessions by construction.
323
+ */
324
+ function claimProcessSessionId() {
325
+ const store = globalThis;
326
+ const existing = store[PROCESS_SESSION_ID_KEY];
327
+ if (typeof existing === "string" && existing.length > 0) return existing;
328
+ const fresh = randomUUID();
329
+ store[PROCESS_SESSION_ID_KEY] = fresh;
330
+ return fresh;
331
+ }
332
+ /**
333
+ * Exclusive-ownership claim over the process-global session state — the
334
+ * hard form of the invariant `claimProcessSessionId` documents softly. The
335
+ * shared slots above (manifest, css, artifact dir) plus the one session id
336
+ * mean two CONCURRENT drive loops in one process (a webpack MultiCompiler
337
+ * array config, parallel rollup array builds, two programmatic CLI runs)
338
+ * would share one session directory, overwrite each other's manifests, and
339
+ * delete each other's live trees on dispose. Drivers that run the loop
340
+ * exclusively (the unplugin host) claim for the build's lifetime and
341
+ * release on dispose; SEQUENTIAL claim/release cycles are legal. The Next
342
+ * multi-compiler adoption path stays the non-exclusive default. Throws
343
+ * naming both hosts and the remediation on overlap. The key lives in
344
+ * `SINGLETON_GLOBAL_KEYS`, so per-test global resets clear a leaked claim.
345
+ */
346
+ function claimExclusiveSessionOwner(label) {
347
+ const store = globalThis;
348
+ const active = store[EXCLUSIVE_SESSION_OWNER_KEY];
349
+ if (typeof active === "string") throw new Error(`[animus] a second Animus host ("${label}") started while "${active}" is still active in this process. The extraction session is process-global (one session tree, one manifest), so concurrent hosts would clobber each other's analysis. Run one Animus-enabled config per process, or make the builds sequential.`);
350
+ store[EXCLUSIVE_SESSION_OWNER_KEY] = label;
351
+ return () => {
352
+ if (store[EXCLUSIVE_SESSION_OWNER_KEY] === label) delete store[EXCLUSIVE_SESSION_OWNER_KEY];
353
+ };
354
+ }
355
+ /**
356
+ * Absolute session artifact directory of the OWNING session's last
357
+ * publication — the webpack loader's source for the session-scoped epoch
358
+ * dependency path (the loader shares the process with the pipeline; the
359
+ * Turbopack loader instead receives the directory via its options).
360
+ */
361
+ function getSessionArtifactDir() {
362
+ return sessionArtifactDirSlot.get();
363
+ }
364
+ function setSessionArtifactDir(dir) {
365
+ sessionArtifactDirSlot.set(dir);
366
+ }
367
+ /**
368
+ * Canonical replacement epoch of the last published analysis
369
+ * (`hashReplacementPlans(snapshotFilePlans(manifest), systemPropsContent)`
370
+ * — openspec: next-webpack-served-transform-coherence, design D5; the
371
+ * served system-props module rides as the served-dependency witness so
372
+ * offline system-props changes move the epoch). Published by the
373
+ * owning session AFTER the manifest so a reader that observes the epoch
374
+ * always observes at least that generation's manifest. (Session
375
+ * attribution lives on the DISK epoch artifact — no in-process mirror.)
376
+ */
377
+ function getReplacementEpoch() {
378
+ return replacementEpochSlot.get();
379
+ }
380
+ function setReplacementEpoch(epoch) {
381
+ replacementEpochSlot.set(epoch);
382
+ }
383
+ /**
384
+ * The one in-flight watch-analysis transaction (design D3): the first
385
+ * compiler entering a watch batch runs analysis + publication; every other
386
+ * compiler (client/server/RSC — each holds its own session instance) joins
387
+ * this promise instead of proceeding against a pre-transaction generation.
388
+ */
389
+ function getWatchTransaction() {
390
+ return watchTransactionSlot.get();
391
+ }
392
+ function setWatchTransaction(transaction) {
393
+ watchTransactionSlot.set(transaction);
394
+ }
395
+ const ENGINE_KEY = "__animus_engine__";
396
+ /** Engine selection travels through the singleton so non-owning compiler
397
+ * instances and the webpack loader honor the same choice as the owner. */
398
+ function setSharedEngine(engine) {
399
+ globalThis[ENGINE_KEY] = engine;
400
+ }
401
+ function getSharedEngine() {
402
+ return globalThis[ENGINE_KEY] || "v2";
403
+ }
404
+ /** Single engine choke-point for every native extraction call. Return type
405
+ * mirrors the untyped `require` the call sites previously used — the NAPI
406
+ * module's own .d.ts is the authoritative surface. */
407
+ function requireEngine() {
408
+ return __require("@animus-ui/extract");
409
+ }
410
+ const V2_ENGINE_KEY = "__animus_v2_engine__";
411
+ /**
412
+ * Engine-agnostic API over both engines (extract-v2-spine row 13). The
413
+ * v2 leg adapts the v1 function surface onto a stateful ExtractEngine
414
+ * (hoisted to `createV2EngineApi` in @animus-ui/extract/pipeline — the
415
+ * single authoritative copy shared with vite-plugin). The engine INSTANCE,
416
+ * its analyze-time sources, and the one-shot drift flag all live on
417
+ * globalThis for the same reason the manifest does — the ESM plugin and the
418
+ * CJS webpack loader must see one engine (and one drift warning) across the
419
+ * double-load. (The next-plugin is already process-singleton by design:
420
+ * manifest, css, and system props share the same globalThis keys.)
421
+ * loadSystemModule is exported by both bindings from one engine-neutral
422
+ * Rust crate, so the default path no longer loads the v1 binary.
423
+ */
424
+ const V2_SENT_SOURCES_KEY = "__animus_v2_sent_sources__";
425
+ const V2_DRIFT_WARNED_KEY = "__animus_v2_drift_warned__";
426
+ const v2EngineApi = createV2EngineApi({
427
+ label: "animus",
428
+ isV2: () => getSharedEngine() === "v2",
429
+ loadNativeEngine: requireEngine,
430
+ passThroughUnknownPaths: true,
431
+ store: {
432
+ getEngine: () => globalThis[V2_ENGINE_KEY],
433
+ setEngine: (engine) => {
434
+ globalThis[V2_ENGINE_KEY] = engine;
435
+ },
436
+ getSentSources: () => globalThis[V2_SENT_SOURCES_KEY] ?? null,
437
+ setSentSources: (sources) => {
438
+ globalThis[V2_SENT_SOURCES_KEY] = sources;
439
+ },
440
+ getDriftWarned: () => Boolean(globalThis[V2_DRIFT_WARNED_KEY]),
441
+ setDriftWarned: (value) => {
442
+ globalThis[V2_DRIFT_WARNED_KEY] = value;
443
+ }
444
+ }
445
+ });
446
+ const ENGINE_API_OVERRIDE_KEY = "__animus_engine_api_override__";
447
+ function engineApi() {
448
+ const override = globalThis[ENGINE_API_OVERRIDE_KEY];
449
+ return override ? override() : v2EngineApi();
450
+ }
451
+ //#endregion
452
+ //#region session/timing.ts
453
+ /**
454
+ * Verbose build-timing waterfall: JS phases, analysis sub-phases, and the
455
+ * shared Rust phase table. `ANIMUS_TIMING_JSON=1` additionally dumps a
456
+ * machine-readable merged record.
457
+ */
458
+ function logBuildTimings(bt, rustTiming, log, verbose) {
459
+ if (!verbose) return;
460
+ const pad = (label, width) => label + " ".repeat(Math.max(0, width - label.length));
461
+ for (const [key, label] of [
462
+ ["systemLoad", "system-load"],
463
+ ["fileDiscovery", "file-discovery"],
464
+ ["fileRead", "file-read+hash"],
465
+ ["packageResolve", "pkg-resolve"],
466
+ ["analysis", "analysis"]
467
+ ]) {
468
+ const ms = bt[key] ?? 0;
469
+ if (ms === 0 && !Object.hasOwn(bt, key)) continue;
470
+ log(` ${pad(label, 17)}${String(ms).padStart(5)}ms`);
471
+ if (key === "analysis") for (const [sk, sl] of [
472
+ ["jsonSerialize", "json-serialize"],
473
+ ["rustExtract", "rust-extract"],
474
+ ["jsonParse", "json-parse"]
475
+ ]) {
476
+ const sms = bt[sk] ?? 0;
477
+ log(` ${pad(sl, 15)}${String(sms).padStart(5)}ms`);
478
+ if (sk === "rustExtract" && rustTiming) for (const line of formatRustTimingWaterfall(rustTiming, {
479
+ indent: " ",
480
+ labelWidth: 13
481
+ })) log(line);
482
+ }
483
+ }
484
+ log(` total ${String(bt.total).padStart(5)}ms`);
485
+ if (process.env.ANIMUS_TIMING_JSON === "1") {
486
+ const merged = {};
487
+ for (const [k, v] of Object.entries(bt)) merged[`buildStart.${k}`] = v;
488
+ if (rustTiming) {
489
+ for (const [k, v] of Object.entries(rustTiming)) if (typeof v === "number") merged[`rust.${k}`] = v;
490
+ }
491
+ console.error(`[animus:timing] ${JSON.stringify(merged)}`);
492
+ }
493
+ }
494
+ //#endregion
495
+ //#region session/extraction-session.ts
496
+ /**
497
+ * Module id the Rust emitter injects for the extracted stylesheet — also the
498
+ * exact resolve.alias key with-animus registers for it, which the adapter's
499
+ * alias harvesting must skip.
500
+ */
501
+ const ANIMUS_CSS_MODULE_ID = ".animus/styles.css";
502
+ /** Retention window for sibling session directories (design D2). */
503
+ const SESSION_DIR_MAX_AGE_MS = 1440 * 60 * 1e3;
504
+ /** Watchdog added to the debounce ceiling for status deadlines (D3). */
505
+ const STATUS_WATCHDOG_MS = 2e3;
506
+ /** Flat legacy `.animus/` artifacts removed at session start — unreachable
507
+ * by session-scoped loaders. The standalone CLI still publishes the three
508
+ * payload names flat; its verified/live sets are fenced off inside
509
+ * `runSessionStartHygiene`. */
510
+ const LEGACY_FLAT_ARTIFACTS = [
511
+ MANIFEST_ARTIFACT,
512
+ ANALYSIS_INPUTS_ARTIFACT,
513
+ STYLES_ARTIFACT,
514
+ SYSTEM_PROPS_ARTIFACT,
515
+ REPLACEMENT_EPOCH_ARTIFACT,
516
+ ANALYSIS_COMMIT_ARTIFACT,
517
+ ANALYSIS_STATUS_ARTIFACT
518
+ ];
519
+ /**
520
+ * Bundler-agnostic extraction pipeline: system loading, source discovery
521
+ * and ingestion, external-package collection, analysis, stylesheet and
522
+ * system-props emission, and watch-cycle diffing.
523
+ *
524
+ * The webpack adapter (plugin.ts) owns only bundler wiring: hook
525
+ * registration, alias harvesting from the compiler config, in-memory asset
526
+ * replacement, and translating watch events into `handleWatchUpdate`
527
+ * change sets. Keeping this class free of webpack types is deliberate — a
528
+ * future Turbopack integration must drive the same session from outside
529
+ * the bundler (Turbopack has no compiler-hook surface), reusing everything
530
+ * here unchanged.
531
+ *
532
+ * Outputs are published through the package singleton (shared CSS,
533
+ * manifest, system props) and written to `.animus/` on disk.
534
+ */
535
+ var ExtractionSession = class {
536
+ /** Set by the adapter before any pipeline run. */
537
+ rootDir = null;
538
+ /** Serialized path aliases, harvested by the adapter from bundler config. */
539
+ pathAliasesJson = null;
540
+ assetCopyCache = /* @__PURE__ */ new Map();
541
+ /** Physical asset files registered with the host watcher. */
542
+ assetDependencyPaths = /* @__PURE__ */ new Set();
543
+ assetDependencyKeys = /* @__PURE__ */ new Set();
544
+ /** Emitter identity override for the system-props module id. Webpack mode
545
+ * (null) injects the absolute `.animus/system-props.js` path, resolved by
546
+ * NormalModuleReplacement; Turbopack rejects absolute-path imports, so
547
+ * its driver sets the virtual id that `resolveAlias` maps to disk. */
548
+ systemPropsModuleId = null;
549
+ /** Whether the analysis-inputs hydration corpus is serialized + written.
550
+ * False (webpack mode): the loader shares the pipeline process and reads
551
+ * the manifest from memory — the corpus is never persisted. True is set
552
+ * by the Turbopack orchestration driver, whose isolated loader workers
553
+ * replay it (spec: next-turbopack-integration, "Manifest disk artifact" /
554
+ * "Webpack mode skips the hydration corpus"). */
555
+ persistAnalysisInputs = false;
556
+ /** Absolute directory prefixes for external DS packages (loader allowlisting). */
557
+ externalPackageDirs = [];
558
+ /** Absolute package dir → owning specifier (cross-source correlation). */
559
+ externalDirOwners = {};
560
+ /** rootDir-relative external file → owning specifier (correlation join). */
561
+ externalFileOwners = {};
562
+ /** External package specifier → absolute source entry path. */
563
+ externalSourceEntries = /* @__PURE__ */ new Map();
564
+ /** SourceId derivation authority for the current generation (openspec:
565
+ * external-source-watch-ingestion, design D2) — canonical roots
566
+ * realpath'd once per full pipeline; alias→SourceId associations
567
+ * recorded while files exist so deletion resolves through the cache. */
568
+ sourceIdentity = null;
569
+ /** Canonical admitted external root → declared specifiers (set-valued
570
+ * ownership, design D2; duplicate specifiers resolving to one canonical
571
+ * root share it). Engine watch wiring and tests read this. */
572
+ externalRootOwners = /* @__PURE__ */ new Map();
573
+ /** Canonical external root → the extension set its collection walk used
574
+ * (widened for dist-only roots); rewalks and classification share it. */
575
+ externalRootExtensions = /* @__PURE__ */ new Map();
576
+ /** Canonical admitted external watch roots — the engine-side watch
577
+ * surface (webpack contextDependencies / Turbopack watchers). */
578
+ externalWatchRoots = [];
579
+ /** Canonical external root → (raw sourceKey → {raw content hash, recorded
580
+ * abs spelling}): the previous-generation inventory a dirty-root rewalk
581
+ * diffs against (design D3). Raw hashes — MDX preprocessing never skews
582
+ * the diff; the recorded abs path is a registered deletion alias, so a
583
+ * reconstructed deletion always resolves through cached identity. */
584
+ externalInventory = /* @__PURE__ */ new Map();
585
+ /** Sticky diagnostics (design D5/D7): stable key → message, re-surfaced
586
+ * on every full pipeline until the underlying condition clears. */
587
+ stickyDiagnostics = /* @__PURE__ */ new Map();
588
+ /** Volume-membership predicate for the cross-volume gate (design D5).
589
+ * Injected seam: the shared predicate only discriminates on Windows
590
+ * (win32 semantics are unit-tested via path.win32), so runtime tests
591
+ * drive the gate through this. */
592
+ sharesProjectVolume = sharesVolumeRoot;
593
+ /** Orchestrator seams (openspec: external-source-watch-ingestion, design
594
+ * D4). `onExternalRootResolved` fires per volume-admitted external root
595
+ * DURING collection — after resolution, BEFORE that root's sources are
596
+ * walked — so a watching host can open its handle with no blind gap
597
+ * between scan and watch. `onExternalRootsCommitted` fires once after a
598
+ * successful full-pipeline publication with the complete admitted
599
+ * canonical root set (the host's promote/replay/close-old phase; a
600
+ * failed pipeline never fires it, so the host rolls back). */
601
+ onExternalRootResolved = null;
602
+ onExternalRootsCommitted = null;
603
+ options;
604
+ staticCssJson;
605
+ system = null;
606
+ /** Discovery-time keyframes diagnostics awaiting the shared surfacing pass. */
607
+ externalKeyframesDiagnostics = [];
608
+ /** Full package-resolution map from the last full pipeline — replayed by
609
+ * incremental passes (sourceEntries alone omits dist-resolved packages). */
610
+ lastPackageMap = {};
611
+ fileCache = /* @__PURE__ */ new Map();
612
+ analysisEntryCache = /* @__PURE__ */ new Map();
613
+ sourceOwnership = {};
614
+ systemDependencyKeys = /* @__PURE__ */ new Set();
615
+ /** Loader-reported dependency paths for bundler watch registration. */
616
+ systemDependencyPaths = [];
617
+ systemDependencyHashes = /* @__PURE__ */ new Map();
618
+ lastSystemPropsHash = null;
619
+ /** Per-payload write guards: payloadHash gates rewrites (byte-identical
620
+ * payloads leave disk untouched); diskHash is the hash of the CURRENT
621
+ * disk bytes (envelope included) recorded in the analysis-commit. null =
622
+ * not yet seeded (first publication reads the artifact's envelope so a
623
+ * same-session restart never rewrites byte-identical artifacts). */
624
+ artifactRecords = {
625
+ manifest: null,
626
+ inputs: null,
627
+ styles: null
628
+ };
629
+ /** Last written analysis-commit; null = seeded from disk on first use. */
630
+ lastCommit = null;
631
+ /** Session identity — claimed once per PROCESS (one Next invocation),
632
+ * adopted by every subsequent session instance so all compilers share
633
+ * one artifact tree (design D2: `next dev`/`next build` co-writing are
634
+ * separate processes and therefore separate sessions). */
635
+ sessionId = claimProcessSessionId();
636
+ /** Epoch value of the last published analysis; null = not yet known
637
+ * (seeded from the session dir's artifact on first publication so a
638
+ * same-session restart with unchanged plans never rewrites bytes). */
639
+ lastEpochValue = null;
640
+ /** Watcher debounce ceiling feeding status deadlines (design D3). */
641
+ debounceCeilingMs = 75;
642
+ /** Test seam: observes every session-artifact write (name, content)
643
+ * post-rename — write ORDER is part of the transaction contract. */
644
+ onArtifactWrite = null;
645
+ /** Status attempt bookkeeping (design D3). */
646
+ statusAttemptId = 0;
647
+ statusAttemptOpen = false;
648
+ /** Monotonic first-emission witness (openspec: standalone-extraction-cli,
649
+ * watch readiness): flips true once the first complete publication
650
+ * succeeds and never regresses — every later status write (idle AND
651
+ * failed) carries it, so readiness stays observable across attempts. */
652
+ firstEmissionComplete = false;
653
+ /** Debounce-window observations pending analysis (sourceKey → hash). */
654
+ debouncePending = /* @__PURE__ */ new Map();
655
+ /** Session-start hygiene (pruning + legacy cleanup) runs once. */
656
+ sessionStartHygieneDone = false;
657
+ lcssTargets = null;
658
+ constructor(options) {
659
+ this.options = options;
660
+ this.staticCssJson = serializeStaticCss(options.staticCss);
661
+ }
662
+ /** This session's artifact directory. Requires `rootDir` to be set. */
663
+ get sessionDir() {
664
+ return sessionArtifactDir(this.rootDir, this.sessionId);
665
+ }
666
+ get verbose() {
667
+ return this.options.verbose === true || process.env.ANIMUS_DEBUG === "1" || process.env.ANIMUS_DEBUG === "true";
668
+ }
669
+ log(msg) {
670
+ if (this.verbose) console.error(`[animus] ${msg}`);
671
+ }
672
+ warn(msg) {
673
+ console.warn(`[animus] ${msg}`);
674
+ }
675
+ now() {
676
+ return this.verbose ? performance.now() : 0;
677
+ }
678
+ elapsed(t) {
679
+ return this.verbose ? Math.round(performance.now() - t) : 0;
680
+ }
681
+ /** Lazily-computed scan config (options are constructor-fixed, so the
682
+ * derivation is stable for the session's lifetime). */
683
+ /** Diagnostic prefix label — drivers set their own so a host's errors
684
+ * never masquerade as another driver's (inc 05 review S1). The default
685
+ * keeps the Next plugin's historical prefix. */
686
+ driverLabel = "animus-next";
687
+ /** Per-specifier discovery outcomes from the last full collection —
688
+ * driver-consumed reporting surface (the CLI's summary). */
689
+ lastExternalOutcomes = [];
690
+ /** Component count of the last published analysis, or null before the
691
+ * first — the CLI's publish path reads this instead of re-parsing the
692
+ * manifest JSON every cycle. */
693
+ lastComponentCount = null;
694
+ /** Driver-owned STRUCTURAL exclusions (a CLI outDir inside the root),
695
+ * joined to the never-replaceable set — never the user `exclude` list,
696
+ * whose presence would flip the replace semantics and silently drop the
697
+ * replaceable defaults. Set before the first pipeline run (the scan
698
+ * config is memoized). */
699
+ structuralExclude = [];
700
+ scanConfigMemo = null;
701
+ /** Per-pattern exclusion hit counts from this session's matcher —
702
+ * driver-consumed reporting surface (dead-pattern visibility). */
703
+ getExcludeStats() {
704
+ return this.resolveScanConfig().excludeMatcher.stats();
705
+ }
706
+ /** Resolve the scan configuration from options — the single source of the
707
+ * exclude/extension policy shared by the full and incremental pipelines. */
708
+ resolveScanConfig() {
709
+ if (this.scanConfigMemo === null) {
710
+ const extensionsSet = new Set(this.options.extensions ?? DEFAULT_EXTENSIONS);
711
+ this.scanConfigMemo = {
712
+ excludeMatcher: createExcludeMatcher(this.options.exclude, this.structuralExclude),
713
+ extensionsSet
714
+ };
715
+ }
716
+ return this.scanConfigMemo;
717
+ }
718
+ /**
719
+ * Watch entry point: one single-flight analysis transaction per event
720
+ * batch (openspec: next-webpack-served-transform-coherence, design D3).
721
+ * The first entering session runs the transaction; every concurrent
722
+ * entry — same session re-entered, or another compiler's session
723
+ * (client/server/RSC each hold their own instance) — joins the in-flight
724
+ * promise, so no compiler proceeds against a generation older than the
725
+ * one the transaction publishes. A rejected transaction rejects every
726
+ * joiner; the gate always clears.
727
+ */
728
+ async handleWatchUpdate(changes) {
729
+ const inflight = getWatchTransaction();
730
+ if (inflight) {
731
+ await inflight;
732
+ return;
733
+ }
734
+ if (!this.system) {
735
+ const owner = getOwningWatchSession();
736
+ const hasBatch = (changes.modifiedFiles?.size ?? 0) > 0 || (changes.removedFiles?.size ?? 0) > 0;
737
+ if (owner && owner !== this && hasBatch) await owner.ingestForwardedBatch(changes);
738
+ return;
739
+ }
740
+ const transaction = this.processWatchUpdate(changes);
741
+ setWatchTransaction(transaction);
742
+ try {
743
+ await transaction;
744
+ } finally {
745
+ setWatchTransaction(null);
746
+ }
747
+ }
748
+ /**
749
+ * Owner-side entry for a batch observed by a NON-OWNING compiler's
750
+ * watcher. Serializes behind any in-flight transaction, then runs the
751
+ * forwarded batch as its own transaction — never drops it (a forwarded
752
+ * batch has no other delivery; content-hash diffing makes an
753
+ * already-covered batch a cheap no-op).
754
+ */
755
+ async ingestForwardedBatch(changes) {
756
+ if (!this.system) return;
757
+ for (;;) {
758
+ const inflight = getWatchTransaction();
759
+ if (!inflight) break;
760
+ await inflight;
761
+ }
762
+ const transaction = this.processWatchUpdate(changes);
763
+ setWatchTransaction(transaction);
764
+ try {
765
+ await transaction;
766
+ } finally {
767
+ setWatchTransaction(null);
768
+ }
769
+ }
770
+ /**
771
+ * Incremental watch pass: geological reset when the system file changed,
772
+ * otherwise content-hash diffing restricted to the watcher's change sets
773
+ * (falling back to a full discovery walk when no sets are provided).
774
+ */
775
+ async processWatchUpdate(changes) {
776
+ const rootDir = this.rootDir;
777
+ try {
778
+ changes = this.reconcileExternalRoots(changes);
779
+ } catch (err) {
780
+ this.warn(`external root reconciliation failed: ${String(err)}`);
781
+ }
782
+ const changed = [...changes.modifiedFiles ?? [], ...changes.removedFiles ?? []];
783
+ let assetChanged = false;
784
+ let systemHit;
785
+ try {
786
+ if (!changes.modifiedFiles && !changes.removedFiles) for (const [dep, hash] of this.systemDependencyHashes) {
787
+ let current = "";
788
+ try {
789
+ current = contentHash(readFileSync(dep, "utf-8"));
790
+ } catch {}
791
+ if (current !== hash) {
792
+ systemHit = dep;
793
+ break;
794
+ }
795
+ }
796
+ else systemHit = changed.find((path) => toWatchKeys(path).some((key) => this.systemDependencyKeys.has(key)));
797
+ } catch (err) {
798
+ this.warn(`HMR geological-reset check failed: ${String(err)}`);
799
+ }
800
+ if (systemHit) {
801
+ this.log(`geological reset: system dependency changed (${relative(rootDir, systemHit)})`);
802
+ this.resetForHmr();
803
+ try {
804
+ const promise = this.runFullPipeline(this.pendingFromBatch(changes));
805
+ setAnalysisPromise(promise);
806
+ await promise;
807
+ } catch (err) {
808
+ try {
809
+ this.beginStatusAttempt();
810
+ this.writeAnalysisStatus("failed", this.pendingFromBatch(changes), String(err));
811
+ } catch (statusErr) {
812
+ this.warn(`failed-status write failed: ${String(statusErr)}`);
813
+ }
814
+ throw err;
815
+ }
816
+ return;
817
+ }
818
+ if (changed.some((path) => toWatchKeys(path).some((key) => this.assetDependencyKeys.has(key)))) {
819
+ this.assetCopyCache.clear();
820
+ assetChanged = true;
821
+ }
822
+ const { excludeMatcher, extensionsSet } = this.resolveScanConfig();
823
+ const priorCacheEntries = /* @__PURE__ */ new Map();
824
+ const priorExternalFileOwners = { ...this.externalFileOwners };
825
+ const recordPrior = (key) => {
826
+ if (!priorCacheEntries.has(key)) priorCacheEntries.set(key, this.fileCache.get(key) ?? null);
827
+ };
828
+ const inventoryUpdates = [];
829
+ const ownerRemovals = [];
830
+ let removedAny = false;
831
+ if (changes.removedFiles) for (const removedPath of changes.removedFiles) {
832
+ let key;
833
+ let owningRoot = null;
834
+ if (isPathWithinRoot(rootDir, removedPath)) key = relative(rootDir, removedPath);
835
+ else {
836
+ const resolved = this.sourceIdentity?.resolveDeletedSourceId(removedPath);
837
+ if (!resolved) continue;
838
+ key = resolved.sourceKey;
839
+ owningRoot = resolved.owningRoot;
840
+ }
841
+ recordPrior(key);
842
+ if (this.fileCache.delete(key)) {
843
+ removedAny = true;
844
+ if (owningRoot) {
845
+ inventoryUpdates.push({
846
+ root: owningRoot,
847
+ key,
848
+ hash: null,
849
+ abs: removedPath
850
+ });
851
+ ownerRemovals.push(key, key + ".tsx");
852
+ }
853
+ }
854
+ }
855
+ let targets;
856
+ if (changes.modifiedFiles) {
857
+ targets = [];
858
+ for (const modifiedPath of changes.modifiedFiles) {
859
+ const classified = this.classifyWatchPath(modifiedPath, {
860
+ excludeMatcher,
861
+ extensionsSet
862
+ });
863
+ if (classified) targets.push({
864
+ abs: modifiedPath,
865
+ ...classified
866
+ });
867
+ }
868
+ } else targets = discoverFiles(rootDir, rootDir, excludeMatcher, extensionsSet).map((abs) => ({
869
+ abs,
870
+ key: relative(rootDir, abs),
871
+ owningRoot: null
872
+ }));
873
+ const changedPaths = [];
874
+ for (const target of targets) {
875
+ const relPath = target.key;
876
+ let source;
877
+ try {
878
+ source = readFileSync(target.abs, "utf-8");
879
+ } catch {
880
+ continue;
881
+ }
882
+ const rawHash = contentHash(source);
883
+ const cached = this.fileCache.get(relPath);
884
+ const hash = rawHash;
885
+ if (!cached || cached.hash !== hash) {
886
+ changedPaths.push(relPath);
887
+ recordPrior(relPath);
888
+ this.fileCache.set(relPath, {
889
+ hash,
890
+ source
891
+ });
892
+ if (target.owningRoot) {
893
+ const owner = this.externalRootOwners.get(target.owningRoot)?.values().next().value;
894
+ if (owner !== void 0) this.externalFileOwners[relPath] ??= owner;
895
+ inventoryUpdates.push({
896
+ root: target.owningRoot,
897
+ key: target.key,
898
+ hash: rawHash,
899
+ abs: target.abs
900
+ });
901
+ }
902
+ }
903
+ }
904
+ if (changedPaths.length > 0 || removedAny || assetChanged) {
905
+ const pending = changedPaths.map((rel) => [rel, this.fileCache.get(rel).hash]);
906
+ let ingested;
907
+ try {
908
+ this.beginStatusAttempt();
909
+ ingested = await this.ingestAccepted();
910
+ this.externalFileOwners = this.projectExternalFileOwners(ingested, this.externalFileOwners);
911
+ resetAnalysisPromise();
912
+ const promise = this.runIncrementalPipeline(ingested.analysisEntries, pending);
913
+ setAnalysisPromise(promise);
914
+ await promise;
915
+ } catch (err) {
916
+ for (const [key, prior] of priorCacheEntries) if (prior === null) this.fileCache.delete(key);
917
+ else this.fileCache.set(key, prior);
918
+ this.externalFileOwners = priorExternalFileOwners;
919
+ if (this.statusAttemptOpen) {
920
+ this.debouncePending.clear();
921
+ this.writeAnalysisStatus("failed", pending, String(err));
922
+ }
923
+ throw err;
924
+ }
925
+ this.publishSourceIngestion(ingested);
926
+ for (const update of inventoryUpdates) {
927
+ let inventory = this.externalInventory.get(update.root);
928
+ if (!inventory) {
929
+ inventory = /* @__PURE__ */ new Map();
930
+ this.externalInventory.set(update.root, inventory);
931
+ }
932
+ if (update.hash === null) inventory.delete(update.key);
933
+ else inventory.set(update.key, {
934
+ hash: update.hash,
935
+ abs: update.abs
936
+ });
937
+ }
938
+ for (const key of ownerRemovals) delete this.externalFileOwners[key];
939
+ } else if (this.statusAttemptOpen) {
940
+ this.debouncePending.clear();
941
+ this.writeAnalysisStatus("idle", []);
942
+ }
943
+ }
944
+ /** The shared ingestion policy point (vite-plugin parity BY CODE): the
945
+ * capability guard, facts memo, and warn-dedupe lifecycle live in the
946
+ * pipeline; this host holds only its prefix, strict flag, and warn sink. */
947
+ sourceIngestor = createSourceIngestor({
948
+ engineApi: () => engineApi(),
949
+ prefix: "[animus-next]",
950
+ strict: () => !!this.options.strict,
951
+ warn: (message) => this.warn(message)
952
+ });
953
+ /** Prepare one raw-source corpus through the shared adaptation boundary. */
954
+ async ingestRawSources(entries) {
955
+ return this.sourceIngestor.ingest(entries);
956
+ }
957
+ /** Ingest and apply the shared per-file quarantine: one invalid original
958
+ * (an `.mdx` with the optional peer absent, an unsupported `.svelte`
959
+ * shape) warns and drops; the rest of the corpus still analyzes. Strict
960
+ * mode throws from the shared policy — callers route that into their own
961
+ * status/rollback handling. */
962
+ async ingestAccepted(entries) {
963
+ const ingested = await this.ingestRawSources(entries ?? this.buildRawEntriesFromCache());
964
+ return withoutInvalidOriginals(ingested, this.surfaceSourceDiagnostics(ingested.diagnostics));
965
+ }
966
+ /** Surface parser diagnostics under the shared strict/warn policy. */
967
+ surfaceSourceDiagnostics(diagnostics) {
968
+ return this.sourceIngestor.surfaceDiagnostics(diagnostics);
969
+ }
970
+ /**
971
+ * Correlate diagnostics emitted against generated children back to the
972
+ * external package owning their raw original.
973
+ */
974
+ projectExternalFileOwners(result, rawOwners) {
975
+ const projected = {};
976
+ for (const owner of Object.values(result.ownership)) {
977
+ const packageOwner = rawOwners[owner.originalPath];
978
+ if (!packageOwner) continue;
979
+ projected[owner.originalPath] = packageOwner;
980
+ for (const analysisPath of owner.analysisPaths) projected[analysisPath] = packageOwner;
981
+ }
982
+ return projected;
983
+ }
984
+ /** Publish the raw cache and complete parser projection atomically. */
985
+ publishSourceIngestion(result) {
986
+ this.sourceIngestor.markPublished(result);
987
+ this.fileCache = new Map(result.originalEntries.map((entry) => [entry.path, {
988
+ hash: entry.hash,
989
+ source: entry.source
990
+ }]));
991
+ this.analysisEntryCache = new Map(result.analysisEntries.map((entry) => [entry.path, {
992
+ hash: entry.hash,
993
+ source: entry.source
994
+ }]));
995
+ this.sourceOwnership = result.ownership;
996
+ }
997
+ async runFullPipeline(pending = []) {
998
+ const pipelineStart = this.now();
999
+ const bt = {};
1000
+ this.runSessionStartHygiene();
1001
+ setSessionArtifactDir(this.sessionDir);
1002
+ const rootDir = this.rootDir;
1003
+ const priorSourceState = this.snapshotSourceState();
1004
+ const resolvedSystemPath = resolve(rootDir, this.options.system);
1005
+ let t = this.now();
1006
+ this.system = loadSystemConfig(engineApi, {
1007
+ systemPath: resolvedSystemPath,
1008
+ rootDir,
1009
+ prefix: this.options.prefix
1010
+ });
1011
+ this.assetCopyCache.clear();
1012
+ this.assetDependencyPaths.clear();
1013
+ this.assetDependencyKeys.clear();
1014
+ {
1015
+ const deps = this.system.dependencies ?? [];
1016
+ const keys = /* @__PURE__ */ new Set();
1017
+ for (const key of toWatchKeys(resolvedSystemPath)) keys.add(key);
1018
+ for (const dep of deps) for (const key of toWatchKeys(dep)) keys.add(key);
1019
+ this.systemDependencyKeys = keys;
1020
+ this.systemDependencyPaths = deps;
1021
+ const hashes = /* @__PURE__ */ new Map();
1022
+ for (const dep of deps.length > 0 ? deps : [resolvedSystemPath]) try {
1023
+ hashes.set(dep, contentHash(readFileSync(dep, "utf-8")));
1024
+ } catch {
1025
+ hashes.set(dep, "");
1026
+ }
1027
+ this.systemDependencyHashes = hashes;
1028
+ }
1029
+ bt.systemLoad = this.elapsed(t);
1030
+ t = this.now();
1031
+ const { excludeMatcher, extensionsSet } = this.resolveScanConfig();
1032
+ const files = discoverFiles(rootDir, rootDir, excludeMatcher, extensionsSet);
1033
+ bt.fileDiscovery = this.elapsed(t);
1034
+ t = this.now();
1035
+ const rawEntries = [];
1036
+ for (const filePath of files) {
1037
+ const source = readFileSync(filePath, "utf-8");
1038
+ const relPath = relative(rootDir, filePath);
1039
+ const hash = contentHash(source);
1040
+ rawEntries.push({
1041
+ path: relPath,
1042
+ source,
1043
+ hash
1044
+ });
1045
+ }
1046
+ bt.fileRead = this.elapsed(t);
1047
+ t = this.now();
1048
+ const packageNames = extractSystemFilePackages(resolvedSystemPath);
1049
+ const preResolved = resolvePackagesByName(rootDir, packageNames);
1050
+ const rawExternalFiles = /* @__PURE__ */ new Map();
1051
+ const collected = await collectExternalPackageSources({
1052
+ specifiers: packageNames,
1053
+ resolveSpecifier: (name) => preResolved[name] ? resolve(rootDir, preResolved[name]) : null,
1054
+ rootDir,
1055
+ extensionsSet,
1056
+ hasEntry: (relPath) => rawEntries.some((e) => e.path === relPath),
1057
+ onSourceRead: (source, _relPath, absPath) => {
1058
+ rawExternalFiles.set(absPath, contentHash(source));
1059
+ },
1060
+ onUnreadable: (relPath, err) => this.warn(`skipped unreadable package file ${relPath}: ${String(err)}`),
1061
+ onPackageResolved: (_specifier, packageDir) => {
1062
+ if (!this.onExternalRootResolved) return;
1063
+ if (!this.sharesProjectVolume(rootDir, packageDir)) return;
1064
+ let canonical = packageDir;
1065
+ try {
1066
+ canonical = realpathSync(packageDir);
1067
+ } catch {}
1068
+ this.onExternalRootResolved(canonical);
1069
+ }
1070
+ });
1071
+ this.lastExternalOutcomes = collected.outcomes;
1072
+ for (const record of collected.outcomes) if (record.outcome === "empty") this.warn(`include '${record.specifier}' resolved but discovered no component sources`);
1073
+ const unresolvableMessage = unresolvableIncludesMessage(collected.outcomes);
1074
+ if (unresolvableMessage !== null) {
1075
+ if (this.options.strict) throw new Error(unresolvableMessage);
1076
+ this.warn(unresolvableMessage);
1077
+ }
1078
+ const staleDistMessage = staleDistIncludesMessage(collected.outcomes);
1079
+ if (staleDistMessage !== null) {
1080
+ if (this.options.strict) throw new Error(staleDistMessage);
1081
+ this.warn(staleDistMessage);
1082
+ }
1083
+ const rejectedSpecifiers = /* @__PURE__ */ new Set();
1084
+ const crossVolumeDetails = [];
1085
+ for (const [dir, specifiers] of Object.entries(collected.dirOwnerSets)) {
1086
+ if (this.sharesProjectVolume(rootDir, dir)) continue;
1087
+ for (const specifier of specifiers) rejectedSpecifiers.add(specifier);
1088
+ crossVolumeDetails.push(`${specifiers.join(", ")} → ${dir}`);
1089
+ }
1090
+ this.stickyDiagnostics.delete("cross-volume");
1091
+ if (rejectedSpecifiers.size > 0) {
1092
+ 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`;
1093
+ if (this.options.strict) throw new Error(`[${this.driverLabel}] ${message}`);
1094
+ this.stickyDiagnostics.set("cross-volume", message);
1095
+ }
1096
+ for (const message of this.stickyDiagnostics.values()) this.warn(message);
1097
+ const admitted = excludeCollectedPackages(collected, rejectedSpecifiers, rootDir);
1098
+ try {
1099
+ const identity = createSourceIdentity(rootDir);
1100
+ this.externalRootOwners = /* @__PURE__ */ new Map();
1101
+ this.externalRootExtensions = /* @__PURE__ */ new Map();
1102
+ for (const [dir, specifiers] of Object.entries(admitted.dirOwnerSets)) {
1103
+ const canonical = identity.registerExternalRoot(dir);
1104
+ const owners = this.externalRootOwners.get(canonical) ?? /* @__PURE__ */ new Set();
1105
+ for (const specifier of specifiers) owners.add(specifier);
1106
+ this.externalRootOwners.set(canonical, owners);
1107
+ const exts = admitted.dirExtensions[dir];
1108
+ if (exts) this.externalRootExtensions.set(canonical, new Set(exts));
1109
+ }
1110
+ this.sourceIdentity = identity;
1111
+ this.externalWatchRoots = identity.externalRoots();
1112
+ this.externalInventory = /* @__PURE__ */ new Map();
1113
+ for (const [absPath, rawHash] of rawExternalFiles) {
1114
+ const resolved = identity.resolveSourceId(absPath);
1115
+ if (!resolved?.owningRoot) continue;
1116
+ let inventory = this.externalInventory.get(resolved.owningRoot);
1117
+ if (!inventory) {
1118
+ inventory = /* @__PURE__ */ new Map();
1119
+ this.externalInventory.set(resolved.owningRoot, inventory);
1120
+ }
1121
+ inventory.set(resolved.sourceKey, {
1122
+ hash: rawHash,
1123
+ abs: absPath
1124
+ });
1125
+ }
1126
+ const packageMap = admitted.packageMap;
1127
+ this.lastPackageMap = packageMap;
1128
+ this.externalDirOwners = firstOwners(admitted.dirOwnerSets);
1129
+ this.externalFileOwners = admitted.fileOwners;
1130
+ this.externalSourceEntries = admitted.sourceEntries;
1131
+ for (const entry of admitted.entries) {
1132
+ const hash = contentHash(entry.source);
1133
+ rawEntries.push({
1134
+ path: entry.path,
1135
+ source: entry.source,
1136
+ hash
1137
+ });
1138
+ }
1139
+ this.externalPackageDirs = admitted.packageDirs;
1140
+ if (this.system && admitted.keyframesScanEntries.size > 0) {
1141
+ const api = engineApi();
1142
+ const merge = mergeExternalKeyframes((entry, root) => api.scanKeyframesExports(entry, root), this.system.keyframesJson, admitted.keyframesScanEntries.values(), this.rootDir);
1143
+ this.system.keyframesJson = merge.keyframesJson;
1144
+ this.externalKeyframesDiagnostics = merge.diagnostics;
1145
+ } else this.externalKeyframesDiagnostics = [];
1146
+ bt.packageResolve = this.elapsed(t);
1147
+ this.beginStatusAttempt();
1148
+ let accepted;
1149
+ try {
1150
+ accepted = await this.ingestAccepted(rawEntries);
1151
+ } catch (err) {
1152
+ this.debouncePending.clear();
1153
+ this.writeAnalysisStatus("failed", pending, String(err));
1154
+ throw err;
1155
+ }
1156
+ this.externalFileOwners = this.projectExternalFileOwners(accepted, this.externalFileOwners);
1157
+ bt.fileCount = accepted.analysisEntries.length;
1158
+ clearEngineCache(engineApi);
1159
+ await this.analyzeAndEmit(accepted.analysisEntries, packageMap, false, bt, pipelineStart, pending);
1160
+ this.publishSourceIngestion(accepted);
1161
+ setSharedExternalDirs(admitted.packageDirs);
1162
+ setSharedExternalEntries(admitted.sourceEntries);
1163
+ this.onExternalRootsCommitted?.(this.externalWatchRoots);
1164
+ setOwningWatchSession(this);
1165
+ } catch (err) {
1166
+ this.restoreSourceState(priorSourceState);
1167
+ throw err;
1168
+ }
1169
+ }
1170
+ /** The per-generation source state runFullPipeline mutates, captured as
1171
+ * ONE object so the restore below cannot omit a member. The three
1172
+ * deep-copied fields are the ones later steps mutate in place rather
1173
+ * than reassign; everything else is rebound wholesale on success. */
1174
+ snapshotSourceState() {
1175
+ return {
1176
+ sourceIdentity: this.sourceIdentity,
1177
+ externalRootOwners: new Map([...this.externalRootOwners].map(([root, owners]) => [root, new Set(owners)])),
1178
+ externalRootExtensions: new Map(this.externalRootExtensions),
1179
+ externalWatchRoots: [...this.externalWatchRoots],
1180
+ externalInventory: new Map([...this.externalInventory].map(([root, inventory]) => [root, new Map(inventory)])),
1181
+ lastPackageMap: this.lastPackageMap,
1182
+ externalDirOwners: this.externalDirOwners,
1183
+ externalFileOwners: this.externalFileOwners,
1184
+ externalSourceEntries: this.externalSourceEntries,
1185
+ externalPackageDirs: this.externalPackageDirs,
1186
+ externalKeyframesDiagnostics: this.externalKeyframesDiagnostics
1187
+ };
1188
+ }
1189
+ restoreSourceState(snapshot) {
1190
+ Object.assign(this, snapshot);
1191
+ }
1192
+ /**
1193
+ * Reset analysis state for HMR geological reset. Payload write guards go
1194
+ * back to null so the next publication reseeds them from the disk
1195
+ * envelopes — a byte-identical post-reset artifact is still not
1196
+ * rewritten.
1197
+ */
1198
+ resetForHmr() {
1199
+ resetAnalysisPromise();
1200
+ this.artifactRecords = {
1201
+ manifest: null,
1202
+ inputs: null,
1203
+ styles: null
1204
+ };
1205
+ this.lastSystemPropsHash = null;
1206
+ }
1207
+ /**
1208
+ * The (sourceKey, observedSourceHash) pairs of a watch batch — cheap
1209
+ * evidence for the status file's pending set on the geological-reset
1210
+ * path, where the batch's component edits ride along with the system
1211
+ * edit (design D3: loaders wait only on observed inputs).
1212
+ */
1213
+ pendingFromBatch(changes) {
1214
+ const { excludeMatcher, extensionsSet } = this.resolveScanConfig();
1215
+ const pending = [];
1216
+ for (const path of changes.modifiedFiles ?? []) {
1217
+ const classified = this.classifyWatchPath(path, {
1218
+ excludeMatcher,
1219
+ extensionsSet
1220
+ });
1221
+ if (!classified) continue;
1222
+ try {
1223
+ pending.push([classified.key, contentHash(readFileSync(path, "utf-8"))]);
1224
+ } catch {}
1225
+ }
1226
+ return pending;
1227
+ }
1228
+ /**
1229
+ * Root-dirty inventory reconciliation (design D3): partition the
1230
+ * watcher's change sets into explicit FILE events and external ROOT hits
1231
+ * (a reported path that IS an admitted root, or a directory inside one),
1232
+ * rewalk each dirty root through the shared discovery policy, diff the
1233
+ * SourceId+raw-hash inventory against the previous generation, and merge
1234
+ * the reconstructed created/edited/deleted deltas with the explicit
1235
+ * events (identity-level dedup happens downstream at the cache gate).
1236
+ * Deletion falls out of the inventory diff — webpack may report only the
1237
+ * directory (probe-proven).
1238
+ */
1239
+ reconcileExternalRoots(changes) {
1240
+ const identity = this.sourceIdentity;
1241
+ if (!identity) return changes;
1242
+ if (!changes.modifiedFiles && !changes.removedFiles) return changes;
1243
+ if (this.externalWatchRoots.length === 0) return changes;
1244
+ const { extensionsSet } = this.resolveScanConfig();
1245
+ const dirtyRoots = /* @__PURE__ */ new Set();
1246
+ const modified = /* @__PURE__ */ new Set();
1247
+ const removed = /* @__PURE__ */ new Set();
1248
+ const rootHitFor = (path) => {
1249
+ const containing = identity.containingExternalRoot(path);
1250
+ if (!containing) return null;
1251
+ try {
1252
+ return statSync(path).isDirectory() ? containing : null;
1253
+ } catch {
1254
+ return identity.resolveDeletedSourceId(path) ? null : containing;
1255
+ }
1256
+ };
1257
+ for (const path of changes.modifiedFiles ?? []) {
1258
+ const root = rootHitFor(path);
1259
+ if (root) dirtyRoots.add(root);
1260
+ else modified.add(path);
1261
+ }
1262
+ for (const path of changes.removedFiles ?? []) {
1263
+ const root = rootHitFor(path);
1264
+ if (root) dirtyRoots.add(root);
1265
+ else removed.add(path);
1266
+ }
1267
+ for (const root of dirtyRoots) {
1268
+ const previous = this.externalInventory.get(root) ?? /* @__PURE__ */ new Map();
1269
+ const seen = /* @__PURE__ */ new Set();
1270
+ const walked = walkPackageSources(root, this.externalRootExtensions.get(root) ?? extensionsSet);
1271
+ if (walked.length === 0 && previous.size > 0) this.warn(`external root rewalk found no files under ${root} while its inventory holds ${previous.size} — reconciling as full deletion`);
1272
+ for (const abs of walked) {
1273
+ const resolved = identity.resolveSourceId(abs);
1274
+ if (!resolved || resolved.owningRoot !== root) continue;
1275
+ seen.add(resolved.sourceKey);
1276
+ let rawHash;
1277
+ try {
1278
+ rawHash = contentHash(readFileSync(abs, "utf-8"));
1279
+ } catch {
1280
+ continue;
1281
+ }
1282
+ if (previous.get(resolved.sourceKey)?.hash !== rawHash) modified.add(abs);
1283
+ }
1284
+ for (const [key, entry] of previous) if (!seen.has(key)) removed.add(entry.abs);
1285
+ }
1286
+ return {
1287
+ modifiedFiles: modified,
1288
+ removedFiles: removed
1289
+ };
1290
+ }
1291
+ /**
1292
+ * Route one watcher-reported path (design D1/D2): a project-root member
1293
+ * (lexical containment — existing local semantics preserved; consumer
1294
+ * exclude patterns apply) or an admitted external member (identity
1295
+ * resolution with symlink-escape rejection; package-relative excludes
1296
+ * mirror the collection walk's filters — guardrail G1, one policy).
1297
+ * Returns null for dropped paths.
1298
+ */
1299
+ classifyWatchPath(absPath, scan) {
1300
+ const ext = extname(absPath);
1301
+ const rootDir = this.rootDir;
1302
+ if (isPathWithinRoot(rootDir, absPath)) {
1303
+ if (!scan.extensionsSet.has(ext)) return null;
1304
+ const rel = relative(rootDir, absPath);
1305
+ if (scan.excludeMatcher.matches(absPath, rel)) return null;
1306
+ return {
1307
+ key: rel,
1308
+ owningRoot: null
1309
+ };
1310
+ }
1311
+ const resolved = this.sourceIdentity?.resolveSourceId(absPath);
1312
+ if (!resolved) return null;
1313
+ if (resolved.owningRoot === null) {
1314
+ if (!scan.extensionsSet.has(ext)) return null;
1315
+ if (scan.excludeMatcher.matches(resolved.sourceKey, resolved.sourceKey)) return null;
1316
+ return {
1317
+ key: resolved.sourceKey,
1318
+ owningRoot: null
1319
+ };
1320
+ }
1321
+ if (!(this.externalRootExtensions.get(resolved.owningRoot) ?? scan.extensionsSet).has(ext)) return null;
1322
+ if (isExcludedPackageRelativePath(resolved.pathInRoot)) return null;
1323
+ return {
1324
+ key: resolved.sourceKey,
1325
+ owningRoot: resolved.owningRoot
1326
+ };
1327
+ }
1328
+ /** Build full raw originals for one shared adaptation attempt. */
1329
+ buildRawEntriesFromCache() {
1330
+ const entries = [];
1331
+ for (const [path, { hash, source }] of this.fileCache) entries.push({
1332
+ path,
1333
+ source,
1334
+ hash
1335
+ });
1336
+ return entries;
1337
+ }
1338
+ /**
1339
+ * Run incremental pipeline with cache-aware file entries.
1340
+ * Reuses system config from the last full pipeline run.
1341
+ */
1342
+ async runIncrementalPipeline(fileEntries, pending = []) {
1343
+ const bt = {};
1344
+ const pipelineStart = this.now();
1345
+ await this.analyzeAndEmit(fileEntries, this.lastPackageMap, true, bt, pipelineStart, pending);
1346
+ }
1347
+ /**
1348
+ * Shared analysis + emit core for both pipelines — the single call site
1349
+ * that routes every manifest through the shared `runProjectAnalysis`,
1350
+ * reachable from both runFullPipeline (production) and
1351
+ * runIncrementalPipeline (HMR).
1352
+ *
1353
+ * Owns diagnostic surfacing, CSS assembly + styles.css write guard,
1354
+ * system-props module emit, and the timing log. The engine's own
1355
+ * `dev_mode` (reconciliation pruning) is derived separately via
1356
+ * `engineDevMode` — an explicit `mode` option overrides the pipeline
1357
+ * path there. For everything else the `devMode` flag is the ONLY
1358
+ * behavioral fork:
1359
+ *
1360
+ * - `false` (production): computes bt.analysis + logs the extraction
1361
+ * report, and writes system-props.js UNCONDITIONALLY (no
1362
+ * lastSystemPropsHash guard).
1363
+ * - `true` (HMR): skips the report log, and guards the system-props.js
1364
+ * write by lastSystemPropsHash.
1365
+ *
1366
+ * The disk artifacts land under the session directory in transaction
1367
+ * order (design D1): manifest → analysis-inputs (Turbopack orchestration
1368
+ * only) → styles.css → system-props → analysis-commit →
1369
+ * replacements-epoch (last, only when moved). The analysis-status file walks starting → analyzing →
1370
+ * committing → idle around the attempt, landing in `failed` (with the
1371
+ * diagnostic) on any throw (design D3).
1372
+ */
1373
+ async analyzeAndEmit(fileEntries, packageMap, devMode, bt, pipelineStart, pending = []) {
1374
+ this.beginStatusAttempt();
1375
+ this.debouncePending.clear();
1376
+ this.writeAnalysisStatus("starting", pending);
1377
+ try {
1378
+ await this.analyzeAndEmitAttempt(fileEntries, packageMap, devMode, bt, pipelineStart, pending);
1379
+ this.firstEmissionComplete = true;
1380
+ this.writeAnalysisStatus("idle", []);
1381
+ } catch (err) {
1382
+ this.writeAnalysisStatus("failed", pending, String(err));
1383
+ throw err;
1384
+ }
1385
+ }
1386
+ /**
1387
+ * The engine's `dev_mode` flag (retain all components vs reconciliation
1388
+ * pruning) is an EMISSION decision, so an explicit `mode` option wins over
1389
+ * the pipeline path (core-options: `mode` "decides emitted bytes …
1390
+ * engine devMode"). Without an explicit mode the historical per-pipeline
1391
+ * default applies: full = production pruning, incremental = dev retention.
1392
+ * A pinned-production watch must not flip to unpruned CSS on its first
1393
+ * incremental republication, and a pinned-development full build must
1394
+ * retain all components.
1395
+ */
1396
+ engineDevMode(pipelineDefault) {
1397
+ if (this.options.mode !== void 0) return this.options.mode === "development";
1398
+ return pipelineDefault;
1399
+ }
1400
+ async analyzeAndEmitAttempt(fileEntries, packageMap, devMode, bt, pipelineStart, pending) {
1401
+ const system = this.system;
1402
+ const analysisOptions = {
1403
+ fileEntries,
1404
+ packageMap,
1405
+ system,
1406
+ emitter: {
1407
+ runtimeImport: "@animus-ui/system/runtime",
1408
+ cssModuleId: ANIMUS_CSS_MODULE_ID,
1409
+ systemPropsModuleId: this.systemPropsModuleId ?? systemPropsPath(this.sessionDir)
1410
+ },
1411
+ pathAliasesJson: this.pathAliasesJson,
1412
+ staticCssJson: this.staticCssJson,
1413
+ externalDirs: this.externalPackageDirs.map((dir) => relative(this.rootDir, dir)),
1414
+ devMode: this.engineDevMode(devMode)
1415
+ };
1416
+ this.writeAnalysisStatus("analyzing", pending);
1417
+ const result = runProjectAnalysis(engineApi, {
1418
+ ...analysisOptions,
1419
+ warn: (message) => this.warn(message),
1420
+ strict: this.options.strict,
1421
+ extraDiagnostics: this.externalKeyframesDiagnostics
1422
+ });
1423
+ assertNoErrorDiagnostics(result.manifest?.diagnostics);
1424
+ enforceExternalTokenContracts({
1425
+ diagnostics: result.manifest?.diagnostics,
1426
+ fileOwners: this.externalFileOwners,
1427
+ dirOwners: this.externalDirOwners,
1428
+ sourceThemeManifestsJson: system.sourceThemeManifestsJson,
1429
+ strict: this.options.strict,
1430
+ prefix: `[${this.driverLabel}]`,
1431
+ warn: (message) => this.warn(message)
1432
+ });
1433
+ bt.jsonSerialize = result.timings.serializeMs;
1434
+ bt.rustExtract = result.timings.extractMs;
1435
+ bt.jsonParse = result.timings.parseMs;
1436
+ const manifest = result.manifest;
1437
+ this.lastComponentCount = Object.keys(manifest?.components ?? {}).length;
1438
+ if (!devMode) {
1439
+ bt.analysis = (bt.jsonSerialize ?? 0) + (bt.rustExtract ?? 0) + (bt.jsonParse ?? 0);
1440
+ if (manifest?.report) this.log(`Extracted ${manifest.report.components_extracted ?? "?"}/${manifest.report.components_total ?? "?"} components (${bt.analysis}ms)`);
1441
+ }
1442
+ const globalCss = this.substituteAssetReferences(result.globalCss, devMode);
1443
+ const { declaration, variables, body } = assembleStylesheet({
1444
+ layers: this.options.layers,
1445
+ variableCss: system.variableCss,
1446
+ globalCss,
1447
+ componentCss: result.componentCss,
1448
+ split: true
1449
+ });
1450
+ if (this.lcssTargets === null) this.lcssTargets = resolveLightningTargets(this.options.targets, this.rootDir);
1451
+ const fullCss = [
1452
+ declaration,
1453
+ variables,
1454
+ postProcessCss(body, {
1455
+ minify: this.options.minify ?? resolveMode(this.options.mode, () => process.env.NODE_ENV === "production" ? "production" : "development").mode === "production",
1456
+ targets: this.lcssTargets,
1457
+ warnFn: (msg) => this.warn(msg)
1458
+ })
1459
+ ].filter(Boolean).join("\n");
1460
+ setSharedCss(fullCss);
1461
+ const systemPropsContent = buildSystemPropsModule({
1462
+ systemPropMapJson: JSON.stringify(manifest?.system_prop_map ?? {}),
1463
+ groupRegistryJson: system.groupRegistryJson,
1464
+ dynamicProps: manifest?.dynamic_props ?? {}
1465
+ });
1466
+ setSharedSystemProps(systemPropsContent);
1467
+ setManifestJson(result.manifestJson);
1468
+ setAnalyzedHashes(new Map(fileEntries.map((entry) => [entry.path, entry.hash])));
1469
+ this.writeAnalysisStatus("committing", pending);
1470
+ const epoch = hashReplacementPlans(snapshotFilePlans(manifest), systemPropsContent);
1471
+ if (this.lastCommit === null) this.lastCommit = this.seedCommitFromDisk();
1472
+ const generation = (this.lastCommit?.generation ?? 0) + 1;
1473
+ this.publishPayloadArtifact("manifest", MANIFEST_ARTIFACT, result.manifestJson, epoch, generation, envelopeJsonArtifact);
1474
+ if (this.persistAnalysisInputs) this.publishPayloadArtifact("inputs", ANALYSIS_INPUTS_ARTIFACT, JSON.stringify({
1475
+ analyzedHashes: Object.fromEntries(fileEntries.map((entry) => [entry.path, entry.hash])),
1476
+ ...result.inputs
1477
+ }), epoch, generation, envelopeJsonArtifact);
1478
+ this.publishPayloadArtifact("styles", STYLES_ARTIFACT, fullCss, epoch, generation, envelopeCssArtifact);
1479
+ if (devMode) {
1480
+ const systemPropsHash = contentHash(systemPropsContent);
1481
+ if (systemPropsHash !== this.lastSystemPropsHash) {
1482
+ this.writeSessionArtifact(SYSTEM_PROPS_ARTIFACT, systemPropsContent);
1483
+ this.lastSystemPropsHash = systemPropsHash;
1484
+ }
1485
+ } else this.writeSessionArtifact(SYSTEM_PROPS_ARTIFACT, systemPropsContent);
1486
+ this.publishAnalysisCommit(epoch, generation);
1487
+ this.publishReplacementEpoch(epoch);
1488
+ bt.total = this.elapsed(pipelineStart);
1489
+ logBuildTimings(bt, manifest?.timing, (msg) => this.log(msg), this.verbose);
1490
+ }
1491
+ /** Open a status attempt (attemptId increments once per burst — a
1492
+ * debouncing pre-write and the analysis that follows share one id). */
1493
+ beginStatusAttempt() {
1494
+ if (!this.statusAttemptOpen) {
1495
+ this.statusAttemptId += 1;
1496
+ this.statusAttemptOpen = true;
1497
+ }
1498
+ }
1499
+ /** Write the session's analysis-status artifact (design D3). Terminal
1500
+ * states (idle/failed) close the attempt. */
1501
+ writeAnalysisStatus(state, pending, diagnostic) {
1502
+ const status = {
1503
+ schema: 2,
1504
+ sessionId: this.sessionId,
1505
+ attemptId: this.statusAttemptId,
1506
+ state,
1507
+ pending,
1508
+ deadlineAt: Date.now() + this.debounceCeilingMs + STATUS_WATCHDOG_MS,
1509
+ ...diagnostic !== void 0 ? { diagnostic } : {},
1510
+ ready: this.firstEmissionComplete
1511
+ };
1512
+ this.writeSessionArtifact(ANALYSIS_STATUS_ARTIFACT, JSON.stringify(status));
1513
+ if (state === "idle" || state === "failed") this.statusAttemptOpen = false;
1514
+ }
1515
+ /**
1516
+ * Orchestrator seam (Turbopack watcher): record watch events observed
1517
+ * during the debounce window so a loader running ahead of the analysis
1518
+ * has positive evidence to wait on (design D3 'debouncing'). Paths are
1519
+ * filtered by the scan config and hashed at observation time.
1520
+ */
1521
+ noteDebouncedWatchEvents(absPaths) {
1522
+ if (!this.rootDir) return;
1523
+ const additions = this.pendingFromBatch({ modifiedFiles: new Set(absPaths) });
1524
+ if (additions.length === 0) return;
1525
+ this.beginStatusAttempt();
1526
+ for (const [key, hash] of additions) this.debouncePending.set(key, hash);
1527
+ if (this.debounceStatusWriteScheduled) return;
1528
+ this.debounceStatusWriteScheduled = true;
1529
+ queueMicrotask(() => {
1530
+ this.debounceStatusWriteScheduled = false;
1531
+ if (this.debouncePending.size === 0) return;
1532
+ try {
1533
+ this.writeAnalysisStatus("debouncing", [...this.debouncePending.entries()]);
1534
+ } catch (err) {
1535
+ this.warn(`debounce status write failed: ${String(err)}`);
1536
+ }
1537
+ });
1538
+ }
1539
+ /** One pending microtask flushes a burst of debounce observations. */
1540
+ debounceStatusWriteScheduled = false;
1541
+ /**
1542
+ * Write one payload artifact into the session directory, enveloped with
1543
+ * `{sessionId, generation, replacementEpoch, payloadHash}` and rewritten
1544
+ * only when the PAYLOAD bytes changed (byte-identical re-analyses leave
1545
+ * disk untouched — spec: "Unchanged manifest is not rewritten"). The
1546
+ * recorded diskHash (hash of the enveloped bytes) feeds the
1547
+ * analysis-commit.
1548
+ */
1549
+ publishPayloadArtifact(key, name, payload, epoch, generation, wrap) {
1550
+ const payloadHash = contentHash(payload);
1551
+ if (this.artifactRecords[key] === null) this.artifactRecords[key] = this.seedPayloadRecord(key, name);
1552
+ const record = this.artifactRecords[key];
1553
+ if (record !== null && record.payloadHash === payloadHash) return;
1554
+ const envelope = {
1555
+ sessionId: this.sessionId,
1556
+ generation,
1557
+ replacementEpoch: epoch,
1558
+ payloadHash
1559
+ };
1560
+ const bytes = wrap(payload, JSON.stringify(envelope));
1561
+ this.writeSessionArtifact(name, bytes);
1562
+ this.artifactRecords[key] = {
1563
+ payloadHash,
1564
+ diskHash: contentHash(bytes)
1565
+ };
1566
+ }
1567
+ /** Reconstruct a payload write guard from the on-disk artifact's envelope
1568
+ * (same-session restart: a byte-identical payload must not rewrite). */
1569
+ seedPayloadRecord(key, name) {
1570
+ let bytes;
1571
+ try {
1572
+ bytes = readFileSync(join(this.sessionDir, name), "utf-8");
1573
+ } catch {
1574
+ return null;
1575
+ }
1576
+ let envelope;
1577
+ try {
1578
+ envelope = key === "styles" ? readCssEnvelope(bytes) : readJsonEnvelope(bytes);
1579
+ } catch {
1580
+ return null;
1581
+ }
1582
+ if (!envelope || typeof envelope.payloadHash !== "string") return null;
1583
+ return {
1584
+ payloadHash: envelope.payloadHash,
1585
+ diskHash: contentHash(bytes)
1586
+ };
1587
+ }
1588
+ /** Last analysis-commit persisted in this session's directory, or null. */
1589
+ seedCommitFromDisk() {
1590
+ try {
1591
+ const parsed = JSON.parse(readFileSync(analysisCommitPath(this.sessionDir), "utf-8"));
1592
+ return parsed.schema === 1 && parsed.sessionId === this.sessionId && typeof parsed.generation === "number" ? parsed : null;
1593
+ } catch {
1594
+ return null;
1595
+ }
1596
+ }
1597
+ /**
1598
+ * Publish the analysis-commit — the transaction identity (design D1).
1599
+ * Written AFTER every payload and BEFORE the epoch; skipped entirely when
1600
+ * the payload set (disk hashes) and epoch are unchanged, so a no-op
1601
+ * re-analysis neither re-keys loader-worker hydration nor burns a
1602
+ * generation.
1603
+ */
1604
+ publishAnalysisCommit(epoch, generation) {
1605
+ const manifestHash = this.artifactRecords.manifest?.diskHash ?? "";
1606
+ const inputsHash = this.persistAnalysisInputs ? this.artifactRecords.inputs?.diskHash ?? "" : void 0;
1607
+ const stylesHash = this.artifactRecords.styles?.diskHash ?? "";
1608
+ const prev = this.lastCommit;
1609
+ if (prev !== null && prev.manifestHash === manifestHash && prev.inputsHash === inputsHash && prev.stylesHash === stylesHash && prev.replacementEpoch === epoch) return;
1610
+ const commit = {
1611
+ schema: 1,
1612
+ sessionId: this.sessionId,
1613
+ generation,
1614
+ replacementEpoch: epoch,
1615
+ manifestHash,
1616
+ ...inputsHash !== void 0 ? { inputsHash } : {},
1617
+ stylesHash
1618
+ };
1619
+ this.writeSessionArtifact(ANALYSIS_COMMIT_ARTIFACT, JSON.stringify(commit));
1620
+ this.lastCommit = commit;
1621
+ }
1622
+ /**
1623
+ * Publish the canonical replacement epoch: maintain the session-scoped
1624
+ * disk witness `{schema, sessionId, epoch}`, rewritten ONLY when the
1625
+ * epoch VALUE changes so style-only analyses and same-session restarts
1626
+ * leave bytes and mtime untouched, then expose the value through the
1627
+ * singleton for the plugin's needBuild fan-out and the loader's catch-up
1628
+ * re-check. Every VALUE move also reconciles sibling sessions' epoch
1629
+ * artifacts (below) — the webpack cold-cache validity witness.
1630
+ */
1631
+ publishReplacementEpoch(epoch) {
1632
+ const onDisk = this.diskEpochValue();
1633
+ if (this.lastEpochValue === null) this.lastEpochValue = onDisk;
1634
+ if (epoch !== onDisk) this.writeSessionArtifact(REPLACEMENT_EPOCH_ARTIFACT, JSON.stringify({
1635
+ schema: 1,
1636
+ sessionId: this.sessionId,
1637
+ epoch
1638
+ }));
1639
+ if (epoch !== this.lastEpochValue) {
1640
+ this.lastEpochValue = epoch;
1641
+ this.reconcileSiblingEpochs(epoch);
1642
+ }
1643
+ setReplacementEpoch(epoch);
1644
+ }
1645
+ /**
1646
+ * Sibling epoch reconciliation — the cross-session half of the webpack
1647
+ * persistent-cache witness (spec: dev-served-transform-coherence,
1648
+ * "Offline change invalidates restored modules"). Restored-module
1649
+ * snapshots reference the epoch artifact of the session that BUILT them;
1650
+ * with session-scoped trees that file would otherwise sit untouched
1651
+ * forever, keeping stale snapshots valid. Whenever this session's epoch
1652
+ * value moves, delete every sibling epoch artifact that disagrees (their
1653
+ * snapshots must invalidate — restore-on-demand then rebuilds from the
1654
+ * current generation) and leave agreeing siblings byte-untouched (warm
1655
+ * restores stay valid). Deleting a stale artifact is pruning, not a
1656
+ * foreign-session write; races with concurrent sessions are tolerated
1657
+ * (S14).
1658
+ */
1659
+ /** Sibling ids already reconciled away (artifact deleted or absent) —
1660
+ * nothing left to invalidate for them on later moves. */
1661
+ reconciledSiblingIds = /* @__PURE__ */ new Set();
1662
+ /** sessions-root listing memo, keyed by the root dir's mtime — a new or
1663
+ * pruned sibling DIRECTORY moves it; agreeing siblings stay listed. */
1664
+ siblingListing = null;
1665
+ reconcileSiblingEpochs(epoch) {
1666
+ const rootPath = sessionsRootDir(this.rootDir);
1667
+ let entries;
1668
+ try {
1669
+ const mtimeMs = statSync(rootPath).mtimeMs;
1670
+ if (this.siblingListing?.mtimeMs === mtimeMs) entries = this.siblingListing.entries;
1671
+ else {
1672
+ entries = readdirSync(rootPath);
1673
+ this.siblingListing = {
1674
+ mtimeMs,
1675
+ entries
1676
+ };
1677
+ }
1678
+ } catch {
1679
+ return;
1680
+ }
1681
+ for (const entry of entries) {
1682
+ if (entry === this.sessionId) continue;
1683
+ if (this.reconciledSiblingIds.has(entry)) continue;
1684
+ const siblingEpochPath = join(rootPath, entry, REPLACEMENT_EPOCH_ARTIFACT);
1685
+ try {
1686
+ if (JSON.parse(readFileSync(siblingEpochPath, "utf-8")).epoch === epoch) continue;
1687
+ } catch (err) {
1688
+ if (err?.code === "ENOENT") {
1689
+ this.reconciledSiblingIds.add(entry);
1690
+ continue;
1691
+ }
1692
+ }
1693
+ try {
1694
+ unlinkSync(siblingEpochPath);
1695
+ } catch {}
1696
+ this.reconciledSiblingIds.add(entry);
1697
+ }
1698
+ }
1699
+ /** Epoch value held by this session's on-disk artifact, or null when
1700
+ * absent, unreadable, or not the expected schema. */
1701
+ diskEpochValue() {
1702
+ try {
1703
+ const parsed = JSON.parse(readFileSync(replacementEpochPath(this.sessionDir), "utf-8"));
1704
+ return parsed.schema === 1 && typeof parsed.epoch === "string" ? parsed.epoch : null;
1705
+ } catch {
1706
+ return null;
1707
+ }
1708
+ }
1709
+ /** True when the flat `.animus/` advisory lock names a live pid — a CLI
1710
+ * invocation (build mid-publish, or a whole watch run) owns the flat
1711
+ * tree right now, and any instantaneous inconsistency is its in-flight
1712
+ * write, not debris. */
1713
+ cliWriterHoldsLock(animusDir) {
1714
+ let holder;
1715
+ try {
1716
+ holder = JSON.parse(readFileSync(join(animusDir, CLI_LOCK_ARTIFACT), "utf-8"));
1717
+ } catch {
1718
+ return false;
1719
+ }
1720
+ if (typeof holder.pid !== "number") return false;
1721
+ try {
1722
+ process.kill(holder.pid, 0);
1723
+ return true;
1724
+ } catch {
1725
+ return false;
1726
+ }
1727
+ }
1728
+ /** Session-start hygiene (design D2): delete legacy flat artifacts
1729
+ * (unreachable by session-scoped loaders; the standalone CLI is the one
1730
+ * remaining writer of flat payload names, and its live output is
1731
+ * fenced off below) and prune sibling session directories older than
1732
+ * the retention window — never the own dir, tolerating races with
1733
+ * concurrently-pruning sessions (S14). */
1734
+ runSessionStartHygiene() {
1735
+ if (this.sessionStartHygieneDone) return;
1736
+ this.sessionStartHygieneDone = true;
1737
+ const animusDir = join(this.rootDir, ".animus");
1738
+ const isCliPublishedSet = this.cliWriterHoldsLock(animusDir) || verifyCommitRecord(animusDir).length === 0;
1739
+ const cliPublishedNames = [
1740
+ MANIFEST_ARTIFACT,
1741
+ STYLES_ARTIFACT,
1742
+ SYSTEM_PROPS_ARTIFACT
1743
+ ];
1744
+ for (const name of LEGACY_FLAT_ARTIFACTS) {
1745
+ if (isCliPublishedSet && cliPublishedNames.includes(name)) continue;
1746
+ try {
1747
+ unlinkSync(join(animusDir, name));
1748
+ } catch {}
1749
+ }
1750
+ if (!isCliPublishedSet) try {
1751
+ unlinkSync(join(animusDir, CLI_COMMIT_ARTIFACT));
1752
+ } catch {}
1753
+ let entries;
1754
+ try {
1755
+ entries = readdirSync(sessionsRootDir(this.rootDir));
1756
+ } catch {
1757
+ return;
1758
+ }
1759
+ const cutoff = Date.now() - SESSION_DIR_MAX_AGE_MS;
1760
+ for (const entry of entries) {
1761
+ if (entry === this.sessionId) continue;
1762
+ const dir = join(sessionsRootDir(this.rootDir), entry);
1763
+ try {
1764
+ if (statSync(dir).mtimeMs < cutoff) rmSync(dir, {
1765
+ recursive: true,
1766
+ force: true
1767
+ });
1768
+ } catch {}
1769
+ }
1770
+ }
1771
+ /** Ensure the session directory exists and write one artifact into it.
1772
+ * Write-then-rename so cross-process readers (Turbopack loader workers)
1773
+ * can never observe a torn half-written file. The tmp name carries the
1774
+ * pid — Next dev evaluates the config in more than one process, and two
1775
+ * sessions writing the same artifact must not race on one tmp path. */
1776
+ writeSessionArtifact(name, content) {
1777
+ const dir = this.sessionDir;
1778
+ mkdirSync(dir, { recursive: true });
1779
+ const tmpPath = join(dir, `.${name}.${process.pid}.tmp`);
1780
+ writeFileSync(tmpPath, content);
1781
+ renameSync(tmpPath, join(dir, name));
1782
+ this.onArtifactWrite?.(name, content);
1783
+ }
1784
+ /**
1785
+ * asset() placeholder substitution (global-styles-system): resolve each
1786
+ * referenced specifier through Node resolution, copy the bytes into the
1787
+ * session directory's `assets/` under a content-hashed name, and
1788
+ * substitute a RELATIVE url — relative to the session-scoped styles.css,
1789
+ * which sits beside `assets/`, so the emitted `./assets/<file>` form is
1790
+ * unchanged. The stylesheet is processed by Next's own CSS pipeline
1791
+ * (webpack and Turbopack alike), which applies its native asset handling
1792
+ * — publicPath and output hashing — to relative url() references.
1793
+ * Unsubstitutable specifiers warn and emit literally in non-strict mode,
1794
+ * fail the build under `strict: true`.
1795
+ */
1796
+ substituteAssetReferences(globalCss, devMode) {
1797
+ const specifiers = findAssetSpecifiers(globalCss);
1798
+ const assetsDir = join(this.sessionDir, SESSION_ASSETS_DIR);
1799
+ const expected = /* @__PURE__ */ new Set();
1800
+ this.assetDependencyPaths.clear();
1801
+ this.assetDependencyKeys.clear();
1802
+ const urlBySpecifier = /* @__PURE__ */ new Map();
1803
+ for (const specifier of specifiers) {
1804
+ const cached = this.assetCopyCache.get(specifier);
1805
+ if (cached && existsSync(join(assetsDir, cached.fileName))) try {
1806
+ const current = statSync(cached.sourcePath);
1807
+ if (current.mtimeMs === cached.mtimeMs && current.size === cached.size) {
1808
+ this.trackAssetDependency(cached.sourcePath);
1809
+ expected.add(cached.fileName);
1810
+ urlBySpecifier.set(specifier, cached.url);
1811
+ continue;
1812
+ }
1813
+ } catch {}
1814
+ const resolvedPath = this.resolveAssetSpecifier(specifier);
1815
+ if (!resolvedPath) {
1816
+ const message = `unresolvable asset() specifier: ${specifier}`;
1817
+ if (this.options.strict) throw new Error(`[${this.driverLabel}] ${message}`);
1818
+ this.warn(message);
1819
+ urlBySpecifier.set(specifier, specifier);
1820
+ continue;
1821
+ }
1822
+ const bytes = readFileSync(resolvedPath);
1823
+ const sourceStat = statSync(resolvedPath);
1824
+ this.trackAssetDependency(resolvedPath);
1825
+ const ext = extname(resolvedPath);
1826
+ const fileName = `${basename(resolvedPath, ext)}.${contentHash(bytes).slice(0, 8)}${ext}`;
1827
+ expected.add(fileName);
1828
+ if (!existsSync(assetsDir)) mkdirSync(assetsDir, { recursive: true });
1829
+ const assetPath = join(assetsDir, fileName);
1830
+ if (!existsSync(assetPath)) writeFileSync(assetPath, bytes);
1831
+ const url = `./${SESSION_ASSETS_DIR}/${fileName}`;
1832
+ urlBySpecifier.set(specifier, url);
1833
+ this.assetCopyCache.set(specifier, {
1834
+ sourcePath: resolvedPath,
1835
+ mtimeMs: sourceStat.mtimeMs,
1836
+ size: sourceStat.size,
1837
+ fileName,
1838
+ url
1839
+ });
1840
+ }
1841
+ if (!devMode) pruneStaleAssets(assetsDir, expected);
1842
+ return substituteAssetPlaceholders(globalCss, urlBySpecifier);
1843
+ }
1844
+ trackAssetDependency(path) {
1845
+ this.assetDependencyPaths.add(path);
1846
+ for (const key of toWatchKeys(path)) this.assetDependencyKeys.add(key);
1847
+ }
1848
+ /**
1849
+ * Resolve an asset specifier to an absolute file via the shared pipeline
1850
+ * resolver (host aliases → Node resolution → package root), with one
1851
+ * session-local last resort: an already-discovered source entry's package
1852
+ * root (dist-less workspace kits the shared resolver cannot see).
1853
+ */
1854
+ resolveAssetSpecifier(specifier) {
1855
+ const resolved = resolveAssetFile(specifier, this.rootDir, this.pathAliasesJson);
1856
+ if (resolved) return resolved;
1857
+ const segments = specifier.split("/");
1858
+ const packageName = specifier.startsWith("@") ? segments.slice(0, 2).join("/") : segments[0];
1859
+ const subpath = specifier.slice(packageName.length + 1);
1860
+ if (!subpath) return null;
1861
+ const sourceEntry = this.externalSourceEntries.get(packageName) ?? [...this.externalSourceEntries].find(([declared]) => declared === packageName || declared.startsWith(`${packageName}/`))?.[1];
1862
+ if (sourceEntry) {
1863
+ const candidate = join(findPackageRoot(sourceEntry), subpath);
1864
+ if (existsSync(candidate)) return candidate;
1865
+ }
1866
+ return null;
1867
+ }
1868
+ };
1869
+ /**
1870
+ * Sync `.animus/assets/` to the current build's content-hashed file set:
1871
+ * anything else in the directory is a superseded revision (the copies are
1872
+ * content-addressed and never overwritten) or the leftover of an asset()
1873
+ * reference that no longer exists. Failures are tolerated per entry — Next
1874
+ * dev evaluates the config in more than one process, and a concurrent
1875
+ * session may have removed (or be about to rewrite) the same file; every
1876
+ * pass rewrites whatever of its own set is missing, so races self-heal.
1877
+ */
1878
+ function pruneStaleAssets(assetsDir, expected) {
1879
+ if (!existsSync(assetsDir)) return;
1880
+ let entries;
1881
+ try {
1882
+ entries = readdirSync(assetsDir);
1883
+ } catch {
1884
+ return;
1885
+ }
1886
+ for (const entry of entries) {
1887
+ if (expected.has(entry)) continue;
1888
+ try {
1889
+ unlinkSync(join(assetsDir, entry));
1890
+ } catch {}
1891
+ }
1892
+ }
1893
+ //#endregion
1894
+ //#region session/turbopack-orchestrator.ts
1895
+ /**
1896
+ * Out-of-band pipeline orchestration for Turbopack (spec:
1897
+ * next-turbopack-integration). Turbopack exposes no compiler hooks, so the
1898
+ * pipeline runs during next.config resolution and, in dev, from a
1899
+ * filesystem watcher — the bundler only ever sees the `.animus/` disk
1900
+ * artifacts.
1901
+ */
1902
+ /** Run the full pipeline with the Turbopack emitter identity: the virtual
1903
+ * system-props id (Turbopack rejects the webpack path's absolute-path
1904
+ * imports). Turbopack orchestration persists the analysis-inputs
1905
+ * hydration corpus — its isolated loader workers replay it (spec:
1906
+ * next-turbopack-integration, "Manifest disk artifact"; webpack mode
1907
+ * skips the corpus). */
1908
+ async function runSessionPipeline(session) {
1909
+ session.systemPropsModuleId = TURBOPACK_SYSTEM_PROPS_ID;
1910
+ session.persistAnalysisInputs = true;
1911
+ await session.runFullPipeline();
1912
+ }
1913
+ const activeWatcherRoots = /* @__PURE__ */ new Set();
1914
+ const IGNORED_SEGMENTS = new Set([
1915
+ ".animus",
1916
+ ".next",
1917
+ "node_modules"
1918
+ ]);
1919
+ /**
1920
+ * Start the dev watcher: fs.watch per eligible top-level directory (plus a
1921
+ * non-recursive watch on the root itself), debounced into
1922
+ * existence-partitioned modified/removed sets feeding
1923
+ * `session.handleWatchUpdate` (serialized — updates never overlap).
1924
+ * Generated and vendored trees (`.animus`, `.next`, node_modules) are never
1925
+ * registered with the OS — recursive registration of those trees exhausts
1926
+ * inotify/kqueue descriptors (EMFILE/ENOSPC) on large projects.
1927
+ * Idempotent per project root; unref'd so it never holds the process open.
1928
+ * Asynchronous FSWatcher errors degrade to no-watch with a warning instead
1929
+ * of crashing the dev server. Returns a close handle, or null when this
1930
+ * root is already watched or the platform lacks recursive fs.watch (Linux
1931
+ * before Node 20 — degrades to no-watch with a warning).
1932
+ */
1933
+ function startTurbopackWatcher(session, rootDir, debounceMs = 75, watchFn = watch) {
1934
+ if (activeWatcherRoots.has(rootDir)) return null;
1935
+ activeWatcherRoots.add(rootDir);
1936
+ if (typeof session.noteDebouncedWatchEvents === "function") session.debounceCeilingMs = debounceMs;
1937
+ const pendingPaths = /* @__PURE__ */ new Set();
1938
+ const watchers = /* @__PURE__ */ new Map();
1939
+ let timer = null;
1940
+ let updateChain = Promise.resolve();
1941
+ let closed = false;
1942
+ let died = false;
1943
+ const externalWatchers = /* @__PURE__ */ new Map();
1944
+ let pendingOpened = /* @__PURE__ */ new Map();
1945
+ let capturedDuringSnapshot = [];
1946
+ const externalDiagnosticKey = (root) => `external-watch:${root}`;
1947
+ const failureReason = (err) => {
1948
+ const code = err?.code;
1949
+ if (code === "EMFILE" || code === "ENFILE" || code === "ENOSPC" || code === "EPERM") return `capacity(${code})`;
1950
+ if (/inotify|too many/i.test(String(err))) return "capacity";
1951
+ return code ?? "error";
1952
+ };
1953
+ const degradeExternalRoot = (root, err) => {
1954
+ externalWatchers.get(root)?.close();
1955
+ externalWatchers.delete(root);
1956
+ pendingOpened.get(root)?.close();
1957
+ pendingOpened.delete(root);
1958
+ const message = `ANIMUS_EXTERNAL_WATCH_UNAVAILABLE root=${relative(rootDir, root)} reason=${failureReason(err)} effect=changes in this workspace source may require restart`;
1959
+ session.stickyDiagnostics?.set(externalDiagnosticKey(root), message);
1960
+ console.warn(`[animus-extract] ${message}`);
1961
+ };
1962
+ const flush = () => {
1963
+ timer = null;
1964
+ const modifiedFiles = /* @__PURE__ */ new Set();
1965
+ const removedFiles = /* @__PURE__ */ new Set();
1966
+ for (const path of pendingPaths) (existsSync(path) ? modifiedFiles : removedFiles).add(path);
1967
+ pendingPaths.clear();
1968
+ updateChain = updateChain.then(() => session.handleWatchUpdate({
1969
+ modifiedFiles,
1970
+ removedFiles
1971
+ }).catch((err) => {
1972
+ console.warn(`[animus-extract] Turbopack watch update failed: ${String(err)}`);
1973
+ }).then(() => {
1974
+ if (pendingOpened.size > 0 || capturedDuringSnapshot.length > 0) rollbackPendingExternal();
1975
+ }));
1976
+ };
1977
+ const rollbackPendingExternal = () => {
1978
+ for (const watcher of pendingOpened.values()) watcher.close();
1979
+ pendingOpened = /* @__PURE__ */ new Map();
1980
+ capturedDuringSnapshot = [];
1981
+ };
1982
+ const closeAll = () => {
1983
+ if (closed) return;
1984
+ closed = true;
1985
+ if (timer) clearTimeout(timer);
1986
+ timer = null;
1987
+ for (const watcher of watchers.values()) watcher.close();
1988
+ watchers.clear();
1989
+ for (const watcher of externalWatchers.values()) watcher.close();
1990
+ externalWatchers.clear();
1991
+ rollbackPendingExternal();
1992
+ session.onExternalRootResolved = null;
1993
+ session.onExternalRootsCommitted = null;
1994
+ activeWatcherRoots.delete(rootDir);
1995
+ };
1996
+ const onWatcherError = (err) => {
1997
+ died = true;
1998
+ closeAll();
1999
+ console.warn(`[animus-extract] Turbopack dev watcher failed (${String(err)}); source edits require a dev-server restart`);
2000
+ handle.onDied?.();
2001
+ };
2002
+ const enqueuePath = (abs) => {
2003
+ pendingPaths.add(abs);
2004
+ try {
2005
+ session.noteDebouncedWatchEvents?.([abs]);
2006
+ } catch (err) {
2007
+ console.warn(`[animus-extract] Turbopack debounce status update failed: ${String(err)}`);
2008
+ }
2009
+ if (!timer) {
2010
+ timer = setTimeout(flush, debounceMs);
2011
+ timer.unref?.();
2012
+ }
2013
+ };
2014
+ const onEvent = (baseDir, filename) => {
2015
+ if (closed || !filename) return;
2016
+ const rel = filename.toString();
2017
+ if (rel.split(/[\\/]/).some((segment) => IGNORED_SEGMENTS.has(segment))) return;
2018
+ const abs = join(baseDir, rel);
2019
+ if (baseDir === rootDir && !watchers.has(abs)) try {
2020
+ if (statSync(abs).isDirectory()) addWatcher(abs, true);
2021
+ } catch {}
2022
+ enqueuePath(abs);
2023
+ };
2024
+ /** External-root event path: fenced by watcher identity ({watcherRootId,
2025
+ * generation} — a handle that is neither current nor pending belongs to
2026
+ * a retired generation and its events are rejected), `filename == null`
2027
+ * marks the ROOT dirty for rediscovery, and events observed while the
2028
+ * root's generation is still snapshotting are buffered for replay. */
2029
+ const onExternalEvent = (root, self, filename) => {
2030
+ if (closed) return;
2031
+ const watcher = self();
2032
+ const active = watcher !== void 0 && externalWatchers.get(root) === watcher;
2033
+ const isPending = watcher !== void 0 && pendingOpened.get(root) === watcher;
2034
+ if (!active && !isPending) return;
2035
+ let abs;
2036
+ if (filename == null) abs = root;
2037
+ else {
2038
+ const rel = filename.toString();
2039
+ if (rel.split(/[\\/]/).some((segment) => IGNORED_SEGMENTS.has(segment))) return;
2040
+ abs = rel === "" ? root : join(root, rel);
2041
+ }
2042
+ if (isPending && !active) {
2043
+ capturedDuringSnapshot.push(abs);
2044
+ return;
2045
+ }
2046
+ enqueuePath(abs);
2047
+ };
2048
+ /** Open one external-root watcher into `into` (the committed set at
2049
+ * startup, the pending set during reset reconciliation). Failures
2050
+ * degrade ONLY this root (design D7); node_modules-resident roots are
2051
+ * documented unwatchable and never registered (guardrail G2). */
2052
+ const openExternalWatcher = (root, into) => {
2053
+ if (root.split(/[\\/]/).includes("node_modules")) return;
2054
+ try {
2055
+ let watcher;
2056
+ watcher = watchFn(root, { recursive: true }, (_event, filename) => onExternalEvent(root, () => watcher, filename));
2057
+ watcher.on("error", (err) => degradeExternalRoot(root, err));
2058
+ watcher.unref?.();
2059
+ into.set(root, watcher);
2060
+ session.stickyDiagnostics?.delete(externalDiagnosticKey(root));
2061
+ } catch (err) {
2062
+ degradeExternalRoot(root, err);
2063
+ }
2064
+ };
2065
+ const addWatcher = (dir, recursive) => {
2066
+ const watcher = watchFn(dir, { recursive }, (_event, filename) => onEvent(dir, filename));
2067
+ watcher.on("error", onWatcherError);
2068
+ watcher.unref?.();
2069
+ watchers.set(dir, watcher);
2070
+ };
2071
+ try {
2072
+ addWatcher(rootDir, false);
2073
+ for (const entry of readdirSync(rootDir, { withFileTypes: true })) {
2074
+ if (!entry.isDirectory() || IGNORED_SEGMENTS.has(entry.name)) continue;
2075
+ addWatcher(join(rootDir, entry.name), true);
2076
+ }
2077
+ } catch (err) {
2078
+ closeAll();
2079
+ console.warn(`[animus-extract] Turbopack dev watcher unavailable (${String(err)}); source edits require a dev-server restart`);
2080
+ return null;
2081
+ }
2082
+ for (const root of session.externalWatchRoots ?? []) openExternalWatcher(root, externalWatchers);
2083
+ session.onExternalRootResolved = (root) => {
2084
+ if (closed) return;
2085
+ if (externalWatchers.has(root) || pendingOpened.has(root)) return;
2086
+ openExternalWatcher(root, pendingOpened);
2087
+ };
2088
+ session.onExternalRootsCommitted = (roots) => {
2089
+ if (closed) return;
2090
+ const admitted = new Set(roots);
2091
+ for (const [root, watcher] of pendingOpened) externalWatchers.set(root, watcher);
2092
+ pendingOpened = /* @__PURE__ */ new Map();
2093
+ for (const [root, watcher] of [...externalWatchers]) if (!admitted.has(root)) {
2094
+ watcher.close();
2095
+ externalWatchers.delete(root);
2096
+ }
2097
+ for (const abs of capturedDuringSnapshot.splice(0)) enqueuePath(abs);
2098
+ };
2099
+ const handle = {
2100
+ close: closeAll,
2101
+ get died() {
2102
+ return died;
2103
+ },
2104
+ onDied: null,
2105
+ settle: () => updateChain
2106
+ };
2107
+ return handle;
2108
+ }
2109
+ //#endregion
2110
+ export { ANIMUS_CSS_MODULE_ID, CLI_COMMIT_ARTIFACT, CLI_LOCK_ARTIFACT, ExtractionSession, MANIFEST_ARTIFACT, SESSION_ASSETS_DIR, STYLES_ARTIFACT, SYSTEM_PROPS_ARTIFACT, TURBOPACK_SYSTEM_PROPS_ID, analysisCommitPath, analysisInputsPath, analysisStatusPath, claimExclusiveSessionOwner, collectSessionAssets, engineApi, getAnalysisPromise, getAnalyzedHashes, getManifestJson, getReplacementEpoch, getSessionArtifactDir, getSharedCss, getSharedExternalDirs, getSharedExternalEntries, getSharedSystemProps, manifestPath, pruneStaleAssets, readJsonEnvelope, replacementEpochPath, runSessionPipeline, sessionArtifactDir, setAnalysisPromise, setSharedEngine, startTurbopackWatcher, stylesPath, systemPropsPath, verifyCommitRecord };