@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
package/dist/index.mjs CHANGED
@@ -1,2026 +1,2 @@
1
- import { createRequire } from "node:module";
2
- import { createHash } from "crypto";
3
- import { existsSync, readFileSync, readdirSync, realpathSync, statSync } from "fs";
4
- import { dirname, extname, isAbsolute, join, relative, resolve } from "path";
5
- import { realpathSync as realpathSync$1 } from "node:fs";
6
- import path, { basename, dirname as dirname$1, join as join$1, normalize } from "node:path";
7
- import { createRequire as createRequire$1 } from "module";
8
- import browserslist from "browserslist";
9
- import { browserslistToTargets, transform } from "lightningcss";
10
- import { isUnitlessProperty } from "@animus-ui/properties";
11
- //#region \0rolldown/runtime.js
12
- var __require = /* @__PURE__ */ createRequire(import.meta.url);
13
- //#endregion
14
- //#region pipeline/assemble-stylesheet.ts
15
- /**
16
- * The 7 Animus cascade layers. Always prefixed with `anm-` to avoid
17
- * collision with other frameworks' layer names (e.g., Tailwind's `base`).
18
- */
19
- const ANIMUS_LAYERS = [
20
- "anm-global",
21
- "anm-base",
22
- "anm-variants",
23
- "anm-compounds",
24
- "anm-states",
25
- "anm-system",
26
- "anm-custom"
27
- ];
28
- /**
29
- * Build the `@layer` declaration line.
30
- *
31
- * When `isCustom` is false (default layers), uses ANIMUS_LAYERS directly.
32
- * When `isCustom` is true, passes names through as-is — the consumer already
33
- * wrote the final names including the `anm-` prefixed entries.
34
- */
35
- function buildLayerDeclaration(layers, isCustom) {
36
- return `@layer ${(isCustom ? layers : [...ANIMUS_LAYERS]).join(", ")};\n`;
37
- }
38
- /**
39
- * Validate that a consumer `layers` array contains all 7 Animus layers
40
- * in the correct relative order. Consumer layers may be interleaved.
41
- *
42
- * @throws Error with descriptive message on violation
43
- */
44
- function validateLayerOrder(layers) {
45
- const expected = [...ANIMUS_LAYERS];
46
- let cursor = 0;
47
- for (const layer of layers) if (cursor < expected.length && layer === expected[cursor]) cursor++;
48
- if (cursor < expected.length) {
49
- const missing = expected.slice(cursor);
50
- const found = expected.slice(0, cursor);
51
- if (!expected.every((l) => layers.includes(l))) {
52
- const absent = expected.filter((l) => !layers.includes(l));
53
- throw new Error(`[animus-extract] Custom layers missing required layers: ${absent.join(", ")}. All 7 Animus layers must be present: ${expected.join(", ")}`);
54
- }
55
- throw new Error(`[animus-extract] Custom layers have wrong order. Found ${found.join(", ")} but then expected ${missing[0]}. Required order: (${expected.join(" < ")}). You may interleave custom layers but must preserve this subsequence.`);
56
- }
57
- }
58
- /**
59
- * Strip a leading `@layer ...;` declaration line from CSS if present.
60
- * The Rust crate embeds this in prod-mode output; we strip it so the
61
- * shared assembler controls placement.
62
- */
63
- function stripLeadingLayerDeclaration(css) {
64
- return css.replace(/^@layer\s+[^;{]+;\s*\n?/, "");
65
- }
66
- function assembleStylesheet(options) {
67
- const hasCustomLayers = !!options.layers;
68
- const layers = options.layers ?? ANIMUS_LAYERS;
69
- if (options.layers) validateLayerOrder(options.layers);
70
- const declaration = buildLayerDeclaration(layers, hasCustomLayers);
71
- const variables = options.variableCss || "";
72
- const componentCss = options.componentCss ? stripLeadingLayerDeclaration(options.componentCss) : "";
73
- const body = [options.globalCss || "", componentCss].filter(Boolean).join("\n");
74
- if (options.split) return {
75
- declaration,
76
- variables,
77
- body
78
- };
79
- return [
80
- declaration,
81
- variables,
82
- body
83
- ].filter(Boolean).join("\n");
84
- }
85
- //#endregion
86
- //#region pipeline/analyze-project-args.ts
87
- /** @internal */
88
- function buildAnalyzeProjectArgs(inputs) {
89
- return [
90
- inputs.filesJson,
91
- inputs.scalesJson,
92
- inputs.variableMapJson,
93
- inputs.contextualVarsJson,
94
- inputs.propConfigJson,
95
- inputs.groupRegistryJson,
96
- inputs.packageResolutionJson,
97
- inputs.devMode,
98
- inputs.emitterConfigJson,
99
- inputs.selectorAliasesJson,
100
- null,
101
- inputs.globalStyleBlocksJson,
102
- inputs.pathAliasesJson,
103
- inputs.keyframesJson,
104
- inputs.staticCssJson,
105
- inputs.conditionAliasesJson,
106
- inputs.externalDirsJson,
107
- inputs.transformSourcesJson
108
- ];
109
- }
110
- //#endregion
111
- //#region pipeline/engine-adapter.ts
112
- /**
113
- * Build the engine-agnostic `engineApi()` both plugins call. Returns a function
114
- * (invoked per call site) so `isV2()` and `loadNativeEngine()` re-evaluate each
115
- * time — next reads its engine choice and native module dynamically from
116
- * globalThis.
117
- */
118
- function createV2EngineApi(deps) {
119
- const { label, isV2, loadNativeEngine, store } = deps;
120
- return () => {
121
- if (!isV2()) return loadNativeEngine();
122
- const native = loadNativeEngine();
123
- return {
124
- loadSystemModule: (...args) => native.loadSystemModule(...args),
125
- scanKeyframesExports: (entryPath, rootDir) => native.scanKeyframesExports(entryPath, rootDir) ?? null,
126
- analyzeProject: (filesJsonRaw, scalesJson, variableMapJson, contextualVarsJson, propConfigJson, groupRegistryJson, packageResolutionJson, devMode, emitterConfigJson, selectorAliasesJson, _selectorOrderJson, globalStyleBlocksJson, pathAliasesJson, keyframesJson, staticCssJson, conditionAliasesJson, externalDirsJson, transformSourcesJson) => {
127
- const filesJson = deps.rehydrateFilesJson ? deps.rehydrateFilesJson(filesJsonRaw) : filesJsonRaw;
128
- const sent = /* @__PURE__ */ new Map();
129
- for (const entry of JSON.parse(filesJson)) sent.set(entry.path, entry.source);
130
- store.setSentSources(sent);
131
- const emitterConfig = emitterConfigJson ? JSON.parse(emitterConfigJson) : {};
132
- store.setEngine(null);
133
- const config = {
134
- runtimeImport: emitterConfig.runtime_import ?? void 0,
135
- cssModuleId: emitterConfig.css_module_id ?? void 0,
136
- systemPropsModuleId: emitterConfig.system_props_module_id ?? void 0,
137
- themeJson: scalesJson,
138
- variableMapJson,
139
- contextualVarsJson: contextualVarsJson ?? void 0,
140
- configJson: propConfigJson,
141
- groupRegistryJson,
142
- selectorAliasesJson: selectorAliasesJson ?? void 0,
143
- conditionAliasesJson: conditionAliasesJson ?? void 0,
144
- globalStyleBlocksJson: globalStyleBlocksJson ?? void 0,
145
- keyframesJson: keyframesJson ?? void 0,
146
- packageResolutionJson: packageResolutionJson ?? void 0,
147
- pathAliasesJson: pathAliasesJson ?? void 0,
148
- staticCssJson: staticCssJson ?? void 0,
149
- externalDirsJson: externalDirsJson ?? void 0,
150
- transformSourcesJson: transformSourcesJson ?? void 0,
151
- devMode
152
- };
153
- const engine = new native.ExtractEngine(config);
154
- store.setEngine(engine);
155
- return engine.analyze(filesJson);
156
- },
157
- transformFile: (source, path, _manifest) => {
158
- const engine = store.getEngine();
159
- if (!engine) throw new Error(`[${label}] v2 transform before analyze — engine instance not initialized`);
160
- const sentMap = store.getSentSources();
161
- if (deps.passThroughUnknownPaths && sentMap && !sentMap.has(path)) return {
162
- code: source,
163
- hasComponents: false
164
- };
165
- const sent = sentMap?.get(path);
166
- if (sent !== void 0 && sent !== source && !store.getDriftWarned()) {
167
- store.setDriftWarned(true);
168
- console.warn(`[${label}] v2: transform-time source for ${path} differs from analyze-time source — an upstream transform may be reverted`);
169
- }
170
- return JSON.parse(engine.transformFile(path));
171
- },
172
- clearAnalysisCache: () => {
173
- const engine = store.getEngine();
174
- if (engine) engine.clearCache();
175
- store.setEngine(null);
176
- }
177
- };
178
- };
179
- }
180
- //#endregion
181
- //#region pipeline/engine-retirement.ts
182
- /**
183
- * Loud rejection of the retired v1 extraction engine (openspec:
184
- * retire-extract-v1).
185
- *
186
- * v2 is the only engine. Selecting v1 — via a plugin `engine: 'v1'` option or
187
- * the `ANIMUS_ENGINE=v1` fixture env override — is a build-stopping error, never
188
- * a silent upgrade to v2 (design D1: a silent flip would let a pinned consumer's
189
- * build change engines without notice). Both extraction plugins call this before
190
- * any engine selection so the rejection is uniform and the message is defined
191
- * once.
192
- */
193
- /** The one canonical retirement message, shared verbatim by both plugins and
194
- * the env path (tasks.md cross-cutting: define once, reuse). */
195
- const RETIRED_ENGINE_MESSAGE = "animus: extraction engine 'v1' was retired (openspec: retire-extract-v1) — v2 is the only engine; remove the engine option / ANIMUS_ENGINE override";
196
- /**
197
- * Throw the canonical retirement error when v1 is selected through either
198
- * surface. Accepts the raw engine option as a string because the option type no
199
- * longer admits `'v1'` — callers cast it so a stale `'v1'` config still fails
200
- * loud at runtime instead of being silently coerced.
201
- */
202
- function assertNoRetiredEngineSelection(engineOption) {
203
- if (engineOption === "v1" || process.env.ANIMUS_ENGINE === "v1") throw new Error(RETIRED_ENGINE_MESSAGE);
204
- }
205
- //#endregion
206
- //#region pipeline/content-hash.ts
207
- /**
208
- * MD5 content hash used for file-change detection (HMR diffing) by both
209
- * extraction plugins, and for content-addressing copied asset bytes. The
210
- * algorithm/encoding is a cross-plugin contract: cache keys written by one
211
- * build path must compare equal in the next. Accepts a Buffer directly so
212
- * binary sources hash without an intermediate string copy.
213
- */
214
- function contentHash(source) {
215
- return createHash("md5").update(source).digest("hex");
216
- }
217
- //#endregion
218
- //#region pipeline/external-keyframes.ts
219
- /** Stable codes for external keyframes discovery. */
220
- const KEYFRAMES_EXTERNAL_ENTRY_FAILED = "animus.keyframes.external-entry-failed";
221
- const KEYFRAMES_EXPORT_COLLISION = "animus.keyframes.export-collision";
222
- /**
223
- * Merge `Keyframes` collections discovered from external package entries into
224
- * the consumer system's collections. Keyframes are the sole carve-out from
225
- * the consumer-config singular-authority rule: nothing but branded
226
- * collections is read from an entry, an entry that fails to evaluate
227
- * degrades to a coded diagnostic naming it, and a collection whose export
228
- * name collides keeps the earlier (consumer-first) collection with a coded
229
- * diagnostic instead of silently reordering names.
230
- */
231
- function mergeExternalKeyframes(scan, consumerKeyframesJson, externalEntries, rootDir) {
232
- const merged = {};
233
- if (consumerKeyframesJson) try {
234
- Object.assign(merged, JSON.parse(consumerKeyframesJson));
235
- } catch {
236
- return {
237
- keyframesJson: consumerKeyframesJson,
238
- diagnostics: []
239
- };
240
- }
241
- const diagnostics = [];
242
- const seenEntries = /* @__PURE__ */ new Set();
243
- for (const entryPath of externalEntries) {
244
- if (seenEntries.has(entryPath)) continue;
245
- seenEntries.add(entryPath);
246
- let scanned;
247
- try {
248
- scanned = scan(entryPath, rootDir);
249
- } catch (error) {
250
- diagnostics.push({
251
- file: entryPath,
252
- component: "keyframes",
253
- kind: "warn",
254
- message: `external package entry failed the keyframes scan — its collections are invisible to extraction: ${String(error)}. Keyframe collections must be reachable from the package's definition entry without evaluating framework re-exports: export them (directly or as a named re-export) from the definition entry, and avoid \`export *\` of framework packages there (${KEYFRAMES_EXTERNAL_ENTRY_FAILED})`,
255
- code: KEYFRAMES_EXTERNAL_ENTRY_FAILED,
256
- severity: "warn"
257
- });
258
- continue;
259
- }
260
- if (!scanned) continue;
261
- let collections;
262
- try {
263
- collections = JSON.parse(scanned);
264
- } catch {
265
- continue;
266
- }
267
- for (const [exportName, collection] of Object.entries(collections)) {
268
- const existing = merged[exportName];
269
- if (existing !== void 0) {
270
- if (JSON.stringify(existing) !== JSON.stringify(collection)) diagnostics.push({
271
- file: entryPath,
272
- component: exportName,
273
- kind: "warn",
274
- message: `keyframes collection export '${exportName}' collides with an earlier collection of the same name — the earlier one wins (${KEYFRAMES_EXPORT_COLLISION})`,
275
- code: KEYFRAMES_EXPORT_COLLISION,
276
- severity: "warn"
277
- });
278
- continue;
279
- }
280
- merged[exportName] = collection;
281
- }
282
- }
283
- return {
284
- keyframesJson: Object.keys(merged).length > 0 ? JSON.stringify(merged) : null,
285
- diagnostics
286
- };
287
- }
288
- //#endregion
289
- //#region pipeline/discover-files.ts
290
- /**
291
- * Recursively discover source files under `dir`, skipping any path that
292
- * contains one of `excludePatterns` (matched as substrings of both the full
293
- * and root-relative path) and keeping files whose extension is in
294
- * `extensionsSet`.
295
- *
296
- * Single authoritative copy for both extraction plugins.
297
- */
298
- function discoverFiles(dir, rootDir, excludePatterns, extensionsSet) {
299
- const results = [];
300
- let entries;
301
- try {
302
- entries = readdirSync(dir, { encoding: "utf8" });
303
- } catch {
304
- return results;
305
- }
306
- for (const entry of entries) {
307
- const fullPath = join(dir, entry);
308
- const relativePath = relative(rootDir, fullPath);
309
- if (excludePatterns.some((pattern) => fullPath.includes(pattern) || relativePath.includes(pattern))) continue;
310
- let stat;
311
- try {
312
- stat = statSync(fullPath);
313
- } catch {
314
- continue;
315
- }
316
- if (stat.isDirectory()) results.push(...discoverFiles(fullPath, rootDir, excludePatterns, extensionsSet));
317
- else if (extensionsSet.has(extname(entry))) results.push(fullPath);
318
- }
319
- return results;
320
- }
321
- //#endregion
322
- //#region pipeline/source-identity.ts
323
- /**
324
- * SourceId derivation authority + allowlist membership (openspec:
325
- * external-source-watch-ingestion, design D1/D2/D5).
326
- *
327
- * One shared derivation produces the canonical source identity consumed by
328
- * discovery, watch ingestion, ownership, deletion pruning, and diagnostics
329
- * — raw event paths are lookup INPUTS only, so event spelling (symlink
330
- * alias vs canonical, lexical vs realpath) can never fork identity.
331
- *
332
- * The containment and volume helpers are pure and path-API-injectable so
333
- * Windows semantics are unit-testable via `path.win32` on any host; runtime
334
- * callers use the ambient platform implementation.
335
- */
336
- /**
337
- * Structural containment: `target` is the root itself or a descendant of it,
338
- * decided by `relative()` shape — never by string prefixing, so `/ui` can
339
- * never claim `/ui-old`, and a cross-drive win32 target (whose relative()
340
- * result is absolute) is never contained.
341
- */
342
- function isPathWithinRoot(root, target, pathApi = path) {
343
- const rel = pathApi.relative(root, target);
344
- return rel === "" || !pathApi.isAbsolute(rel) && rel !== ".." && !rel.startsWith(".." + pathApi.sep);
345
- }
346
- /**
347
- * Cross-volume gate (design D5): two paths share a platform path root
348
- * (win32 drive letter or UNC share; always true on posix). Compared
349
- * case-insensitively — win32 drive letters are case-insensitive.
350
- */
351
- function sharesVolumeRoot(a, b, pathApi = path) {
352
- const volumeOf = (p) => pathApi.parse(pathApi.resolve(p)).root.toLowerCase();
353
- return volumeOf(a) === volumeOf(b);
354
- }
355
- function canonicalize(p) {
356
- try {
357
- return realpathSync$1(p);
358
- } catch {
359
- return null;
360
- }
361
- }
362
- function createSourceIdentity(rootDir) {
363
- const normalizedRootDir = path.normalize(rootDir);
364
- const canonicalRootDir = canonicalize(normalizedRootDir) ?? normalizedRootDir;
365
- const roots = [];
366
- const aliases = /* @__PURE__ */ new Map();
367
- const owningRecord = (canonicalPath) => {
368
- let owner = null;
369
- for (const record of roots) {
370
- if (!isPathWithinRoot(record.canonical, canonicalPath)) continue;
371
- if (!owner || record.canonical.length > owner.canonical.length) owner = record;
372
- }
373
- return owner;
374
- };
375
- return {
376
- rootDir: normalizedRootDir,
377
- canonicalRootDir,
378
- registerExternalRoot(root) {
379
- const asRegistered = path.normalize(root);
380
- const canonical = canonicalize(asRegistered) ?? asRegistered;
381
- const existing = roots.find((record) => record.canonical === canonical);
382
- if (existing) return existing.canonical;
383
- roots.push({
384
- asRegistered,
385
- canonical
386
- });
387
- return canonical;
388
- },
389
- externalRoots() {
390
- return roots.map((record) => record.canonical);
391
- },
392
- resolveSourceId(inputPath) {
393
- const lexical = path.normalize(inputPath);
394
- const canonical = canonicalize(lexical);
395
- if (canonical === null) return null;
396
- const owner = owningRecord(canonical);
397
- const ownedBy = (record) => {
398
- const pathInRoot = path.relative(record.canonical, canonical);
399
- return {
400
- sourceKey: path.relative(normalizedRootDir, path.join(record.asRegistered, pathInRoot)),
401
- owningRoot: record.canonical,
402
- pathInRoot
403
- };
404
- };
405
- const ownerIsMoreSpecific = owner !== null && owner.canonical.length > canonicalRootDir.length;
406
- let resolved;
407
- if (!ownerIsMoreSpecific && isPathWithinRoot(canonicalRootDir, canonical)) {
408
- const key = path.relative(canonicalRootDir, canonical);
409
- resolved = {
410
- sourceKey: key,
411
- owningRoot: null,
412
- pathInRoot: key
413
- };
414
- } else if (owner) resolved = ownedBy(owner);
415
- else return null;
416
- aliases.set(lexical, resolved);
417
- aliases.set(canonical, resolved);
418
- return resolved;
419
- },
420
- resolveDeletedSourceId(inputPath) {
421
- return aliases.get(path.normalize(inputPath)) ?? null;
422
- },
423
- containingExternalRoot(inputPath) {
424
- const lexical = path.normalize(inputPath);
425
- let owner = null;
426
- for (const record of roots) {
427
- if (!(isPathWithinRoot(record.canonical, lexical) || isPathWithinRoot(record.asRegistered, lexical))) continue;
428
- if (!owner || record.canonical.length > owner.canonical.length) owner = record;
429
- }
430
- if (owner) return owner.canonical;
431
- const canonical = canonicalize(lexical);
432
- if (canonical === null) return null;
433
- for (const record of roots) {
434
- if (!isPathWithinRoot(record.canonical, canonical)) continue;
435
- if (!owner || record.canonical.length > owner.canonical.length) owner = record;
436
- }
437
- return owner?.canonical ?? null;
438
- }
439
- };
440
- }
441
- //#endregion
442
- //#region pipeline/discover-packages.ts
443
- /**
444
- * Walk up from a resolved package entry file to the nearest directory
445
- * containing a package.json (the package root). Stops at the filesystem
446
- * root and returns it if no package.json is found on the way up.
447
- */
448
- function findPackageRoot(absEntryPath) {
449
- let pkgRoot = dirname(absEntryPath);
450
- while (pkgRoot !== dirname(pkgRoot) && !existsSync(join(pkgRoot, "package.json"))) pkgRoot = dirname(pkgRoot);
451
- return pkgRoot;
452
- }
453
- /**
454
- * Exclusion fragments for discovery inside an external package's src/,
455
- * matched against paths RELATIVE TO the src dir. Per spec
456
- * external-package-file-discovery, the filters apply "within the package" —
457
- * an npm-installed package whose own location is under node_modules (or a
458
- * repo path containing 'dist') must still have its sources discovered.
459
- */
460
- const PACKAGE_SRC_EXCLUDES = [
461
- "dist",
462
- "node_modules",
463
- ".test.",
464
- ".spec."
465
- ];
466
- /** True when a PACKAGE-RELATIVE path matches a package-source exclusion
467
- * fragment (the "within the package" filter — see PACKAGE_SRC_EXCLUDES). */
468
- function isExcludedPackageRelativePath(rel) {
469
- return PACKAGE_SRC_EXCLUDES.some((pattern) => rel.includes(pattern));
470
- }
471
- /**
472
- * THE package-source walk (guardrail G1 — one policy): shared discovery with
473
- * no consumer patterns, then exclusion by package-relative path so fragments
474
- * in the package's own location can't blank out its sources. Used by the
475
- * collector, hosts' dirty-root rewalks, and watch-path classification alike.
476
- */
477
- function walkPackageSources(packageDir, extensionsSet) {
478
- return discoverFiles(packageDir, packageDir, [], extensionsSet).filter((absPath) => !isExcludedPackageRelativePath(relative(packageDir, absPath)));
479
- }
480
- /** Exclusions for the compiled-output fallback when a package does not ship src/. */
481
- const PACKAGE_OUTPUT_EXCLUDES = [
482
- "node_modules",
483
- ".test.",
484
- ".spec.",
485
- ".d.ts",
486
- ".map"
487
- ];
488
- const isFile = (path) => {
489
- try {
490
- return statSync(path).isFile();
491
- } catch {
492
- return false;
493
- }
494
- };
495
- /**
496
- * Resolve an absolute-path specifier (a relative `includes` entry already
497
- * resolved against the system file) without a bundler: the path itself when it
498
- * is a file, otherwise the extension and directory-index candidates built from
499
- * the caller's extension set. Used only as a fallback — a bundler resolver that
500
- * answers first still wins, since it also knows aliases and `.js`→`.ts` mapping.
501
- */
502
- function resolveAbsolutePathSpecifier(absSpecifier, extensionsSet) {
503
- return [
504
- absSpecifier,
505
- ...Array.from(extensionsSet, (ext) => absSpecifier + ext),
506
- ...Array.from(extensionsSet, (ext) => join(absSpecifier, `index${ext}`))
507
- ].find(isFile) ?? null;
508
- }
509
- /** The package-name half of a bare specifier (`@scope/name/sub` → `@scope/name`). */
510
- function bareSpecifierPackageName(specifier) {
511
- const segments = specifier.split("/");
512
- return specifier.startsWith("@") ? segments.slice(0, 2).join("/") : segments[0];
513
- }
514
- function sourceEntryForSpecifier(specifier, srcDir, extensionsSet) {
515
- if (isAbsolute(specifier)) {
516
- const resolved = resolveAbsolutePathSpecifier(specifier, extensionsSet);
517
- if (!resolved) return null;
518
- return isPathWithinRoot(srcDir, resolved) ? resolved : null;
519
- }
520
- const packageName = bareSpecifierPackageName(specifier);
521
- return resolveAbsolutePathSpecifier(join(srcDir, specifier.slice(packageName.length + 1) || "index"), extensionsSet);
522
- }
523
- /**
524
- * The D13 dist-freshness check: applicable only when a specifier has BOTH a
525
- * walked src/ tree and a resolved dist entry that exists on disk outside that
526
- * tree; stale when the dist entry's mtime is older than the newest walked
527
- * source file's. Not applicable (never stale) when the entry resolves inside
528
- * src/ (no dist to skew), when the entry file is missing, or when no source
529
- * file's mtime is readable. Detection only — reporting is the caller's policy.
530
- */
531
- function distEntryIsStale(absEntry, srcDir, srcFiles) {
532
- if (isPathWithinRoot(srcDir, absEntry)) return false;
533
- let distMtime;
534
- try {
535
- distMtime = statSync(absEntry).mtimeMs;
536
- } catch {
537
- return false;
538
- }
539
- let newestSrcMtime = -Infinity;
540
- for (const srcFile of srcFiles) try {
541
- newestSrcMtime = Math.max(newestSrcMtime, statSync(srcFile).mtimeMs);
542
- } catch {}
543
- return distMtime < newestSrcMtime;
544
- }
545
- /**
546
- * Shared external-package source collection (spec:
547
- * external-package-file-discovery), consumed by both extraction plugins.
548
- * For each specifier: resolve to an absolute entry (null/throw → silently
549
- * skip; an absolute-path specifier falls back to a filesystem probe), walk up
550
- * to the package root, then either discover sources under src/ (redirecting
551
- * module resolution to src/index.ts when present) or fall back to ingesting
552
- * the resolved entry file itself.
553
- *
554
- * The only bundler-specific seams are callbacks: specifier resolution,
555
- * dedup against already-ingested files, per-file preprocessing (MDX), and
556
- * the unreadable-file warning. Hashing and caching stay in the plugins —
557
- * their cache policies legitimately differ.
558
- *
559
- * Alongside the aggregates, one `ExternalPackageOutcome` per declared
560
- * specifier records what that specifier produced. Collection never reports on
561
- * them — any warning or gate is the caller's policy.
562
- */
563
- async function collectExternalPackageSources(opts) {
564
- const { specifiers, resolveSpecifier, rootDir, extensionsSet, hasEntry, preprocessFile, onUnreadable, onPackageResolved } = opts;
565
- const entries = [];
566
- const pushed = /* @__PURE__ */ new Set();
567
- const packageMap = {};
568
- const sourceEntries = /* @__PURE__ */ new Map();
569
- const keyframesScanEntries = /* @__PURE__ */ new Map();
570
- const packageDirs = [];
571
- const dirOwnerSets = {};
572
- const dirExtensions = {};
573
- const fileOwners = {};
574
- const outcomes = [];
575
- const claimDir = (dir, specifier) => {
576
- (dirOwnerSets[dir] ??= []).push(specifier);
577
- };
578
- const alreadyIngested = (relPath) => hasEntry(relPath) || pushed.has(relPath);
579
- for (const specifier of specifiers) {
580
- let absEntry;
581
- try {
582
- absEntry = await resolveSpecifier(specifier);
583
- } catch {
584
- absEntry = null;
585
- }
586
- if (!absEntry && isAbsolute(specifier)) absEntry = resolveAbsolutePathSpecifier(specifier, extensionsSet);
587
- if (!absEntry) {
588
- outcomes.push({
589
- specifier,
590
- outcome: "unresolvable",
591
- fileCount: 0
592
- });
593
- continue;
594
- }
595
- const srcDir = join(findPackageRoot(absEntry), "src");
596
- let fileCount = 0;
597
- let staleDist = false;
598
- if (existsSync(srcDir)) {
599
- packageDirs.push(srcDir);
600
- claimDir(srcDir, specifier);
601
- dirExtensions[srcDir] = [...extensionsSet];
602
- onPackageResolved?.(specifier, srcDir);
603
- const srcEntry = sourceEntryForSpecifier(specifier, srcDir, extensionsSet);
604
- if (srcEntry) {
605
- packageMap[specifier] = relative(rootDir, srcEntry);
606
- sourceEntries.set(specifier, srcEntry);
607
- } else packageMap[specifier] = relative(rootDir, absEntry);
608
- keyframesScanEntries.set(specifier, srcEntry ?? absEntry);
609
- if (!isAbsolute(specifier)) {
610
- const packageName = bareSpecifierPackageName(specifier);
611
- if (packageName !== specifier && !(packageName in packageMap)) {
612
- const rootEntry = sourceEntryForSpecifier(packageName, srcDir, extensionsSet);
613
- if (rootEntry) {
614
- packageMap[packageName] = relative(rootDir, rootEntry);
615
- sourceEntries.set(packageName, rootEntry);
616
- keyframesScanEntries.set(packageName, rootEntry);
617
- }
618
- }
619
- }
620
- const pkgFiles = walkPackageSources(srcDir, extensionsSet);
621
- staleDist = distEntryIsStale(absEntry, srcDir, pkgFiles);
622
- for (const pkgFile of pkgFiles) {
623
- const relPath = relative(rootDir, pkgFile);
624
- if (alreadyIngested(relPath)) {
625
- fileCount++;
626
- continue;
627
- }
628
- let source;
629
- try {
630
- source = readFileSync(pkgFile, "utf-8");
631
- } catch (err) {
632
- onUnreadable(relPath, err);
633
- continue;
634
- }
635
- const processed = await preprocessFile(source, relPath, pkgFile);
636
- if (!processed) continue;
637
- entries.push({
638
- path: processed.relPath,
639
- source: processed.source
640
- });
641
- pushed.add(processed.relPath);
642
- fileOwners[processed.relPath] ??= specifier;
643
- fileCount++;
644
- }
645
- } else {
646
- const outputDir = dirname(absEntry);
647
- packageDirs.push(outputDir);
648
- claimDir(outputDir, specifier);
649
- onPackageResolved?.(specifier, outputDir);
650
- packageMap[specifier] = relative(rootDir, absEntry);
651
- keyframesScanEntries.set(specifier, absEntry);
652
- const outputExtensions = new Set(extensionsSet);
653
- outputExtensions.add(extname(absEntry));
654
- dirExtensions[outputDir] = [...outputExtensions];
655
- const outputFiles = discoverFiles(outputDir, outputDir, [], outputExtensions).filter((file) => {
656
- const relToOutput = relative(outputDir, file);
657
- return !PACKAGE_OUTPUT_EXCLUDES.some((pattern) => relToOutput.includes(pattern));
658
- });
659
- if (!outputFiles.includes(absEntry)) outputFiles.unshift(absEntry);
660
- for (const outputFile of outputFiles) {
661
- const outputRelPath = relative(rootDir, outputFile);
662
- if (alreadyIngested(outputRelPath)) {
663
- fileCount++;
664
- continue;
665
- }
666
- let source;
667
- try {
668
- source = readFileSync(outputFile, "utf-8");
669
- } catch (err) {
670
- onUnreadable(outputRelPath, err);
671
- continue;
672
- }
673
- const processed = await preprocessFile(source, outputRelPath, outputFile);
674
- if (!processed) continue;
675
- entries.push({
676
- path: processed.relPath,
677
- source: processed.source
678
- });
679
- pushed.add(processed.relPath);
680
- fileOwners[processed.relPath] ??= specifier;
681
- fileCount++;
682
- }
683
- }
684
- outcomes.push({
685
- specifier,
686
- outcome: staleDist ? "stale-dist" : fileCount > 0 ? "resolved" : "empty",
687
- fileCount
688
- });
689
- }
690
- return {
691
- entries,
692
- packageMap,
693
- sourceEntries,
694
- keyframesScanEntries,
695
- packageDirs,
696
- dirOwnerSets,
697
- dirExtensions,
698
- fileOwners,
699
- outcomes
700
- };
701
- }
702
- /** First-declared specifier per package dir — the single-value ownership
703
- * view correlation consumers key on, derived from `dirOwnerSets`. */
704
- function firstOwners(dirOwnerSets) {
705
- const owners = {};
706
- for (const [dir, specifiers] of Object.entries(dirOwnerSets)) if (specifiers.length > 0) owners[dir] = specifiers[0];
707
- return owners;
708
- }
709
- /**
710
- * Excise a set of rejected specifiers from a collection result ATOMICALLY
711
- * (openspec: external-source-watch-ingestion, design D5): the returned copy
712
- * carries no entries, package-map targets, source entries, package dirs, or
713
- * ownership for the rejected packages — a package dir is removed only when
714
- * EVERY specifier that claimed it is rejected (a dir-level rejection, such
715
- * as the cross-volume gate, always rejects them together). Outcome records
716
- * are reporting inputs, not membership, and pass through untouched.
717
- */
718
- function excludeCollectedPackages(collected, rejectedSpecifiers, rootDir) {
719
- if (rejectedSpecifiers.size === 0) return collected;
720
- const rejectedDirs = Object.entries(collected.dirOwnerSets).filter(([, specs]) => specs.every((s) => rejectedSpecifiers.has(s))).map(([dir]) => dir);
721
- const underRejectedDir = (absPath) => rejectedDirs.some((dir) => isPathWithinRoot(dir, absPath));
722
- const targetRejected = (specifier, absTarget) => rejectedSpecifiers.has(specifier) || underRejectedDir(absTarget);
723
- const packageMap = {};
724
- for (const [specifier, relTarget] of Object.entries(collected.packageMap)) {
725
- if (targetRejected(specifier, resolve(rootDir, relTarget))) continue;
726
- packageMap[specifier] = relTarget;
727
- }
728
- const sourceEntries = /* @__PURE__ */ new Map();
729
- for (const [specifier, absEntry] of collected.sourceEntries) {
730
- if (targetRejected(specifier, absEntry)) continue;
731
- sourceEntries.set(specifier, absEntry);
732
- }
733
- const keyframesScanEntries = /* @__PURE__ */ new Map();
734
- for (const [specifier, absEntry] of collected.keyframesScanEntries) {
735
- if (targetRejected(specifier, absEntry)) continue;
736
- keyframesScanEntries.set(specifier, absEntry);
737
- }
738
- const dirOwnerSets = {};
739
- for (const [dir, specs] of Object.entries(collected.dirOwnerSets)) {
740
- const kept = specs.filter((s) => !rejectedSpecifiers.has(s));
741
- if (kept.length === 0) continue;
742
- dirOwnerSets[dir] = kept;
743
- }
744
- const dirExtensions = {};
745
- for (const [dir, exts] of Object.entries(collected.dirExtensions)) {
746
- if (rejectedDirs.includes(dir)) continue;
747
- dirExtensions[dir] = exts;
748
- }
749
- const fileOwners = {};
750
- for (const [relPath, owner] of Object.entries(collected.fileOwners)) {
751
- if (rejectedSpecifiers.has(owner)) continue;
752
- fileOwners[relPath] = owner;
753
- }
754
- return {
755
- entries: collected.entries.filter((entry) => !rejectedSpecifiers.has(collected.fileOwners[entry.path])),
756
- packageMap,
757
- sourceEntries,
758
- keyframesScanEntries,
759
- packageDirs: collected.packageDirs.filter((dir) => !rejectedDirs.includes(dir)),
760
- dirOwnerSets,
761
- dirExtensions,
762
- fileOwners,
763
- outcomes: collected.outcomes
764
- };
765
- }
766
- /**
767
- * Extract external DS package names from inheritance declarations in the
768
- * system file.
769
- *
770
- * Supports four forms:
771
- * - Primary: `createSystem(...).extend(identifier)` chain calls
772
- * (repeatable, mixable with `.from()` links; each call
773
- * contributes one source; a library-bundle identifier
774
- * traces its base import)
775
- * - Deprecated chain: `createSystem(...).from(identifier)` chain calls
776
- * - Deprecated alias: `createSystem({ includes: [identifier, ...] })`
777
- * - Legacy: `.includes([identifier, ...])` chain method (RC
778
- * migration fallback)
779
- *
780
- * For each identifier found, traces back to its import declaration and returns
781
- * the import specifier: a bare specifier normalized to its package name, a
782
- * relative specifier resolved against the system file's directory into an
783
- * absolute path (so a sibling package referenced by path contributes discovery
784
- * too). Only packages explicitly declared through one of these forms are
785
- * treated as external DS dependencies.
786
- *
787
- * Falls back to empty array if no declaration is found.
788
- */
789
- /**
790
- * The message for the strict/warn gate over unresolvable includes, or null
791
- * when every declared specifier resolved (external-package-file-discovery:
792
- * silence is never an outcome — non-strict consumers warn with this line,
793
- * strict consumers throw it).
794
- */
795
- function unresolvableIncludesMessage(outcomes) {
796
- const unresolvable = outcomes.filter((record) => record.outcome === "unresolvable").map((record) => record.specifier);
797
- if (unresolvable.length === 0) return null;
798
- return `[animus-extract] unresolvable include specifier(s): ${unresolvable.join(", ")}`;
799
- }
800
- /**
801
- * The message for the strict/warn gate over stale dist entries
802
- * (first-class-extension D13), or null when no declared specifier is stale.
803
- * A stale dist silently skews merged registry content while discovery
804
- * compiles the fresh sources, so it surfaces like an unresolvable specifier:
805
- * non-strict consumers warn with this line, strict consumers throw it.
806
- */
807
- function staleDistIncludesMessage(outcomes) {
808
- const stale = outcomes.filter((record) => record.outcome === "stale-dist").map((record) => record.specifier);
809
- if (stale.length === 0) return null;
810
- return `[animus-extract] stale dist for include specifier(s): ${stale.join(", ")} — dist entry is older than the newest src/ file; rebuild the package(s) before extracting`;
811
- }
812
- function extractSystemFilePackages(systemFilePath) {
813
- let source;
814
- try {
815
- source = readFileSync(systemFilePath, "utf-8");
816
- } catch {
817
- return [];
818
- }
819
- const identifiers = /* @__PURE__ */ new Set();
820
- const constructorRegex = /createSystem\s*\(\s*\{[^}]*?\bincludes\s*:\s*\[([^\]]*)\]/gs;
821
- const chainRegex = /\.includes\s*\(\s*\[([^\]]*)\]\s*\)/gs;
822
- const collectIdentifiers = (regex) => {
823
- let match;
824
- while ((match = regex.exec(source)) !== null) {
825
- const inner = match[1];
826
- for (const token of inner.split(",")) {
827
- const id = token.trim();
828
- if (id && /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(id)) identifiers.add(id);
829
- }
830
- }
831
- };
832
- collectIdentifiers(constructorRegex);
833
- collectIdentifiers(chainRegex);
834
- const IDENT_START_RE = /^[a-zA-Z_$][a-zA-Z0-9_$]*/;
835
- /** Position after any run of whitespace, line comments, block comments. */
836
- const skipTrivia = (from) => {
837
- let pos = from;
838
- for (;;) {
839
- while (pos < source.length && /\s/.test(source[pos])) pos++;
840
- if (source.startsWith("//", pos)) {
841
- const newline = source.indexOf("\n", pos);
842
- pos = newline === -1 ? source.length : newline + 1;
843
- continue;
844
- }
845
- if (source.startsWith("/*", pos)) {
846
- const close = source.indexOf("*/", pos + 2);
847
- pos = close === -1 ? source.length : close + 2;
848
- continue;
849
- }
850
- return pos;
851
- }
852
- };
853
- /**
854
- * Consume consecutive extend/from links starting at `from`, collecting
855
- * each link's base identifier; tolerates trivia between tokens and a
856
- * trailing comma in the argument list. Returns the position after the
857
- * last consumed link (`from` itself when none matched).
858
- */
859
- const consumeChainLinks = (from) => {
860
- let pos = from;
861
- for (;;) {
862
- let cursor = skipTrivia(pos);
863
- if (source[cursor] !== ".") return pos;
864
- cursor = skipTrivia(cursor + 1);
865
- const method = IDENT_START_RE.exec(source.slice(cursor))?.[0];
866
- if (method !== "extend" && method !== "from") return pos;
867
- cursor = skipTrivia(cursor + method.length);
868
- if (source[cursor] !== "(") return pos;
869
- cursor = skipTrivia(cursor + 1);
870
- const base = IDENT_START_RE.exec(source.slice(cursor))?.[0];
871
- if (!base) return pos;
872
- cursor = skipTrivia(cursor + base.length);
873
- while (source[cursor] === ".") {
874
- const afterDot = skipTrivia(cursor + 1);
875
- const segment = IDENT_START_RE.exec(source.slice(afterDot))?.[0];
876
- if (!segment) break;
877
- cursor = skipTrivia(afterDot + segment.length);
878
- }
879
- if (source[cursor] === ",") cursor = skipTrivia(cursor + 1);
880
- if (source[cursor] !== ")") return pos;
881
- identifiers.add(base);
882
- pos = cursor + 1;
883
- }
884
- };
885
- /** Identifier assigned directly before `index` (`const x = <here>`), if any. */
886
- const boundIdentifierBefore = (index) => {
887
- const match = /([a-zA-Z_$][a-zA-Z0-9_$]*)\s*=\s*$/.exec(source.slice(0, index));
888
- return match ? match[1] : null;
889
- };
890
- const chainRootIdentifiers = /* @__PURE__ */ new Set();
891
- const createSystemAnchor = /createSystem\s*\(/g;
892
- let anchorMatch;
893
- while ((anchorMatch = createSystemAnchor.exec(source)) !== null) {
894
- let pos = anchorMatch.index + anchorMatch[0].length;
895
- let depth = 1;
896
- while (pos < source.length && depth > 0) {
897
- const ch = source[pos];
898
- if (ch === "(") depth++;
899
- else if (ch === ")") depth--;
900
- pos++;
901
- }
902
- consumeChainLinks(pos);
903
- const bound = boundIdentifierBefore(anchorMatch.index);
904
- if (bound) chainRootIdentifiers.add(bound);
905
- }
906
- const scannedRoots = /* @__PURE__ */ new Set();
907
- for (;;) {
908
- const pendingRoots = [...chainRootIdentifiers].filter((root) => !scannedRoots.has(root));
909
- if (pendingRoots.length === 0) break;
910
- for (const root of pendingRoots) {
911
- scannedRoots.add(root);
912
- const rootUse = new RegExp(`(?<![a-zA-Z0-9_$])${root.replace(/\$/g, "\\$")}(?![a-zA-Z0-9_$])`, "g");
913
- let useMatch;
914
- while ((useMatch = rootUse.exec(source)) !== null) {
915
- const afterIdentifier = useMatch.index + useMatch[0].length;
916
- if (consumeChainLinks(afterIdentifier) === afterIdentifier) continue;
917
- const bound = boundIdentifierBefore(useMatch.index);
918
- if (bound) chainRootIdentifiers.add(bound);
919
- }
920
- }
921
- }
922
- if (identifiers.size === 0) return [];
923
- const importMap = /* @__PURE__ */ new Map();
924
- const importRegex = /^\s*import\s+(?:([a-zA-Z_$][a-zA-Z0-9_$]*)\s*,\s*)?(?:\{([^}]*)\}|([a-zA-Z_$][a-zA-Z0-9_$]*))\s+from\s+['"]([^'"]+)['"]/gm;
925
- let importMatch;
926
- while ((importMatch = importRegex.exec(source)) !== null) {
927
- const [, comboDefault, namedImports, defaultImport, specifier] = importMatch;
928
- if (comboDefault) importMap.set(comboDefault, specifier);
929
- if (defaultImport) importMap.set(defaultImport, specifier);
930
- if (namedImports) for (const binding of namedImports.split(",")) {
931
- const parts = binding.trim().split(/\s+as\s+/);
932
- const localName = (parts[1] || parts[0]).trim();
933
- if (localName) importMap.set(localName, specifier);
934
- }
935
- }
936
- const systemFileDir = dirname(systemFilePath);
937
- const packages = /* @__PURE__ */ new Set();
938
- for (const id of identifiers) {
939
- const specifier = importMap.get(id);
940
- if (!specifier) continue;
941
- if (specifier.startsWith(".")) packages.add(resolve(systemFileDir, specifier));
942
- else packages.add(specifier);
943
- }
944
- return Array.from(packages);
945
- }
946
- //#endregion
947
- //#region pipeline/asset-placeholders.ts
948
- /**
949
- * Host-side handling of `asset()` placeholders (global-styles-system):
950
- * `animus-asset:<specifier>` markers ride through the sandbox and the
951
- * emitter byte-exact; each HOST plugin substitutes them with its bundler's
952
- * resolved asset URL after extraction. This module owns the shared scanning
953
- * and replacement mechanics — resolution and strict gating stay at the
954
- * plugin call sites.
955
- */
956
- /** Mirrors the producer-side constant in `@animus-ui/system`'s `asset.ts`
957
- * (extract must not take a runtime dependency on system); the pairing is
958
- * pinned by a contract test in `tests/asset-placeholders.test.ts`. */
959
- const ASSET_PLACEHOLDER_PREFIX = "animus-asset:";
960
- const escapeRegExp = (value) => value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
961
- const PREFIX_RE = escapeRegExp(ASSET_PLACEHOLDER_PREFIX);
962
- /**
963
- * Quoted `url('animus-asset:<specifier>')` form — the emitter always quotes
964
- * `url()` values, so a quoted match carries the FULL specifier, including
965
- * whitespace and parentheses (D5 pins the placeholder as specifier-verbatim,
966
- * so scanning fidelity is the only place such characters can be honored).
967
- */
968
- const QUOTED_PLACEHOLDER_RE = new RegExp(`(['"])${PREFIX_RE}([^'"]*?)\\1`, "g");
969
- /** Bare-form fallback: a placeholder up to CSS url()/quote/whitespace. */
970
- const BARE_PLACEHOLDER_RE = new RegExp(`${PREFIX_RE}([^'")\\s]+)`, "g");
971
- /** Unique asset specifiers referenced by placeholders, in appearance order. */
972
- function findAssetSpecifiers(css) {
973
- if (!css.includes("animus-asset:")) return [];
974
- const seen = /* @__PURE__ */ new Set();
975
- const remainder = css.replace(QUOTED_PLACEHOLDER_RE, (_match, _quote, specifier) => {
976
- seen.add(specifier);
977
- return "";
978
- });
979
- for (const match of remainder.matchAll(BARE_PLACEHOLDER_RE)) seen.add(match[1]);
980
- return [...seen];
981
- }
982
- /**
983
- * Replace each specifier's placeholder with its substitution. Specifiers
984
- * absent from the map keep their placeholder — the caller decides whether
985
- * that is a strict failure or a warn-and-emit-literally. A substitution may
986
- * itself be a bundler marker (e.g. Vite's `__VITE_ASSET__<ref>__`) that the
987
- * host's own asset pipeline resolves to a hashed file name later.
988
- *
989
- * Each replacement is anchored to a following delimiter (quote, `)`,
990
- * whitespace, or end of input) so a specifier that textually prefixes a
991
- * longer one can never clobber the longer placeholder; longest-first
992
- * ordering additionally lets the longer of two mapped specifiers claim its
993
- * occurrences before the shorter runs.
994
- */
995
- function substituteAssetPlaceholders(css, urlBySpecifier) {
996
- if (urlBySpecifier.size === 0) return css;
997
- if (!css.includes("animus-asset:")) return css;
998
- const specifiers = [...urlBySpecifier.keys()].sort((a, b) => b.length - a.length);
999
- let out = css;
1000
- for (const specifier of specifiers) {
1001
- const placeholder = new RegExp(escapeRegExp(ASSET_PLACEHOLDER_PREFIX + specifier) + String.raw`(?=['")\s]|$)`, "g");
1002
- out = out.replace(placeholder, () => urlBySpecifier.get(specifier));
1003
- }
1004
- return out;
1005
- }
1006
- //#endregion
1007
- //#region pipeline/resolve-asset.ts
1008
- /**
1009
- * Node-side asset specifier resolution shared by the host plugins (the
1010
- * asset() contract, global-styles-system): host path aliases apply FIRST —
1011
- * an alias such as `@fonts` works in application modules, so
1012
- * `asset('@fonts/inter.woff2')` must resolve identically — then direct Node
1013
- * resolution, then the package-root fallback (exports maps rarely list
1014
- * asset subpaths). Bundler-native resolution (Vite's `this.resolve`) is
1015
- * still preferred where available; this resolver covers the paths that have
1016
- * no bundler hook (Next's session, Vite's dev re-analysis).
1017
- */
1018
- const requireByRoot = /* @__PURE__ */ new Map();
1019
- function requireAnchoredAt(rootDir) {
1020
- let req = requireByRoot.get(rootDir);
1021
- if (!req) {
1022
- req = createRequire$1(join(rootDir, "package.json"));
1023
- requireByRoot.set(rootDir, req);
1024
- }
1025
- return req;
1026
- }
1027
- function packageRootFromEntry(entry) {
1028
- let current = dirname(entry);
1029
- while (true) {
1030
- if (existsSync(join(current, "package.json"))) return current;
1031
- const parent = dirname(current);
1032
- if (parent === current) return null;
1033
- current = parent;
1034
- }
1035
- }
1036
- const aliasTableCache = /* @__PURE__ */ new Map();
1037
- function parseAliasTable(pathAliasesJson) {
1038
- const cached = aliasTableCache.get(pathAliasesJson);
1039
- if (cached) return cached;
1040
- let aliases;
1041
- try {
1042
- aliases = JSON.parse(pathAliasesJson).aliases ?? [];
1043
- } catch {
1044
- aliases = [];
1045
- }
1046
- aliasTableCache.set(pathAliasesJson, aliases);
1047
- return aliases;
1048
- }
1049
- /**
1050
- * Map a specifier through the harvested host alias table (the same
1051
- * `pathAliasesJson` wire the engine consumes — entries pre-sorted longest
1052
- * pattern first by `buildPathAliasesJson`). Returns an absolute path to an
1053
- * EXISTING file, or null when no alias claims the specifier.
1054
- */
1055
- function resolveThroughPathAliases(specifier, rootDir, pathAliasesJson) {
1056
- if (!pathAliasesJson) return null;
1057
- const aliases = parseAliasTable(pathAliasesJson);
1058
- for (const alias of aliases) {
1059
- let mapped = null;
1060
- if (alias.type === "exact") {
1061
- if (alias.pattern === specifier) mapped = alias.replacement;
1062
- } else if (specifier.startsWith(alias.pattern)) mapped = alias.replacement + specifier.slice(alias.pattern.length);
1063
- if (mapped === null) continue;
1064
- const absolute = isAbsolute(mapped) ? mapped : join(rootDir, mapped);
1065
- if (existsSync(absolute)) return absolute;
1066
- }
1067
- return null;
1068
- }
1069
- /**
1070
- * Resolve an asset specifier to an absolute file: host aliases, then direct
1071
- * Node resolution anchored at `rootDir`, then the package-root fallback.
1072
- * Returns null when nothing matches — strict gating stays at the caller.
1073
- */
1074
- function resolveAssetFile(specifier, rootDir, pathAliasesJson) {
1075
- const aliased = resolveThroughPathAliases(specifier, rootDir, pathAliasesJson);
1076
- if (aliased) return aliased;
1077
- const requireFromRoot = requireAnchoredAt(rootDir);
1078
- try {
1079
- return requireFromRoot.resolve(specifier);
1080
- } catch {}
1081
- const segments = specifier.split("/");
1082
- const packageName = specifier.startsWith("@") ? segments.slice(0, 2).join("/") : segments[0];
1083
- const subpath = specifier.slice(packageName.length + 1);
1084
- if (!subpath) return null;
1085
- for (const modulesDir of requireFromRoot.resolve.paths(packageName) ?? []) {
1086
- const packageRoot = join(modulesDir, packageName);
1087
- if (!existsSync(join(packageRoot, "package.json"))) continue;
1088
- const candidate = join(packageRoot, subpath);
1089
- if (existsSync(candidate)) return candidate;
1090
- }
1091
- try {
1092
- const packageRoot = packageRootFromEntry(requireFromRoot.resolve(packageName));
1093
- if (!packageRoot) return null;
1094
- const candidate = join(packageRoot, subpath);
1095
- return existsSync(candidate) ? candidate : null;
1096
- } catch {
1097
- return null;
1098
- }
1099
- }
1100
- //#endregion
1101
- //#region pipeline/correlate-external-tokens.ts
1102
- /**
1103
- * Index the loader-captured theme manifests by owning specifier. Module paths
1104
- * are canonical absolute paths (symlinks resolved), so each package dir is
1105
- * realpath'd before prefix-matching; a module outside every known package dir
1106
- * (typically the consumer's own theme) contributes nothing.
1107
- */
1108
- function buildSourceTokenIndex(opts) {
1109
- const index = /* @__PURE__ */ new Map();
1110
- if (!opts.sourceThemeManifestsJson) return index;
1111
- let manifests;
1112
- try {
1113
- manifests = JSON.parse(opts.sourceThemeManifestsJson);
1114
- } catch {
1115
- return index;
1116
- }
1117
- const realDirOwners = [];
1118
- const addOwnerDir = (dir, specifier) => {
1119
- if (!realDirOwners.some((entry) => entry.dir === dir)) realDirOwners.push({
1120
- dir,
1121
- specifier
1122
- });
1123
- };
1124
- for (const [dir, specifier] of Object.entries(opts.dirOwners)) {
1125
- let real = dir;
1126
- try {
1127
- real = realpathSync(dir);
1128
- } catch {}
1129
- addOwnerDir(real, specifier);
1130
- let packageRoot = real;
1131
- while (packageRoot !== dirname(packageRoot) && !existsSync(join(packageRoot, "package.json"))) packageRoot = dirname(packageRoot);
1132
- if (existsSync(join(packageRoot, "package.json"))) addOwnerDir(packageRoot, specifier);
1133
- }
1134
- for (const [modulePath, exports] of Object.entries(manifests)) {
1135
- const owner = realDirOwners.find(({ dir }) => isPathWithinRoot(dir, modulePath));
1136
- if (!owner) continue;
1137
- let tokens = index.get(owner.specifier);
1138
- if (!tokens) {
1139
- tokens = /* @__PURE__ */ new Set();
1140
- index.set(owner.specifier, tokens);
1141
- }
1142
- for (const paths of Object.values(exports)) for (const token of paths) tokens.add(token);
1143
- }
1144
- return index;
1145
- }
1146
- /**
1147
- * The correlation join. Returns one teaching-error message per distinct
1148
- * (component, token, specifier) whose file belongs to a discovered source AND
1149
- * whose token that source's manifest defines. The messages follow the
1150
- * standard severity routing at the CALLER (throw under `strict`, warn
1151
- * otherwise) — this join never reports on its own.
1152
- */
1153
- function correlateExternalTokenDiagnostics(opts) {
1154
- const messages = [];
1155
- const seen = /* @__PURE__ */ new Set();
1156
- for (const diagnostic of opts.diagnostics ?? []) {
1157
- if (diagnostic.kind !== "external-token-candidate" || !diagnostic.token) continue;
1158
- const specifier = opts.fileOwners[diagnostic.file];
1159
- if (!specifier) continue;
1160
- if (!opts.sourceTokens.get(specifier)?.has(diagnostic.token)) continue;
1161
- const key = `${diagnostic.component}\u0000${diagnostic.token}\u0000${specifier}`;
1162
- if (seen.has(key)) continue;
1163
- seen.add(key);
1164
- messages.push(`${diagnostic.component} (from '${specifier}') references token '${diagnostic.token}', which the consumer theme does not define — inherit the source's tokens with createTheme().extend(...) using the tokens (or bundle) export of '${specifier}'`);
1165
- }
1166
- return messages;
1167
- }
1168
- const indexCache = /* @__PURE__ */ new WeakMap();
1169
- /**
1170
- * The complete cross-source token-contract gate both plugins share
1171
- * (extraction-diagnostics): index the loader-captured source manifests,
1172
- * join them against the engine's candidates, and route the resulting
1173
- * teaching errors — throw under `strict`, warn otherwise. One entry point
1174
- * so the two hosts cannot drift on wiring or severity semantics.
1175
- */
1176
- function enforceExternalTokenContracts(opts) {
1177
- const manifestsJson = opts.sourceThemeManifestsJson ?? "";
1178
- const cached = indexCache.get(opts.dirOwners);
1179
- let sourceTokens;
1180
- if (cached && cached.manifestsJson === manifestsJson) sourceTokens = cached.index;
1181
- else {
1182
- sourceTokens = buildSourceTokenIndex({
1183
- sourceThemeManifestsJson: opts.sourceThemeManifestsJson,
1184
- dirOwners: opts.dirOwners
1185
- });
1186
- indexCache.set(opts.dirOwners, {
1187
- manifestsJson,
1188
- index: sourceTokens
1189
- });
1190
- }
1191
- const messages = correlateExternalTokenDiagnostics({
1192
- diagnostics: opts.diagnostics,
1193
- fileOwners: opts.fileOwners,
1194
- sourceTokens
1195
- });
1196
- if (messages.length === 0) return;
1197
- if (opts.strict) throw new Error(`${opts.prefix} ${messages.join("\n")}`);
1198
- for (const message of messages) opts.warn(message);
1199
- }
1200
- //#endregion
1201
- //#region pipeline/path-aliases.ts
1202
- /**
1203
- * Normalize alias pairs: strip a `rootDir` prefix from targets, classify
1204
- * exact (file) vs prefix (directory) matches, force trailing slashes on
1205
- * prefix entries, and sort longest pattern first for correct matching
1206
- * priority. Returns null when no entries survive.
1207
- */
1208
- function buildPathAliasesJson(pairs, rootDir) {
1209
- const entries = [];
1210
- for (const { pattern, target, kind } of pairs) {
1211
- const replacement = target.startsWith(rootDir) ? target.slice(rootDir.length + 1) : target;
1212
- if (kind ? kind === "exact" : /\.\w+$/.test(replacement)) entries.push({
1213
- pattern,
1214
- replacement,
1215
- type: "exact"
1216
- });
1217
- else entries.push({
1218
- pattern: pattern.endsWith("/") ? pattern : pattern + "/",
1219
- replacement: replacement.endsWith("/") ? replacement : replacement + "/",
1220
- type: "prefix"
1221
- });
1222
- }
1223
- entries.sort((a, b) => b.pattern.length - a.pattern.length);
1224
- if (entries.length === 0) return null;
1225
- return {
1226
- json: JSON.stringify({ aliases: entries }),
1227
- count: entries.length
1228
- };
1229
- }
1230
- //#endregion
1231
- //#region pipeline/post-process-css.ts
1232
- /**
1233
- * CSS post-processing (spec: css-post-processing) — Lightning CSS
1234
- * autoprefixing, syntax lowering, and optional minification against
1235
- * browserslist targets. The single implementation consumed by both the
1236
- * Vite plugin (virtual-module serve time) and the Next.js plugin
1237
- * (ExtractionSession artifact emission).
1238
- */
1239
- /**
1240
- * Resolve browser targets for Lightning CSS.
1241
- * Priority: explicit config → project browserslist → 'defaults' fallback.
1242
- */
1243
- function resolveLightningTargets(explicitTargets, rootDir) {
1244
- let queries;
1245
- if (explicitTargets) queries = Array.isArray(explicitTargets) ? explicitTargets : [explicitTargets];
1246
- else {
1247
- const detected = browserslist(void 0, { path: rootDir });
1248
- queries = detected.length > 0 ? detected : browserslist("defaults");
1249
- }
1250
- return browserslistToTargets(Array.isArray(queries) && typeof queries[0] === "string" && queries[0].includes(" ") ? browserslist(queries) : queries);
1251
- }
1252
- /**
1253
- * Post-process CSS with Lightning CSS: autoprefixing + optional minification.
1254
- * On failure, returns the original CSS and logs a warning.
1255
- */
1256
- function postProcessCss(css, opts) {
1257
- if (!css) return css;
1258
- try {
1259
- return transform({
1260
- filename: "animus-extracted.css",
1261
- code: Buffer.from(css),
1262
- minify: opts.minify,
1263
- targets: opts.targets
1264
- }).code.toString();
1265
- } catch (e) {
1266
- const msg = e instanceof Error ? e.message : String(e);
1267
- (opts.warnFn ?? console.warn)(`[animus] Lightning CSS post-processing failed: ${msg}`);
1268
- return css;
1269
- }
1270
- }
1271
- //#endregion
1272
- //#region pipeline/manifest-diagnostics.ts
1273
- /** Stable code for selector forms with no substitutable subject.
1274
- * Mirrors the Rust constant in `extract-v2/src/eval.rs`. */
1275
- const SELECTOR_UNSUPPORTED_SUBJECT = "animus.selector.unsupported-subject";
1276
- /** Unresolved-parent chain-drop message (mirrors the Rust diagnostic in
1277
- * `extract-v2` — the ONE encoding of this message shape; consumers match
1278
- * through the helpers below, never their own regex copies). */
1279
- const UNRESOLVED_PARENT_RE = /chain dropped: could not resolve parent component '([^']+)'/;
1280
- /** True when the diagnostic reports a chain dropped for an unresolved
1281
- * parent component. */
1282
- function isUnresolvedParentDrop(diagnostic) {
1283
- return typeof diagnostic?.message === "string" && UNRESOLVED_PARENT_RE.test(diagnostic.message);
1284
- }
1285
- /** The parent binding named by an unresolved-parent drop, or null when the
1286
- * diagnostic is not one. */
1287
- function unresolvedParentName(diagnostic) {
1288
- if (typeof diagnostic?.message !== "string") return null;
1289
- return UNRESOLVED_PARENT_RE.exec(diagnostic.message)?.[1] ?? null;
1290
- }
1291
- /** True when the selector string carries at least one substitutable `&`
1292
- * subject outside quoted text (mirrors the Rust `selector_subject` walk —
1293
- * ancestor, leading, and repeated subjects all count; a `&` inside a
1294
- * quoted attribute value does not). */
1295
- function hasSelectorSubject(value) {
1296
- let quote = null;
1297
- let escaped = false;
1298
- for (const c of value) {
1299
- if (escaped) {
1300
- escaped = false;
1301
- continue;
1302
- }
1303
- if (c === "\\") {
1304
- escaped = true;
1305
- continue;
1306
- }
1307
- if (quote !== null) {
1308
- if (c === quote) quote = null;
1309
- } else if (c === "\"" || c === "'") quote = c;
1310
- else if (c === "&") return true;
1311
- }
1312
- return false;
1313
- }
1314
- /**
1315
- * Synthesize coded diagnostics for registered selector-alias values that
1316
- * look selector-shaped (`&` present) but carry no substitutable subject —
1317
- * every `&` sits inside quoted text, so there is nothing to anchor the
1318
- * class to. Ancestor-prefixed and repeated subjects are supported and pass
1319
- * validation. The system-config boundary is where these must fail loud
1320
- * (alias values never reach the evaluator's key guard).
1321
- */
1322
- function collectSelectorAliasDiagnostics(selectorAliasesJson) {
1323
- if (!selectorAliasesJson) return [];
1324
- let aliases;
1325
- try {
1326
- aliases = JSON.parse(selectorAliasesJson);
1327
- } catch {
1328
- return [];
1329
- }
1330
- const diagnostics = [];
1331
- for (const [name, value] of Object.entries(aliases)) {
1332
- if (typeof value !== "string") continue;
1333
- if (value.includes("&") && !hasSelectorSubject(value)) diagnostics.push({
1334
- file: "system",
1335
- component: name,
1336
- kind: "warn",
1337
- message: `selector alias '${name}' value '${value}' has no substitutable '&' subject outside quoted text (${SELECTOR_UNSUPPORTED_SUBJECT})`,
1338
- code: SELECTOR_UNSUPPORTED_SUBJECT,
1339
- severity: "error"
1340
- });
1341
- }
1342
- return diagnostics;
1343
- }
1344
- /**
1345
- * Surface extraction-manifest diagnostics through a plugin's warn channel.
1346
- *
1347
- * Single authoritative copy for both extraction plugins — and the single
1348
- * strict-escalation policy point: error-severity diagnostics throw one
1349
- * Error naming every offender when `policy.strict`, and print as warnings
1350
- * otherwise. Surfaces `bail` (component not extracted), `skip` (component
1351
- * skipped), and `warn` kinds; unknown kinds stay silent. Printed lines
1352
- * include the diagnostic code when the message doesn't already carry it.
1353
- */
1354
- function surfaceManifestDiagnostics(manifest, warn, policy = {}) {
1355
- const errors = [];
1356
- const diagnostics = policy.prepend?.length ? [...policy.prepend, ...manifest.diagnostics ?? []] : manifest.diagnostics ?? [];
1357
- for (const diagnostic of diagnostics) {
1358
- let line = null;
1359
- if (diagnostic.kind === "bail") line = `⚠ ${diagnostic.component} not extracted: ${diagnostic.message}`;
1360
- else if (diagnostic.kind === "skip") line = `⚠ ${diagnostic.component}: skipped ${diagnostic.message}`;
1361
- else if (diagnostic.kind === "warn") line = `⚠ ${diagnostic.file}: ${diagnostic.component}: ${diagnostic.message}`;
1362
- if (line === null) continue;
1363
- if (diagnostic.code && !diagnostic.message.includes(diagnostic.code)) line += ` [${diagnostic.code}]`;
1364
- if (policy.strict && diagnostic.severity === "error") {
1365
- errors.push(`${diagnostic.code ?? "error"} — ${diagnostic.component}: ${diagnostic.message}`);
1366
- continue;
1367
- }
1368
- warn(line);
1369
- }
1370
- if (errors.length > 0) throw new Error(`[animus] strict: ${errors.length} error diagnostic(s):\n${errors.join("\n")}`);
1371
- }
1372
- //#endregion
1373
- //#region pipeline/unit-fallback.ts
1374
- /**
1375
- * Append `px` to bare numeric values in CSS declarations for properties
1376
- * that expect length units. Unitless properties are preserved as-is.
1377
- * Numbers inside CSS function calls (cubic-bezier, rgb, calc, etc.) are skipped.
1378
- */
1379
- function applyUnitFallback(css) {
1380
- return css.replace(/([a-z-]+)\s*:\s*([^;{}]+);/g, (match, prop, value) => {
1381
- if (isUnitlessProperty(prop)) return match;
1382
- let depth = 0;
1383
- let fixed = "";
1384
- let i = 0;
1385
- while (i < value.length) if (value[i] === "(") {
1386
- depth++;
1387
- fixed += value[i];
1388
- i++;
1389
- } else if (value[i] === ")") {
1390
- depth--;
1391
- fixed += value[i];
1392
- i++;
1393
- } else if (depth > 0) {
1394
- fixed += value[i];
1395
- i++;
1396
- } else {
1397
- const numMatch = value.slice(i).match(/^(-?\d+\.?\d*)/);
1398
- if (numMatch) {
1399
- const num = numMatch[1];
1400
- const after = value[i + num.length];
1401
- if (after && /[a-z%]/i.test(after)) fixed += num;
1402
- else fixed += num + "px";
1403
- i += num.length;
1404
- } else {
1405
- fixed += value[i];
1406
- i++;
1407
- }
1408
- }
1409
- return fixed !== value ? `${prop}:${fixed};` : match;
1410
- });
1411
- }
1412
- //#endregion
1413
- //#region pipeline/run-analysis.ts
1414
- /**
1415
- * Build the named `analyzeProject` input set from analysis options. Also
1416
- * the persistence shape for `.animus/analysis-inputs.json` — an isolated
1417
- * process can replay the analysis from exactly this object
1418
- * (spec: next-turbopack-integration).
1419
- */
1420
- function buildAnalysisInputs(opts) {
1421
- return {
1422
- filesJson: JSON.stringify(opts.fileEntries),
1423
- scalesJson: opts.system.scalesJson,
1424
- variableMapJson: opts.system.variableMapJson,
1425
- contextualVarsJson: opts.system.contextualVarsJson,
1426
- propConfigJson: opts.system.propConfigJson,
1427
- groupRegistryJson: opts.system.groupRegistryJson,
1428
- packageResolutionJson: JSON.stringify(opts.packageMap),
1429
- devMode: opts.devMode,
1430
- emitterConfigJson: JSON.stringify({
1431
- runtime_import: opts.emitter.runtimeImport,
1432
- css_module_id: opts.emitter.cssModuleId,
1433
- ...opts.emitter.systemPropsModuleId ? { system_props_module_id: opts.emitter.systemPropsModuleId } : {}
1434
- }),
1435
- selectorAliasesJson: opts.system.selectorAliasesJson,
1436
- globalStyleBlocksJson: opts.system.globalStyleBlocksJson,
1437
- pathAliasesJson: opts.pathAliasesJson,
1438
- keyframesJson: opts.system.keyframesJson,
1439
- staticCssJson: opts.staticCssJson ?? null,
1440
- conditionAliasesJson: opts.system.conditionAliasesJson ?? null,
1441
- transformSourcesJson: opts.system.transformSourcesJson ?? null,
1442
- externalDirsJson: opts.externalDirs?.length && hasSourceThemeManifests(opts.system) ? JSON.stringify(opts.externalDirs) : null
1443
- };
1444
- }
1445
- /** Whether the loader captured at least one source built-theme manifest. */
1446
- function hasSourceThemeManifests(system) {
1447
- const json = system.sourceThemeManifestsJson;
1448
- return typeof json === "string" && json.length > 0 && json !== "{}";
1449
- }
1450
- /**
1451
- * The one analysis invocation both plugins share: build the emitter
1452
- * config, serialize inputs, call the NAPI `analyzeProject`, parse the
1453
- * manifest, surface its diagnostics, and resolve the CSS outputs.
1454
- *
1455
- * Error handling stays at the call site (strict-mode throw vs warn).
1456
- */
1457
- function runProjectAnalysis(engineApi, opts) {
1458
- const { analyzeProject } = engineApi();
1459
- let t = performance.now();
1460
- const inputs = buildAnalysisInputs(opts);
1461
- const serializeMs = Math.round(performance.now() - t);
1462
- t = performance.now();
1463
- const manifestJson = analyzeProject(...buildAnalyzeProjectArgs(inputs));
1464
- const extractMs = Math.round(performance.now() - t);
1465
- t = performance.now();
1466
- const manifest = JSON.parse(manifestJson);
1467
- surfaceManifestDiagnostics(manifest, opts.warn, {
1468
- strict: opts.strict,
1469
- prepend: [...collectSelectorAliasDiagnostics(opts.system.selectorAliasesJson), ...opts.extraDiagnostics ?? []]
1470
- });
1471
- const parseMs = Math.round(performance.now() - t);
1472
- return {
1473
- manifest,
1474
- manifestJson,
1475
- globalCss: manifest?.sheets?.global || "",
1476
- componentCss: applyUnitFallback(manifest?.css || ""),
1477
- inputs,
1478
- timings: {
1479
- serializeMs,
1480
- extractMs,
1481
- parseMs
1482
- }
1483
- };
1484
- }
1485
- /**
1486
- * Clear the engine's per-file analysis cache so stale results from a prior
1487
- * build never bleed into a fresh run. Tolerates engines without the
1488
- * capability (older builds) — the probe is benign.
1489
- */
1490
- function clearEngineCache(engineApi) {
1491
- try {
1492
- const { clearAnalysisCache } = engineApi();
1493
- clearAnalysisCache();
1494
- } catch {}
1495
- }
1496
- //#endregion
1497
- //#region pipeline/static-css.ts
1498
- /** Key-sorted stringify so semantically identical configs serialize
1499
- * identically (stable analysis-inputs hashing). */
1500
- function stableStringify(value) {
1501
- if (Array.isArray(value)) return `[${value.map(stableStringify).join(",")}]`;
1502
- if (value !== null && typeof value === "object") return `{${Object.entries(value).filter(([, v]) => v !== void 0).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([k, v]) => `${JSON.stringify(k)}:${stableStringify(v)}`).join(",")}}`;
1503
- return JSON.stringify(value);
1504
- }
1505
- /** Serialize a staticCss option for the engine; null when absent/empty. */
1506
- function serializeStaticCss(config) {
1507
- if (!config) return null;
1508
- const json = stableStringify(config);
1509
- return json === "{}" ? null : json;
1510
- }
1511
- //#endregion
1512
- //#region pipeline/prefix.ts
1513
- /**
1514
- * Apply namespace prefix to a variable map, CSS variable declarations, and theme JSON.
1515
- *
1516
- * Variable map: `{ "colors.ember": "--color-ember" }` -> `{ "colors.ember": "--prefix-color-ember" }`
1517
- * Variable CSS: `--color-ember: #FF2800` -> `--prefix-color-ember: #FF2800`
1518
- * `var(--color-ember)` -> `var(--prefix-color-ember)`
1519
- * Theme JSON: `{ "colors.ember": "var(--color-ember)" }` -> `{ "colors.ember": "var(--prefix-color-ember)" }`
1520
- */
1521
- function applyPrefix(prefix, variableMapJson, variableCss, themeJson, contextualVarsJson) {
1522
- if (!prefix) return {
1523
- variableMapJson,
1524
- variableCss,
1525
- themeJson,
1526
- contextualVarsJson
1527
- };
1528
- const varRefRe = /var\(--([a-zA-Z][\w-]*)\)/g;
1529
- const map = JSON.parse(variableMapJson);
1530
- const prefixed = {};
1531
- for (const [key, varName] of Object.entries(map)) prefixed[key] = varName.startsWith("--") ? `--${prefix}-${varName.slice(2)}` : varName;
1532
- let css = variableCss;
1533
- css = css.replace(/--([a-zA-Z][\w-]*)\s*:/g, `--${prefix}-$1:`);
1534
- css = css.replace(varRefRe, `var(--${prefix}-$1)`);
1535
- const result = {
1536
- variableMapJson: JSON.stringify(prefixed),
1537
- variableCss: css
1538
- };
1539
- if (themeJson) result.themeJson = themeJson.replace(varRefRe, `var(--${prefix}-$1)`);
1540
- if (contextualVarsJson) {
1541
- const ctxVars = JSON.parse(contextualVarsJson);
1542
- const prefixedCtx = {};
1543
- for (const [scale, names] of Object.entries(ctxVars)) prefixedCtx[scale] = names.map((name) => `${prefix}-${name}`);
1544
- result.contextualVarsJson = JSON.stringify(prefixedCtx);
1545
- }
1546
- return result;
1547
- }
1548
- //#endregion
1549
- //#region pipeline/system-config.ts
1550
- /**
1551
- * Load a SystemInstance via the engine's `loadSystemModule` and normalize
1552
- * it into a SystemConfig. When `prefix` is set, CSS variable names in the
1553
- * variable map/css (and theme + contextual vars when affected) are
1554
- * namespaced via the shared `applyPrefix`.
1555
- *
1556
- * Error handling stays at the call site — the Vite plugin warns (or throws
1557
- * in strict mode) and keeps its previous config, the Next plugin lets the
1558
- * failure propagate.
1559
- */
1560
- function loadSystemConfig(engineApi, opts) {
1561
- const { loadSystemModule } = engineApi();
1562
- const config = loadSystemModule(opts.systemPath, opts.rootDir);
1563
- let scalesJson = config.scalesJson;
1564
- let variableMapJson = config.variableMapJson;
1565
- let variableCss = config.variableCss;
1566
- let contextualVarsJson = config.contextualVarsJson || null;
1567
- if (opts.prefix) {
1568
- const prefixed = applyPrefix(opts.prefix, variableMapJson, variableCss, scalesJson, contextualVarsJson || void 0);
1569
- variableMapJson = prefixed.variableMapJson;
1570
- variableCss = prefixed.variableCss;
1571
- if (prefixed.themeJson) scalesJson = prefixed.themeJson;
1572
- if (prefixed.contextualVarsJson) contextualVarsJson = prefixed.contextualVarsJson;
1573
- }
1574
- return {
1575
- propConfigJson: config.propConfig,
1576
- groupRegistryJson: config.groupRegistry,
1577
- scalesJson,
1578
- variableMapJson,
1579
- variableCss,
1580
- contextualVarsJson,
1581
- selectorAliasesJson: config.selectorAliases || null,
1582
- conditionAliasesJson: config.conditionAliases || null,
1583
- transformSourcesJson: config.transformSources || null,
1584
- globalStyleBlocksJson: config.globalStyleBlocks || null,
1585
- keyframesJson: config.keyframesBlocks || null,
1586
- dependencies: config.dependencies ?? [],
1587
- sourceThemeManifestsJson: config.sourceThemeManifests || null
1588
- };
1589
- }
1590
- //#endregion
1591
- //#region pipeline/dynamic-prop-config.ts
1592
- function buildDynamicPropConfig(dynamicProps) {
1593
- const configEntries = {};
1594
- for (const [propName, meta] of Object.entries(dynamicProps)) {
1595
- if (!meta.varName || !meta.slotClass) throw new Error(`buildDynamicPropConfig: dynamic prop '${propName}' carries no slot metadata — expected varName and slotClass, got keys [${Object.keys(meta).join(", ")}].`);
1596
- const entry = {
1597
- varName: meta.varName,
1598
- slotClass: meta.slotClass
1599
- };
1600
- if (meta.property) entry.property = meta.property;
1601
- if (meta.properties && meta.properties.length > 0) entry.properties = meta.properties;
1602
- if (meta.transformName) entry.transformName = meta.transformName;
1603
- if (meta.scaleValues && Object.keys(meta.scaleValues).length > 0) entry.scaleValues = meta.scaleValues;
1604
- configEntries[propName] = entry;
1605
- }
1606
- return configEntries;
1607
- }
1608
- //#endregion
1609
- //#region pipeline/system-props-module.ts
1610
- /**
1611
- * Build the source of the runtime system-props module — served as
1612
- * `virtual:animus/system-props` by the Vite plugin and written to
1613
- * `.animus/system-props.js` by the Next plugin. One generator so the two
1614
- * runtimes can never drift.
1615
- *
1616
- * Runtime transform functions for dynamic props are not yet supported
1617
- * (transforms are resolved at extraction time via boa_engine in Rust), so
1618
- * `transforms` defaults to an empty object literal.
1619
- *
1620
- * `dynamicPropConfig` entries carry the CSS property the slot class declares
1621
- * — the runtime's unit-fallback decision. Their field order and omission
1622
- * rules belong to buildDynamicPropConfig.
1623
- */
1624
- function buildSystemPropsModule(opts) {
1625
- const dynamicPropConfig = buildDynamicPropConfig(opts.dynamicProps);
1626
- return `export const systemPropMap = ${opts.systemPropMapJson};\nexport const systemPropGroups = ${opts.groupRegistryJson};\nexport const dynamicPropConfig = ${JSON.stringify(dynamicPropConfig)};\nexport const transforms = ${opts.transformsSource ?? "{}"};\n`;
1627
- }
1628
- //#endregion
1629
- //#region pipeline/timing-waterfall.ts
1630
- /**
1631
- * Rust-side timing phases as reported in `manifest.timing`, in waterfall
1632
- * order, with their display labels. Mirrors the timing struct in the
1633
- * extract-v2 crate — a renamed or added Rust phase is updated here once,
1634
- * not per plugin.
1635
- */
1636
- const RUST_TIMING_PHASES = [
1637
- ["parseAndWalk", "parse+walk"],
1638
- ["importResolution", "imports"],
1639
- ["extensionProvenance", "provenance"],
1640
- ["topologicalSort", "topo-sort"],
1641
- ["chainEvaluation", "chains"],
1642
- ["jsxScanning", "jsx-scan"],
1643
- ["systemPropAggregation", "sys-props"],
1644
- ["usageLedger", "usage"],
1645
- ["reconciliation", "reconcile"],
1646
- ["cssGeneration", "css-gen"],
1647
- ["manifestSerialization", "serialize"]
1648
- ];
1649
- /**
1650
- * Format the Rust timing waterfall as log lines. `indent` and `labelWidth`
1651
- * let each plugin keep its established column layout; the phase table and
1652
- * the `(N files, M cached)` suffix are shared.
1653
- */
1654
- function formatRustTimingWaterfall(timing, opts) {
1655
- const lines = [];
1656
- for (const [key, label] of RUST_TIMING_PHASES) {
1657
- const ms = timing[key] ?? 0;
1658
- const pad = " ".repeat(Math.max(0, opts.labelWidth - label.length));
1659
- const extra = key === "parseAndWalk" ? ` (${timing.fileCount ?? 0} files, ${timing.cacheHits ?? 0} cached)` : "";
1660
- lines.push(`${opts.indent}${label}${pad}${String(ms).padStart(5)}ms${extra}`);
1661
- }
1662
- return lines;
1663
- }
1664
- //#endregion
1665
- //#region pipeline/tsconfig-paths.ts
1666
- /**
1667
- * tsconfig `paths` → alias pairs for the Rust `pathAliasesJson` contract
1668
- * (via `buildPathAliasesJson`). Used by drivers that cannot harvest aliases
1669
- * from a live bundler config — Turbopack exposes none.
1670
- *
1671
- * Semantics (deliberately the TypeScript subset that matters for import
1672
- * provenance): JSONC tolerated (comments + trailing commas); `extends`
1673
- * chains followed (string or array; missing parents and cycles skipped);
1674
- * the NEAREST config declaring `paths` wins wholesale (TS replaces the
1675
- * object, never merges); targets resolve against the nearest `baseUrl`
1676
- * (resolved from its declaring config's directory) or, absent one, the
1677
- * directory of the config declaring `paths`; first target per pattern.
1678
- * `x/*` patterns become prefix pairs, non-wildcard patterns exact pairs,
1679
- * bare `*` catch-alls and mid-pattern wildcards are skipped.
1680
- */
1681
- /** String-aware JSONC → JSON: strips // and block comments + trailing commas. */
1682
- function stripJsonc(text) {
1683
- let out = "";
1684
- let inString = false;
1685
- let inLine = false;
1686
- let inBlock = false;
1687
- for (let i = 0; i < text.length; i++) {
1688
- const ch = text[i];
1689
- const next = text[i + 1];
1690
- if (inLine) {
1691
- if (ch === "\n") {
1692
- inLine = false;
1693
- out += ch;
1694
- }
1695
- continue;
1696
- }
1697
- if (inBlock) {
1698
- if (ch === "*" && next === "/") {
1699
- inBlock = false;
1700
- i++;
1701
- }
1702
- continue;
1703
- }
1704
- if (inString) {
1705
- out += ch;
1706
- if (ch === "\\") {
1707
- out += next ?? "";
1708
- i++;
1709
- } else if (ch === "\"") inString = false;
1710
- continue;
1711
- }
1712
- if (ch === "\"") {
1713
- inString = true;
1714
- out += ch;
1715
- continue;
1716
- }
1717
- if (ch === "/" && next === "/") {
1718
- inLine = true;
1719
- i++;
1720
- continue;
1721
- }
1722
- if (ch === "/" && next === "*") {
1723
- inBlock = true;
1724
- i++;
1725
- continue;
1726
- }
1727
- out += ch;
1728
- }
1729
- return out.replace(/,(\s*[}\]])/g, "$1");
1730
- }
1731
- function readConfig(path) {
1732
- let raw;
1733
- try {
1734
- raw = readFileSync(path, "utf-8");
1735
- } catch {
1736
- return null;
1737
- }
1738
- try {
1739
- const json = JSON.parse(stripJsonc(raw));
1740
- return {
1741
- dir: dirname(path),
1742
- compilerOptions: json.compilerOptions ?? {},
1743
- extends: json.extends
1744
- };
1745
- } catch {
1746
- return null;
1747
- }
1748
- }
1749
- function resolveExtendsTarget(specifier, fromDir) {
1750
- if (specifier.startsWith(".") || isAbsolute(specifier)) {
1751
- const base = resolve(fromDir, specifier);
1752
- for (const candidate of [
1753
- base,
1754
- `${base}.json`,
1755
- join(base, "tsconfig.json")
1756
- ]) if (existsSync(candidate)) return candidate;
1757
- return null;
1758
- }
1759
- try {
1760
- return __require.resolve(specifier.endsWith(".json") ? specifier : `${specifier}/tsconfig.json`, { paths: [fromDir] });
1761
- } catch {
1762
- try {
1763
- return __require.resolve(specifier, { paths: [fromDir] });
1764
- } catch {
1765
- return null;
1766
- }
1767
- }
1768
- }
1769
- /** Child-first flattened extends chain starting at `entryPath`. */
1770
- function loadChain(entryPath) {
1771
- const chain = [];
1772
- const visited = /* @__PURE__ */ new Set();
1773
- const queue = [entryPath];
1774
- while (queue.length > 0) {
1775
- const key = resolve(queue.shift());
1776
- if (visited.has(key)) continue;
1777
- visited.add(key);
1778
- const node = readConfig(key);
1779
- if (!node) continue;
1780
- chain.push(node);
1781
- const parents = Array.isArray(node.extends) ? node.extends : node.extends !== void 0 ? [node.extends] : [];
1782
- for (const parent of parents) {
1783
- if (typeof parent !== "string") continue;
1784
- const resolved = resolveExtendsTarget(parent, node.dir);
1785
- if (resolved) queue.push(resolved);
1786
- }
1787
- }
1788
- return chain;
1789
- }
1790
- /**
1791
- * Read the project's tsconfig path aliases as pairs consumable by
1792
- * `buildPathAliasesJson`. Returns an empty array when no readable tsconfig
1793
- * (or no usable `paths`) exists.
1794
- */
1795
- function readTsconfigAliasPairs(rootDir) {
1796
- const chain = loadChain(join(rootDir, "tsconfig.json"));
1797
- if (chain.length === 0) return [];
1798
- const pathsOwner = chain.find((node) => node.compilerOptions.paths && typeof node.compilerOptions.paths === "object");
1799
- if (!pathsOwner) return [];
1800
- const paths = pathsOwner.compilerOptions.paths;
1801
- const baseOwner = chain.find((node) => typeof node.compilerOptions.baseUrl === "string");
1802
- const base = baseOwner ? resolve(baseOwner.dir, baseOwner.compilerOptions.baseUrl) : pathsOwner.dir;
1803
- const pairs = [];
1804
- for (const [pattern, targets] of Object.entries(paths)) {
1805
- const target = Array.isArray(targets) ? targets[0] : void 0;
1806
- if (typeof target !== "string") continue;
1807
- const patternStars = pattern.split("*").length - 1;
1808
- const targetStars = target.split("*").length - 1;
1809
- if (pattern === "*" || patternStars > 1 || targetStars > 1) continue;
1810
- if (pattern.endsWith("/*")) {
1811
- if (!target.endsWith("/*")) continue;
1812
- pairs.push({
1813
- pattern: pattern.slice(0, -2),
1814
- target: resolve(base, target.slice(0, -2)),
1815
- kind: "prefix"
1816
- });
1817
- continue;
1818
- }
1819
- if (patternStars > 0 || targetStars > 0) continue;
1820
- pairs.push({
1821
- pattern,
1822
- target: resolve(base, target),
1823
- kind: "exact"
1824
- });
1825
- }
1826
- return pairs;
1827
- }
1828
- //#endregion
1829
- //#region pipeline/error-diagnostics.ts
1830
- /**
1831
- * Throw when the diagnostics carry any `kind: "error"` entry — one
1832
- * aggregated `Error` naming EVERY offender (component, file, message — one
1833
- * line per entry, each prefixed `[animus]`). Warning-only diagnostics
1834
- * (`bail`/`skip`/`warn`, any severity) never trip this gate; their routing
1835
- * stays with `surfaceManifestDiagnostics`. Callers accept the manifest only
1836
- * past this point, so no stylesheet from a failing analysis is published.
1837
- */
1838
- function assertNoErrorDiagnostics(diagnostics) {
1839
- const errors = (diagnostics ?? []).filter((diagnostic) => diagnostic.kind === "error");
1840
- if (errors.length === 0) return;
1841
- const lines = [...new Set(errors.map((diagnostic) => `[animus] ${diagnostic.component || "<unknown component>"} (${diagnostic.file || "<unknown file>"}): ${diagnostic.message || "<no message>"}`))];
1842
- throw new Error(lines.join("\n"));
1843
- }
1844
- //#endregion
1845
- //#region pipeline/mdx-preprocessor.ts
1846
- /**
1847
- * MDX source preprocessor for the extraction pipeline.
1848
- *
1849
- * MDX files are first-class consumers of ds-built components but are not
1850
- * directly parseable by OXC (which the scanner uses for .tsx/.jsx). This
1851
- * module compiles MDX sources to scanner-consumable JSX using @mdx-js/mdx.
1852
- *
1853
- * @mdx-js/mdx is declared as `peerDependenciesMeta.optional` on the
1854
- * plugin packages that import this module. The dynamic import with
1855
- * .catch() ensures non-MDX consumers (who configure `extensions` to
1856
- * exclude .mdx) never trigger the resolution — zero install-footprint
1857
- * cost for them.
1858
- *
1859
- * The `DEFAULT_EXTENSIONS` constant is the shared source of truth for
1860
- * both `@animus-ui/vite-plugin` and `@animus-ui/next-plugin`. Each plugin
1861
- * imports it directly; independent redeclaration of default extensions
1862
- * is considered a regression.
1863
- */
1864
- const DEFAULT_EXTENSIONS = [
1865
- ".ts",
1866
- ".tsx",
1867
- ".js",
1868
- ".jsx",
1869
- ".mdx"
1870
- ];
1871
- /**
1872
- * Preprocess an MDX source string into scanner-consumable JSX.
1873
- *
1874
- * - Returns `{ kind: 'ok', source }` with JSX-compiled output on success.
1875
- * - Returns `{ kind: 'missing-dep' }` if @mdx-js/mdx is not resolvable
1876
- * (consumer needs to install it).
1877
- * - Returns `{ kind: 'error', error }` on compile failure (e.g. malformed
1878
- * MDX syntax). Plugins SHALL warn + skip affected files; the build
1879
- * continues with remaining files.
1880
- */
1881
- async function preprocessMdx(source, filename) {
1882
- const mdxMod = await import("@mdx-js/mdx").catch(() => null);
1883
- if (mdxMod === null) return { kind: "missing-dep" };
1884
- try {
1885
- const vfile = await mdxMod.compile(source, {
1886
- outputFormat: "program",
1887
- development: false,
1888
- jsx: true
1889
- });
1890
- return {
1891
- kind: "ok",
1892
- source: `/* @mdx-source: ${filename} */\n${String(vfile)}`
1893
- };
1894
- } catch (err) {
1895
- return {
1896
- kind: "error",
1897
- error: err instanceof Error ? err.message : String(err)
1898
- };
1899
- }
1900
- }
1901
- //#endregion
1902
- //#region pipeline/replacement-plans.ts
1903
- const snapshotByManifest = /* @__PURE__ */ new WeakMap();
1904
- function snapshotFilePlans(manifest) {
1905
- const memoKey = manifest !== null && typeof manifest === "object" ? manifest : null;
1906
- if (memoKey) {
1907
- const cached = snapshotByManifest.get(memoKey);
1908
- if (cached) return cached;
1909
- }
1910
- const entriesByFile = /* @__PURE__ */ new Map();
1911
- for (const [id, desc] of Object.entries(manifest?.components ?? {})) {
1912
- const file = desc.file;
1913
- if (!file) continue;
1914
- const list = entriesByFile.get(file) ?? [];
1915
- list.push([id, desc.replacement ?? ""]);
1916
- entriesByFile.set(file, list);
1917
- }
1918
- const snapshot = /* @__PURE__ */ new Map();
1919
- for (const [file, entries] of entriesByFile) {
1920
- entries.sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0);
1921
- snapshot.set(file, JSON.stringify(entries));
1922
- }
1923
- if (memoKey) snapshotByManifest.set(memoKey, snapshot);
1924
- return snapshot;
1925
- }
1926
- /**
1927
- * Rel paths whose plan changed between two snapshots: absent→present,
1928
- * present→absent, and any change to membership or replacement content.
1929
- * `exclude` drops one path (the changed file itself on the edit path — its
1930
- * own modules are already in the update set).
1931
- */
1932
- function diffFilePlans(prev, next, opts) {
1933
- const changed = /* @__PURE__ */ new Set();
1934
- for (const [file, plan] of next) if (prev.get(file) !== plan) changed.add(file);
1935
- for (const file of prev.keys()) if (!next.has(file)) changed.add(file);
1936
- if (opts?.exclude) changed.delete(opts.exclude);
1937
- return [...changed].sort();
1938
- }
1939
- /** Domain prefix keeping the epoch hash disjoint from every other
1940
- * contentHash use in the pipeline (design D5). */
1941
- const REPLACEMENT_PLANS_DOMAIN = "animus-replacement-plans-v1\0";
1942
- /** Section marker for the served-dependency witness. Leads with NUL: every
1943
- * plan entry ends `…\0` and neither file paths nor plan JSON contain NUL,
1944
- * so `\0\0` is unreachable from entry serialization alone — a snapshot can
1945
- * never forge the witness section. */
1946
- const SERVED_DEPENDENCY_DOMAIN = "\0animus-served-dependency-v1\0";
1947
- /**
1948
- * Canonical replacement epoch: contentHash over the domain-prefixed, sorted
1949
- * canonical serialization of a file-plan snapshot — each entry contributes
1950
- * `file + '\0' + plan + '\0'` (unambiguous: neither file paths nor the
1951
- * JSON plan strings contain NUL). Byte-identical plans → identical epoch;
1952
- * any membership/replacement/absent↔present change moves it.
1953
- *
1954
- * `servedDependencyWitness` extends the epoch to content the plans cannot
1955
- * see but restored modules depend on: transformed modules import the
1956
- * session's served system-props artifact, so a consumer passes that
1957
- * artifact's content here and an offline change to it moves the epoch —
1958
- * invalidating persistent-cache snapshots that reference the old epoch
1959
- * artifact. Absence and empty-string are distinct values.
1960
- *
1961
- * This is THE epoch definition — integrations consume this hash (or the
1962
- * snapshot diff) and never define their own. Epoch values compare only for
1963
- * equality (a moved value invalidates), so the serialization is free to
1964
- * evolve with a domain bump: sessions running different serializations
1965
- * simply disagree once and rebuild.
1966
- */
1967
- function hashReplacementPlans(snapshot, servedDependencyWitness) {
1968
- const entries = [...snapshot.entries()].sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0);
1969
- let serialized = REPLACEMENT_PLANS_DOMAIN;
1970
- for (const [file, plan] of entries) serialized += file + "\0" + plan + "\0";
1971
- if (servedDependencyWitness !== void 0) serialized += SERVED_DEPENDENCY_DOMAIN + servedDependencyWitness;
1972
- return contentHash(serialized);
1973
- }
1974
- //#endregion
1975
- //#region pipeline/utils.ts
1976
- /** Convert camelCase CSS property names to kebab-case. */
1977
- function camelToKebab(str) {
1978
- return str.replace(/[A-Z]/g, (m) => `-${m.toLowerCase()}`);
1979
- }
1980
- //#endregion
1981
- //#region pipeline/watch-keys.ts
1982
- /**
1983
- * Membership keys for a filesystem path in the system-dependency watch set.
1984
- *
1985
- * The loader reports symlink-resolved canonical paths; watcher events carry
1986
- * lexical absolute paths that may traverse symlinks (bun workspace links) and
1987
- * — for deletions — may no longer exist, so `realpathSync` on the event path
1988
- * alone cannot produce the canonical form. Both insertion and lookup go
1989
- * through this one normalizer: the lexical form plus a canonical form
1990
- * reconstructed through the nearest existing ancestor.
1991
- */
1992
- function toWatchKeys(input) {
1993
- const lexical = normalize(input);
1994
- const canonical = realpathThroughNearestExistingAncestor(lexical);
1995
- return canonical === lexical ? [lexical] : [lexical, canonical];
1996
- }
1997
- /**
1998
- * Canonicalize a path that may not exist: walk up to the nearest existing
1999
- * ancestor, realpath it, and re-append the missing suffix. Handles deleted
2000
- * files under still-existing (possibly symlinked) directories and atomic
2001
- * unlink/rename saves. Falls back to the input when no ancestor resolves.
2002
- *
2003
- * Known limit: a symlink retargeted AFTER the system load canonicalizes to
2004
- * the new target, which cannot match the recorded (old-target) dependency —
2005
- * the membership test then fails open (no reset), identical to not having
2006
- * this reconstruction at all. Retarget sensitivity is a resolution-input
2007
- * concern, deliberately out of scope for the watch set.
2008
- */
2009
- function realpathThroughNearestExistingAncestor(path) {
2010
- try {
2011
- return realpathSync$1(path);
2012
- } catch {}
2013
- const suffix = [];
2014
- let current = path;
2015
- for (;;) {
2016
- const parent = dirname$1(current);
2017
- if (parent === current) return path;
2018
- suffix.unshift(basename(current));
2019
- current = parent;
2020
- try {
2021
- return join$1(realpathSync$1(current), ...suffix);
2022
- } catch {}
2023
- }
2024
- }
2025
- //#endregion
2026
- export { ANIMUS_LAYERS, DEFAULT_EXTENSIONS, KEYFRAMES_EXPORT_COLLISION, KEYFRAMES_EXTERNAL_ENTRY_FAILED, RETIRED_ENGINE_MESSAGE, applyPrefix, applyUnitFallback, assembleStylesheet, assertNoErrorDiagnostics, assertNoRetiredEngineSelection, buildAnalysisInputs, buildAnalyzeProjectArgs, buildDynamicPropConfig, buildPathAliasesJson, buildSystemPropsModule, camelToKebab, clearEngineCache, collectExternalPackageSources, contentHash, createSourceIdentity, createV2EngineApi, diffFilePlans, discoverFiles, enforceExternalTokenContracts, excludeCollectedPackages, extractSystemFilePackages, findAssetSpecifiers, findPackageRoot, firstOwners, formatRustTimingWaterfall, hashReplacementPlans, isExcludedPackageRelativePath, isPathWithinRoot, isUnresolvedParentDrop, loadSystemConfig, mergeExternalKeyframes, postProcessCss, preprocessMdx, readTsconfigAliasPairs, resolveAbsolutePathSpecifier, resolveAssetFile, resolveLightningTargets, resolveThroughPathAliases, runProjectAnalysis, serializeStaticCss, sharesVolumeRoot, snapshotFilePlans, staleDistIncludesMessage, stripLeadingLayerDeclaration, substituteAssetPlaceholders, surfaceManifestDiagnostics, toWatchKeys, unresolvableIncludesMessage, unresolvedParentName, validateLayerOrder, walkPackageSources };
1
+ import { $ as CORE_OPTION_KEYS, A as createSourceIngestor, B as extractSystemFilePackages, C as resolveLightningTargets, D as resolveThroughPathAliases, E as resolveAssetFile, F as ENGINE_TRANSFORM_EXTENSIONS, G as staleDistIncludesMessage, H as firstOwners, I as preprocessMdx, J as createSourceIdentity, K as unresolvableIncludesMessage, L as adaptSvelteSource, M as isAdvisorySourceDiagnostic, N as withoutInvalidOriginals, O as findAssetSpecifiers, P as DEFAULT_EXTENSIONS, Q as AnimusConfigError, R as collectExternalPackageSources, S as postProcessCss, T as enforceExternalTokenContracts, U as isExcludedPackageRelativePath, V as findPackageRoot, W as resolveAbsolutePathSpecifier, X as sharesVolumeRoot, Y as isPathWithinRoot, Z as discoverFiles, _ as runProjectAnalysis, _t as stripLeadingLayerDeclaration, a as snapshotFilePlans, at as createExcludeMatcher, b as surfaceManifestDiagnostics, c as formatRustTimingWaterfall, ct as KEYFRAMES_EXTERNAL_ENTRY_FAILED, d as runStructuralSelfCheck, dt as RETIRED_ENGINE_MESSAGE, et as DEFAULT_EXCLUDE, f as loadSystemConfig, ft as assertNoRetiredEngineSelection, g as clearEngineCache, gt as assembleStylesheet, h as buildAnalysisInputs, ht as ANIMUS_LAYERS, i as hashReplacementPlans, it as assertKnownOptionKeys, j as ingestSourceEntries, k as substituteAssetPlaceholders, l as buildSystemPropsModule, lt as mergeExternalKeyframes, m as serializeStaticCss, mt as buildAnalyzeProjectArgs, n as camelToKebab, nt as REPLACEABLE_DEFAULT_EXCLUDE, o as assertNoErrorDiagnostics, ot as resolveMode, p as applyPrefix, pt as createV2EngineApi, q as walkPackageSources, r as diffFilePlans, rt as STRUCTURAL_EXCLUDE, s as readTsconfigAliasPairs, st as KEYFRAMES_EXPORT_COLLISION, t as toWatchKeys, tt as DRIVER_NAMESPACES, u as buildDynamicPropConfig, ut as contentHash, v as applyUnitFallback, vt as validateLayerOrder, w as buildPathAliasesJson, x as unresolvedParentName, y as isUnresolvedParentDrop, z as excludeCollectedPackages } from "./pipeline-lkbOoyAr.mjs";
2
+ export { ANIMUS_LAYERS, AnimusConfigError, CORE_OPTION_KEYS, DEFAULT_EXCLUDE, DEFAULT_EXTENSIONS, DRIVER_NAMESPACES, ENGINE_TRANSFORM_EXTENSIONS, KEYFRAMES_EXPORT_COLLISION, KEYFRAMES_EXTERNAL_ENTRY_FAILED, REPLACEABLE_DEFAULT_EXCLUDE, RETIRED_ENGINE_MESSAGE, STRUCTURAL_EXCLUDE, adaptSvelteSource, applyPrefix, applyUnitFallback, assembleStylesheet, assertKnownOptionKeys, assertNoErrorDiagnostics, assertNoRetiredEngineSelection, buildAnalysisInputs, buildAnalyzeProjectArgs, buildDynamicPropConfig, buildPathAliasesJson, buildSystemPropsModule, camelToKebab, clearEngineCache, collectExternalPackageSources, contentHash, createExcludeMatcher, createSourceIdentity, createSourceIngestor, createV2EngineApi, diffFilePlans, discoverFiles, enforceExternalTokenContracts, excludeCollectedPackages, extractSystemFilePackages, findAssetSpecifiers, findPackageRoot, firstOwners, formatRustTimingWaterfall, hashReplacementPlans, ingestSourceEntries, isAdvisorySourceDiagnostic, isExcludedPackageRelativePath, isPathWithinRoot, isUnresolvedParentDrop, loadSystemConfig, mergeExternalKeyframes, postProcessCss, preprocessMdx, readTsconfigAliasPairs, resolveAbsolutePathSpecifier, resolveAssetFile, resolveLightningTargets, resolveMode, resolveThroughPathAliases, runProjectAnalysis, runStructuralSelfCheck, serializeStaticCss, sharesVolumeRoot, snapshotFilePlans, staleDistIncludesMessage, stripLeadingLayerDeclaration, substituteAssetPlaceholders, surfaceManifestDiagnostics, toWatchKeys, unresolvableIncludesMessage, unresolvedParentName, validateLayerOrder, walkPackageSources, withoutInvalidOriginals };