@timber-js/app 0.2.0-alpha.210 → 0.2.0-alpha.211

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 (36) hide show
  1. package/dist/_chunks/{chains-BoO51joc.js → chains-DGX9zmg9.js} +5 -146
  2. package/dist/_chunks/chains-DGX9zmg9.js.map +1 -0
  3. package/dist/_chunks/classify-QwG5rxKI.js +147 -0
  4. package/dist/_chunks/classify-QwG5rxKI.js.map +1 -0
  5. package/dist/_chunks/client-dep-entries-2HCF09no.js +66 -0
  6. package/dist/_chunks/client-dep-entries-2HCF09no.js.map +1 -0
  7. package/dist/_chunks/{dev-server-v97rQH4b.js → dev-server-TFpEwm3H.js} +2 -2
  8. package/dist/_chunks/{dev-server-v97rQH4b.js.map → dev-server-TFpEwm3H.js.map} +1 -1
  9. package/dist/_chunks/{live-graph-9cSnn_h9.js → live-graph-cNuWMYQI.js} +4 -3
  10. package/dist/_chunks/{live-graph-9cSnn_h9.js.map → live-graph-cNuWMYQI.js.map} +1 -1
  11. package/dist/_chunks/{poison-scan-vGV7Re0B.js → poison-scan-CfQ3unZR.js} +2 -4
  12. package/dist/_chunks/poison-scan-CfQ3unZR.js.map +1 -0
  13. package/dist/analyze/classify.d.ts +2 -0
  14. package/dist/analyze/classify.d.ts.map +1 -1
  15. package/dist/analyze/crawl-entry.js +3 -2
  16. package/dist/analyze/crawl-entry.js.map +1 -1
  17. package/dist/analyze/graph-command.js +2 -2
  18. package/dist/analyze/poison-scan.d.ts.map +1 -1
  19. package/dist/cli.js +1 -1
  20. package/dist/index.d.ts.map +1 -1
  21. package/dist/index.js +40 -2
  22. package/dist/index.js.map +1 -1
  23. package/dist/plugins/client-dep-entries.d.ts +44 -0
  24. package/dist/plugins/client-dep-entries.d.ts.map +1 -0
  25. package/dist/plugins/content.d.ts.map +1 -1
  26. package/dist/plugins/entries.d.ts +6 -0
  27. package/dist/plugins/entries.d.ts.map +1 -1
  28. package/package.json +1 -1
  29. package/src/analyze/classify.ts +1 -1
  30. package/src/analyze/poison-scan.ts +1 -4
  31. package/src/index.ts +21 -2
  32. package/src/plugins/client-dep-entries.ts +78 -0
  33. package/src/plugins/content.ts +26 -1
  34. package/src/plugins/entries.ts +7 -0
  35. package/dist/_chunks/chains-BoO51joc.js.map +0 -1
  36. package/dist/_chunks/poison-scan-vGV7Re0B.js.map +0 -1
@@ -0,0 +1,44 @@
1
+ /**
2
+ * client-dep-entries — seed the client dep optimizer's startup scan with
3
+ * the app's `'use client'` modules.
4
+ *
5
+ * Vite's dev optimizer discovers bare imports by crawling from its
6
+ * entries before the first request. With no `optimizeDeps.entries`, the
7
+ * client environment crawls its build input — timber's browser entry —
8
+ * and nothing more: every `'use client'` module is reached only through
9
+ * the RSC payload at runtime, never through a static import the crawl
10
+ * can follow. A package imported only from client components is then
11
+ * found on the first browser request, re-optimized mid-load, and the
12
+ * page full-reloads ("optimized dependencies changed. reloading"). That
13
+ * reload can leave react and react-dom from two optimizer runs in the
14
+ * browser (duplicate React → "Invalid hook call").
15
+ *
16
+ * Listing the `'use client'` files as entries lets the startup crawl see
17
+ * those imports. Setting `entries` replaces the build-input default, so
18
+ * the browser entry is listed too. Files that gain the directive after
19
+ * startup still fall back to Vite's late discovery.
20
+ *
21
+ * Design docs: 21-dev-server.md §"Client Dependency Pre-Bundling".
22
+ */
23
+ /**
24
+ * Every project source file under `root` whose directive prologue holds
25
+ * `'use client'`. Uses the same walker as `timber graph` (node_modules,
26
+ * root-level dot dirs and build outputs skipped) and the same AST
27
+ * directive check the RSC plugin applies. Files under `excludeDir` (the
28
+ * build output) are skipped.
29
+ */
30
+ export declare function findUseClientFiles(root: string, excludeDir?: string): Promise<string[]>;
31
+ /**
32
+ * Escape a path for use as an `optimizeDeps.entries` pattern. Vite globs
33
+ * entries, and route directories are full of glob syntax: `(group)`,
34
+ * `[slug]`, `[[...catchAll]]`, `@slot`. Slashes are normalized first, so
35
+ * the only backslashes left are literal (POSIX) ones, which are escaped
36
+ * too.
37
+ */
38
+ export declare function escapeGlobPath(path: string): string;
39
+ /**
40
+ * The client environment's `optimizeDeps.entries`: timber's browser
41
+ * entry plus every `'use client'` file in the project.
42
+ */
43
+ export declare function clientOptimizeDepsEntries(root: string, browserEntryFile: string, buildDir: string): Promise<string[]>;
44
+ //# sourceMappingURL=client-dep-entries.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client-dep-entries.d.ts","sourceRoot":"","sources":["../../src/plugins/client-dep-entries.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;GAqBG;AAOH;;;;;;GAMG;AACH,wBAAsB,kBAAkB,CAAC,IAAI,EAAE,MAAM,EAAE,UAAU,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,EAAE,CAAC,CAkB7F;AAED;;;;;;GAMG;AACH,wBAAgB,cAAc,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAEnD;AAED;;;GAGG;AACH,wBAAsB,yBAAyB,CAC7C,IAAI,EAAE,MAAM,EACZ,gBAAgB,EAAE,MAAM,EACxB,QAAQ,EAAE,MAAM,GACf,OAAO,CAAC,MAAM,EAAE,CAAC,CAGnB"}
@@ -1 +1 @@
1
- {"version":3,"file":"content.d.ts","sourceRoot":"","sources":["../../src/plugins/content.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAEH,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,MAAM,CAAC;AAGnC,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,sBAAsB,CAAC;AAoB1D;;;;;GAKG;AACH,wBAAgB,aAAa,CAAC,GAAG,EAAE,aAAa,GAAG,MAAM,CAoGxD"}
1
+ {"version":3,"file":"content.d.ts","sourceRoot":"","sources":["../../src/plugins/content.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAEH,OAAO,KAAK,EAAE,MAAM,EAAgB,MAAM,MAAM,CAAC;AAGjD,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,sBAAsB,CAAC;AAyC1D;;;;;GAKG;AACH,wBAAgB,aAAa,CAAC,GAAG,EAAE,aAAa,GAAG,MAAM,CAwGxD"}
@@ -12,6 +12,12 @@
12
12
  */
13
13
  import type { Plugin } from 'vite';
14
14
  import type { PluginContext } from '../plugin-context.ts';
15
+ /**
16
+ * The real file behind virtual:timber-browser-entry. The client dep
17
+ * optimizer scans it explicitly once timber sets optimizeDeps.entries
18
+ * (see plugins/client-dep-entries.ts).
19
+ */
20
+ export declare const BROWSER_ENTRY_FILE: string;
15
21
  /**
16
22
  * Detect a user convention file at both root and src/.
17
23
  *
@@ -1 +1 @@
1
- {"version":3,"file":"entries.d.ts","sourceRoot":"","sources":["../../src/plugins/entries.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AAEH,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,MAAM,CAAC;AAInC,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,sBAAsB,CAAC;AAuK1D;;;;;GAKG;AACH,wBAAgB,oBAAoB,CAAC,IAAI,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI,CAUlF;AAED,wBAAgB,yBAAyB,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI,CAErE;AAED;;;;;;;GAOG;AACH,wBAAgB,eAAe,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI,CAE3D;AAED;;;;;;;;GAQG;AACH,wBAAgB,6BAA6B,CAAC,mBAAmB,EAAE,MAAM,GAAG,IAAI,GAAG,MAAM,CAqBxF;AAED;;;;;;;;;;;;GAYG;AACH,wBAAgB,0BAA0B,CAAC,SAAS,EAAE,MAAM,GAAG,IAAI,GAAG,MAAM,CA+B3E;AAED;;;;GAIG;AACH,wBAAgB,aAAa,CAAC,GAAG,EAAE,aAAa,GAAG,MAAM,CAiFxD"}
1
+ {"version":3,"file":"entries.d.ts","sourceRoot":"","sources":["../../src/plugins/entries.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AAEH,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,MAAM,CAAC;AAInC,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,sBAAsB,CAAC;AAsC1D;;;;GAIG;AACH,eAAO,MAAM,kBAAkB,QAA2C,CAAC;AAmI3E;;;;;GAKG;AACH,wBAAgB,oBAAoB,CAAC,IAAI,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI,CAUlF;AAED,wBAAgB,yBAAyB,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI,CAErE;AAED;;;;;;;GAOG;AACH,wBAAgB,eAAe,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI,CAE3D;AAED;;;;;;;;GAQG;AACH,wBAAgB,6BAA6B,CAAC,mBAAmB,EAAE,MAAM,GAAG,IAAI,GAAG,MAAM,CAqBxF;AAED;;;;;;;;;;;;GAYG;AACH,wBAAgB,0BAA0B,CAAC,SAAS,EAAE,MAAM,GAAG,IAAI,GAAG,MAAM,CA+B3E;AAED;;;;GAIG;AACH,wBAAgB,aAAa,CAAC,GAAG,EAAE,aAAa,GAAG,MAAM,CAiFxD"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@timber-js/app",
3
- "version": "0.2.0-alpha.210",
3
+ "version": "0.2.0-alpha.211",
4
4
  "description": "Vite-native React framework built for Servers and Serverless Platforms — correct HTTP semantics, real status codes, pages that work without JavaScript",
5
5
  "keywords": [
6
6
  "cloudflare-workers",
@@ -105,7 +105,7 @@ export interface ModuleClassification {
105
105
  }
106
106
 
107
107
  /** File extensions eligible for directive detection. */
108
- const PARSEABLE_EXTENSIONS = /\.(?:ts|tsx|js|jsx|mjs|cjs|mts|cts)$/;
108
+ export const PARSEABLE_EXTENSIONS = /\.(?:ts|tsx|js|jsx|mjs|cjs|mts|cts)$/;
109
109
 
110
110
  /**
111
111
  * Parse language for a source file, from its extension. Never force
@@ -19,7 +19,7 @@
19
19
 
20
20
  import { parseAst } from 'vite';
21
21
  import { EXPLICIT_MARKERS, INFERRED_RULES } from './poison-rules.ts';
22
- import { langForFile, type ModuleKind } from './classify.ts';
22
+ import { langForFile, PARSEABLE_EXTENSIONS, type ModuleKind } from './classify.ts';
23
23
 
24
24
  /** One poisoning finding on a module, in the JSON-contract shape. */
25
25
  export interface Poisoning {
@@ -33,9 +33,6 @@ export interface Poisoning {
33
33
  description: string;
34
34
  }
35
35
 
36
- /** File extensions the specifier scan can parse. */
37
- const PARSEABLE_EXTENSIONS = /\.(?:ts|tsx|js|jsx|mjs|cjs|mts|cts)$/;
38
-
39
36
  /**
40
37
  * A NON-EMPTY specifier list where every entry is type-only. Empty or
41
38
  * absent lists return false — a bare `import 'pkg'` is a side-effect
package/src/index.ts CHANGED
@@ -18,7 +18,7 @@ import { createRequire } from 'node:module';
18
18
  import react from '@vitejs/plugin-react';
19
19
  import { timberContent } from './plugins/content.ts';
20
20
  import { timberDevServer } from './plugins/dev-server.ts';
21
- import { timberEntries } from './plugins/entries.ts';
21
+ import { timberEntries, BROWSER_ENTRY_FILE } from './plugins/entries.ts';
22
22
  import { timberMdx } from './plugins/mdx.ts';
23
23
  import { timberRouting } from './plugins/routing.ts';
24
24
  import { timberShims } from './plugins/shims.ts';
@@ -473,9 +473,28 @@ export function timber(config?: TimberUserConfig): PluginOption[] {
473
473
  console: originalConsole as Console,
474
474
  });
475
475
 
476
+ // Seed the client optimizer's startup crawl with every 'use client'
477
+ // file so client-only packages are pre-bundled before the first
478
+ // request, not discovered mid-load (which full-reloads the page).
479
+ // Vite concatenates these with any entries the user sets.
480
+ // See design/21-dev-server.md §"Client Dependency Pre-Bundling".
481
+ let environments: Record<string, object> = envOutDirs;
482
+ if (!isPreview) {
483
+ ctx.timer.start('client-deps-scan');
484
+ // Loaded lazily: directive detection pulls in @vitejs/plugin-rsc's
485
+ // transforms, which builds and preview never need.
486
+ const { clientOptimizeDepsEntries } = await import('./plugins/client-dep-entries.ts');
487
+ const entries = await clientOptimizeDepsEntries(resolvedRoot, BROWSER_ENTRY_FILE, buildDir);
488
+ ctx.timer.end('client-deps-scan');
489
+ environments = {
490
+ ...envOutDirs,
491
+ client: { ...envOutDirs.client, optimizeDeps: { entries } },
492
+ };
493
+ }
494
+
476
495
  return {
477
496
  build: { outDir: buildOutDir },
478
- environments: envOutDirs,
497
+ environments,
479
498
  optimizeDeps: { exclude: timberOptimizeDepsExclude },
480
499
  customLogger,
481
500
  server: serverConfig,
@@ -0,0 +1,78 @@
1
+ /**
2
+ * client-dep-entries — seed the client dep optimizer's startup scan with
3
+ * the app's `'use client'` modules.
4
+ *
5
+ * Vite's dev optimizer discovers bare imports by crawling from its
6
+ * entries before the first request. With no `optimizeDeps.entries`, the
7
+ * client environment crawls its build input — timber's browser entry —
8
+ * and nothing more: every `'use client'` module is reached only through
9
+ * the RSC payload at runtime, never through a static import the crawl
10
+ * can follow. A package imported only from client components is then
11
+ * found on the first browser request, re-optimized mid-load, and the
12
+ * page full-reloads ("optimized dependencies changed. reloading"). That
13
+ * reload can leave react and react-dom from two optimizer runs in the
14
+ * browser (duplicate React → "Invalid hook call").
15
+ *
16
+ * Listing the `'use client'` files as entries lets the startup crawl see
17
+ * those imports. Setting `entries` replaces the build-input default, so
18
+ * the browser entry is listed too. Files that gain the directive after
19
+ * startup still fall back to Vite's late discovery.
20
+ *
21
+ * Design docs: 21-dev-server.md §"Client Dependency Pre-Bundling".
22
+ */
23
+
24
+ import { readFile } from 'node:fs/promises';
25
+ import { sep } from 'node:path';
26
+ import { detectDirective, PARSEABLE_EXTENSIONS } from '../analyze/classify.ts';
27
+ import { normalizeSlashes, scanProjectSourceFiles } from '../analyze/scan.ts';
28
+
29
+ /**
30
+ * Every project source file under `root` whose directive prologue holds
31
+ * `'use client'`. Uses the same walker as `timber graph` (node_modules,
32
+ * root-level dot dirs and build outputs skipped) and the same AST
33
+ * directive check the RSC plugin applies. Files under `excludeDir` (the
34
+ * build output) are skipped.
35
+ */
36
+ export async function findUseClientFiles(root: string, excludeDir?: string): Promise<string[]> {
37
+ const files: string[] = [];
38
+ // An unreadable directory only means its client deps are discovered
39
+ // late, through Vite's normal fallback — never fatal for dev startup.
40
+ await scanProjectSourceFiles(root, files, () => {}, 0, PARSEABLE_EXTENSIONS);
41
+ const excludePrefix = excludeDir ? excludeDir + sep : undefined;
42
+ const candidates = excludePrefix ? files.filter((f) => !f.startsWith(excludePrefix)) : files;
43
+
44
+ const matches = await Promise.all(
45
+ candidates.map(async (file) => {
46
+ const code = await readFile(file, 'utf8').catch(() => null);
47
+ // Cheap text gate before parsing: a directive is a literal
48
+ // without escapes, so a file lacking the text cannot carry it.
49
+ if (code === null || !code.includes('use client')) return null;
50
+ return detectDirective(code, file) === 'use client' ? file : null;
51
+ })
52
+ );
53
+ return matches.filter((file): file is string => file !== null);
54
+ }
55
+
56
+ /**
57
+ * Escape a path for use as an `optimizeDeps.entries` pattern. Vite globs
58
+ * entries, and route directories are full of glob syntax: `(group)`,
59
+ * `[slug]`, `[[...catchAll]]`, `@slot`. Slashes are normalized first, so
60
+ * the only backslashes left are literal (POSIX) ones, which are escaped
61
+ * too.
62
+ */
63
+ export function escapeGlobPath(path: string): string {
64
+ return normalizeSlashes(path).replace(/[\\()[\]{}*?|!+@]/g, '\\$&');
65
+ }
66
+
67
+ /**
68
+ * The client environment's `optimizeDeps.entries`: timber's browser
69
+ * entry plus every `'use client'` file in the project.
70
+ */
71
+ export async function clientOptimizeDepsEntries(
72
+ root: string,
73
+ browserEntryFile: string,
74
+ buildDir: string
75
+ ): Promise<string[]> {
76
+ const clientFiles = await findUseClientFiles(root, buildDir);
77
+ return [browserEntryFile, ...clientFiles].map(escapeGlobPath);
78
+ }
@@ -8,7 +8,7 @@
8
8
  * Design doc: 20-content-collections.md §"Content Collections"
9
9
  */
10
10
 
11
- import type { Plugin } from 'vite';
11
+ import type { Plugin, PluginOption } from 'vite';
12
12
  import { existsSync } from 'node:fs';
13
13
  import { join } from 'node:path';
14
14
  import type { PluginContext } from '../plugin-context.ts';
@@ -31,6 +31,27 @@ function findConfigFile(root: string): string | undefined {
31
31
  return undefined;
32
32
  }
33
33
 
34
+ /** The name @content-collections/vite gives its plugin. */
35
+ const CONTENT_COLLECTIONS_PLUGIN_NAME = 'content-collections';
36
+
37
+ /**
38
+ * Whether the user's own config already registers @content-collections/vite.
39
+ * Walks nested arrays and awaits promised plugins, the same PluginOption
40
+ * shapes Vite flattens (and has already resolved by the time config hooks
41
+ * run, so awaiting here costs nothing).
42
+ */
43
+ async function registersContentCollections(plugins: PluginOption[] | undefined): Promise<boolean> {
44
+ for (const option of plugins ?? []) {
45
+ const plugin = await option;
46
+ if (Array.isArray(plugin)) {
47
+ if (await registersContentCollections(plugin)) return true;
48
+ } else if (plugin && 'name' in plugin && plugin.name === CONTENT_COLLECTIONS_PLUGIN_NAME) {
49
+ return true;
50
+ }
51
+ }
52
+ return false;
53
+ }
54
+
34
55
  /**
35
56
  * Create the timber-content Vite plugin.
36
57
  *
@@ -75,6 +96,10 @@ export function timberContent(ctx: PluginContext): Plugin {
75
96
  name: 'timber-content',
76
97
 
77
98
  async config(config, env) {
99
+ // Two registrations start two builders and two watchers that race on
100
+ // the same cache ("Failed to parse the cache mapping"). The user's
101
+ // own registration, with its options, wins.
102
+ if (await registersContentCollections(config.plugins)) return;
78
103
  const root = config.root ?? ctx.root;
79
104
  ctx.timer.start('content-activate');
80
105
  await activate(root);
@@ -53,6 +53,13 @@ const ENTRY_FILE_MAP: Record<string, string> = {
53
53
  [VIRTUAL_IDS.browserEntry]: resolve(SRC_DIR, 'client', 'browser-entry', 'index.ts'),
54
54
  };
55
55
 
56
+ /**
57
+ * The real file behind virtual:timber-browser-entry. The client dep
58
+ * optimizer scans it explicitly once timber sets optimizeDeps.entries
59
+ * (see plugins/client-dep-entries.ts).
60
+ */
61
+ export const BROWSER_ENTRY_FILE = ENTRY_FILE_MAP[VIRTUAL_IDS.browserEntry];
62
+
56
63
  /** The \0-prefixed resolved ID for virtual:timber-config */
57
64
  const RESOLVED_CONFIG_ID = `\0${VIRTUAL_IDS.config}`;
58
65
 
@@ -1 +0,0 @@
1
- {"version":3,"file":"chains-BoO51joc.js","names":[],"sources":["../../src/analyze/classify.ts","../../src/analyze/chains.ts"],"sourcesContent":["/**\n * classify — environment-graph classification for project modules.\n *\n * The one classification module every frontend shares (design/47): the\n * `timber graph` CLI, the dev-server endpoint, the VS Code extension,\n * and the cold crawl must never disagree about a file's environment.\n * Classification intersects RSC/SSR module-graph membership with\n * first-directive detection to produce the decided taxonomy:\n *\n * - `server` — RSC graph only\n * - `client-boundary` — has `'use client'`\n * - `client-internal` — reachable only behind a boundary, no directive\n * - `shared` — instantiated in both environments; INFO, never a\n * warning — shared-by-design is a legitimate pattern\n * - `server-action` — has `'use server'`\n * - `unreferenced` — in no graph and no provisional signal; files with\n * a directive or filename convention get that\n * provisional kind instead, marked `pending`\n *\n * The browser (`client`) Vite graph stays empty until a real browser\n * requests modules, so membership is RSC × SSR — the SSR graph is a\n * faithful proxy for the client tree (design/47 §8, with the frontier\n * caveat below).\n *\n * Design docs: 47-module-environment-tooling.md (taxonomy, §8),\n * 43-analyze-cli.md (directive detection rules).\n */\n\nimport { basename, extname } from 'node:path';\nimport { parseAst, normalizePath } from 'vite';\nimport { hasDirective } from '../rsc-runtime/transforms.ts';\nimport { isRouteConventionFile } from '../routing/scanner.ts';\nimport {\n isDynamicMetadataExtension,\n isStaticMetadataExtension,\n} from '../server/metadata-routes.ts';\n\n/** The statement-list shape hasDirective consumes (estree Program body). */\ntype DirectiveBody = Parameters<typeof hasDirective>[0];\n\nexport type ModuleKind =\n | 'server'\n | 'client-boundary'\n | 'client-internal'\n | 'shared'\n | 'server-action'\n | 'unreferenced';\n\nexport type Directive = 'use client' | 'use server' | null;\n\n/**\n * What a frontend observed about one project module. Graph membership\n * comes from the live dev-server graphs or the cold crawl; the directive\n * comes from the module's original source (never the transformed output,\n * where the RSC plugin has already stripped or proxied it).\n */\nexport interface ModuleObservation {\n /** Absolute path of the source file. */\n file: string;\n /** Present in the RSC environment's module graph. */\n inRsc: boolean;\n /** Present in the SSR environment's module graph. */\n inSsr: boolean;\n /**\n * Present in the browser (`client`) environment's module graph. Only a\n * live dev server with a real connected browser can confirm this — the\n * client graph stays empty otherwise (design/47 §8) — so the cold\n * crawl always observes false. Defaults to false.\n */\n inClient?: boolean;\n /**\n * False when the SSR graph has a node for this file but Vite never\n * transformed it — the §8 signature of a module behind an unexecuted\n * dynamic import (`transformResult == null`). Its own membership is\n * trustworthy; its subtree is not. Defaults to true.\n */\n ssrTransformed?: boolean;\n /** First directive of the original source, or null. */\n directive: Directive;\n}\n\nexport interface ModuleClassification {\n file: string;\n kind: ModuleKind;\n /**\n * Raw per-environment graph membership, in doc 43's classification\n * vocabulary (`{ client, ssr, rsc }`). `kind` is the interpreted\n * answer; this is the evidence. `client` is confirmable only by a\n * live browser graph — static scans always report false.\n */\n envs: { rsc: boolean; ssr: boolean; client: boolean };\n /**\n * True when no graph has confirmed this module — the kind is\n * provisional, derived from directive + filename convention, and\n * frontends must visibly mark it \"pending\" (design/47 §2).\n */\n pending: boolean;\n /**\n * §8 frontier: the module is reachable (it ships to the browser) but\n * was never transformed, so modules behind it may be missing from the\n * graphs entirely. Consumers should transform-on-demand or surface\n * \"reachable, subtree unknown\".\n */\n subtreeUnknown: boolean;\n}\n\n/** File extensions eligible for directive detection. */\nconst PARSEABLE_EXTENSIONS = /\\.(?:ts|tsx|js|jsx|mjs|cjs|mts|cts)$/;\n\n/**\n * Parse language for a source file, from its extension. Never force\n * `tsx` onto plain `.ts`: JSX-ambiguous TypeScript such as\n * `const identity = <T>(value: T) => value` is valid TS but rejected\n * by a TSX parse, and the resulting parse failure would silently drop\n * the file's directive and poison signals. Plain JS parses as `jsx`\n * (JSX-in-.js is common in Vite projects and JS has no generic-arrow\n * ambiguity for the x-syntax to break).\n */\nexport function langForFile(file: string): 'ts' | 'tsx' | 'jsx' {\n if (/\\.tsx$/.test(file)) return 'tsx';\n if (/\\.[mc]?ts$/.test(file)) return 'ts';\n return 'jsx';\n}\n\n/**\n * Detect the first directive of a module's original source.\n *\n * Never string-match or regex directives (design/43): `hasDirective`\n * from @vitejs/plugin-rsc checks for the `directive` property on\n * ExpressionStatements — the same check the RSC plugin runs to decide\n * boundaries, so classification agrees with what the framework actually\n * does with the file. The directive must be in prologue position (before\n * any import or statement) per the ECMAScript spec. Non-JS sources\n * (CSS, MDX, assets) and sources that fail to parse return null — no\n * directive is a safe default; classification then falls back to graph\n * membership.\n */\nexport function detectDirective(code: string, file: string): Directive {\n if (!PARSEABLE_EXTENSIONS.test(file)) return null;\n let body: DirectiveBody;\n try {\n // Vite's parseAst returns oxc-typed nodes; hasDirective expects the\n // estree shapes. They are structurally identical for the top-level\n // statement scan — the same bridge the rest of the codebase uses\n // (plugin-context.ts parse memo, routing/export-detect.ts).\n body = parseAst(code, { lang: langForFile(file) }).body as unknown as DirectiveBody;\n } catch {\n return null;\n }\n if (hasDirective(body, 'use client')) return 'use client';\n if (hasDirective(body, 'use server')) return 'use server';\n return null;\n}\n\n/** Optional context for classification. */\nexport interface ClassifyContext {\n /**\n * Absolute path of the app directory. When provided, convention-based\n * provisional classification only applies to files inside it — a\n * `lib/page.tsx` is not a route file, and the scanner would never\n * recognize it there.\n */\n appDir?: string;\n /**\n * Configured pageExtensions, when the caller has resolved the app\n * config. Omitted → scanner defaults.\n */\n pageExtensions?: readonly string[];\n}\n\n/**\n * Whether a file is a route-convention source the framework itself\n * imports (page/layout/route/… plus metadata routes). Conventions are\n * derived from the routing scanner and the metadata route table — never\n * a local duplicate list (drift lesson). Each family carries the\n * scanner's own extension rules.\n *\n * Shared by the provisional classifier below and by chains.ts, whose\n * RSC-side walks terminate at the first route-convention file\n * (design/47 §7) — the two must never disagree about what counts.\n *\n * `pageExtensions` mirrors the scanner's parameter: callers that have\n * resolved the app config pass the configured set (a `page.mdx` app);\n * callers without config access fall back to the defaults and tolerate\n * the mismatch.\n */\nexport function isConventionSourceFile(file: string, pageExtensions?: readonly string[]): boolean {\n const ext = extname(file).slice(1);\n const base = basename(file, `.${ext}`);\n return (\n isRouteConventionFile(base, ext, pageExtensions) ||\n isStaticMetadataExtension(base, ext) ||\n isDynamicMetadataExtension(base, ext)\n );\n}\n\n/**\n * Provisional kind for a file no graph has confirmed (design/47 §2):\n * directive first, then filename convention, else `unreferenced`.\n */\nfunction provisionalKind(file: string, directive: Directive, ctx?: ClassifyContext): ModuleKind {\n if (directive === 'use client') return 'client-boundary';\n if (directive === 'use server') return 'server-action';\n // Normalize both sides before the containment check: on Windows,\n // `file` may arrive slash-normalized (Vite module-node paths are)\n // while appDir comes from node:path with backslashes — comparing raw\n // would misreport every provisional route file as unreferenced.\n if (ctx?.appDir && !normalizePath(file).startsWith(normalizePath(ctx.appDir) + '/')) {\n return 'unreferenced';\n }\n if (isConventionSourceFile(file, ctx?.pageExtensions)) return 'server';\n return 'unreferenced';\n}\n\n/**\n * Classify one module from its observation. Pure — all frontends call\n * this with membership data from their own graph source.\n */\nexport function classifyModule(\n obs: ModuleObservation,\n ctx?: ClassifyContext\n): ModuleClassification {\n const referenced = obs.inRsc || obs.inSsr || obs.inClient === true;\n const subtreeUnknown = obs.inSsr && obs.ssrTransformed === false;\n const envs = { rsc: obs.inRsc, ssr: obs.inSsr, client: obs.inClient === true };\n\n if (!referenced) {\n return {\n file: obs.file,\n kind: provisionalKind(obs.file, obs.directive, ctx),\n envs,\n pending: true,\n subtreeUnknown: false,\n };\n }\n\n // Directive wins over membership: a 'use client' file also has an RSC\n // graph node (the client-reference proxy), and a 'use server' module\n // appears in the SSR graph when referenced from client forms — the\n // directive is what those memberships mean.\n let kind: ModuleKind;\n if (obs.directive === 'use client') kind = 'client-boundary';\n else if (obs.directive === 'use server') kind = 'server-action';\n else if (obs.inRsc && obs.inSsr) kind = 'shared';\n else if (obs.inRsc) kind = 'server';\n else kind = 'client-internal';\n\n return { file: obs.file, kind, envs, pending: false, subtreeUnknown };\n}\n\n/** Classify a batch of observations, sorted by file for stable output. */\nexport function classifyModules(\n observations: Iterable<ModuleObservation>,\n ctx?: ClassifyContext\n): ModuleClassification[] {\n return [...observations]\n .map((obs) => classifyModule(obs, ctx))\n .sort((a, b) => (a.file < b.file ? -1 : a.file > b.file ? 1 : 0));\n}\n","/**\n * chains — boundary-aware import-chain stitching (the \"why\" answer).\n *\n * The human-meaningful import chain for a client-reachable module is a\n * JOIN of two graphs: RSC-graph importers ABOVE the `'use client'`\n * boundary and SSR-graph importers BELOW it. Walking `importers` naively\n * in one graph produces virtual-entry noise (`virtual:vite-rsc/css`)\n * instead of semantic importers — the design/47 §7 findings this module\n * bakes in:\n *\n * - RSC-side walks terminate at `virtual:timber-route-manifest` or the\n * first route-convention file (page/layout/…), never the literal RSC\n * entry — route files' importer is the manifest, whose importers are\n * framework internals; the manifest is the semantic root.\n * - `\\0virtual:vite-rsc/*` importers are filtered so they can never\n * surface in a chain.\n * - When multiple boundaries import the target, one chain is reported\n * PER BOUNDARY — a single BFS shortest path would pick arbitrarily.\n *\n * The chain/hop shapes and text formatting are shared with doc 43's\n * `timber why` so both commands emit the same contract: hops carry\n * `{ id, directive, boundary }`, and one shortest chain is emitted per\n * (boundary, reaching route entry) pair — doc 43's \"one shortest path\n * per reaching entry\", crossed with §7's per-boundary rule.\n *\n * Design docs: 47-module-environment-tooling.md §7, 43-analyze-cli.md\n * §Output Formats.\n */\n\nimport { relative, isAbsolute } from 'node:path';\nimport { normalizePath } from 'vite';\nimport { isConventionSourceFile, type Directive } from './classify.ts';\n\n/**\n * Duck-typed view of a Vite environment module node — a supertype of\n * `EnvironmentModuleNode` for the members the walk reads, so live\n * dev-server graphs and crawl graphs both satisfy it structurally.\n */\nexport interface ChainModuleNode {\n id: string | null;\n url: string;\n file: string | null;\n importers: Set<ChainModuleNode>;\n}\n\n/** Duck-typed view of a Vite environment module graph. */\nexport interface ChainGraph {\n getModulesByFile(file: string): Set<ChainModuleNode> | undefined;\n}\n\n/** Per-hop directive in doc 43's JSON vocabulary. */\nexport type HopDirective = 'client' | 'server' | null;\n\nexport interface ChainHop {\n /** Absolute file path, or a virtual module id printed verbatim. */\n id: string;\n directive: HopDirective;\n /** True only on the hop that crosses the server→client boundary. */\n boundary: boolean;\n}\n\nexport interface ImportChain {\n /**\n * Semantic root: a route-convention file, or the route-manifest\n * virtual id when the walk reached it without passing one. Null when\n * the RSC-side walk dead-ended (no root found) — the chain then\n * starts at its deepest known importer and consumers must present it\n * as partial.\n */\n entry: string | null;\n /**\n * The `'use client'` file this chain crosses; null for a pure\n * server-side chain.\n */\n boundary: string | null;\n /** Hops in forward import order, entry → … → target. */\n hops: ChainHop[];\n}\n\nexport interface ChainContext {\n rsc: ChainGraph;\n ssr: ChainGraph;\n /** Absolute app directory — scopes route-convention root detection. */\n appDir: string;\n /**\n * Configured pageExtensions, when the caller has resolved the app\n * config — a `page.mdx` app's route files are only roots with it.\n * Omitted → scanner defaults.\n */\n pageExtensions?: readonly string[];\n /**\n * First directive of a file's ORIGINAL source (design/43: never the\n * transformed output, where directives are stripped/proxied).\n */\n getDirective(file: string): Directive;\n}\n\n/**\n * The route manifest appears under several ids depending on environment\n * and build phase: `virtual:timber-route-manifest`,\n * `\\0virtual:timber-route-manifest`, and a root-prefixed form\n * (plugins/routing.ts) — match by substring.\n */\nfunction isRouteManifest(key: string): boolean {\n return key.includes('virtual:timber-route-manifest');\n}\n\n/** plugin-rsc internal virtuals (observed: virtual:vite-rsc/css). */\nfunction isViteRscInternal(key: string): boolean {\n return key.includes('virtual:vite-rsc/');\n}\n\n/**\n * File-level vertex key for a node: the file path when Vite resolved\n * one, else the virtual id. Multiple nodes can exist per file (query\n * variants); collapsing to the file keeps chains at source granularity.\n */\nfunction vertexKey(node: ChainModuleNode): string | null {\n return node.file ?? node.id ?? node.url ?? null;\n}\n\n/**\n * Separator for path signatures. Sorts below every printable character\n * so comparing joined signatures equals comparing key sequences.\n */\nconst SIG_SEP = '\\u0000';\n\n/**\n * Backwards level-order BFS over `importers` from `start`, collapsing\n * nodes to file-level vertices and filtering plugin-rsc internals.\n *\n * Shortest-path ties are broken GLOBALLY: each vertex's predecessor is\n * the candidate whose full path signature (the id sequence from the\n * target outward) is lexicographically smallest — per-frontier\n * candidate selection, not merely per-parent importer sorting, so\n * reconverging equal-length branches still yield the advertised\n * representative path (doc 43 §Tie-Breaking).\n *\n * `stopAt` marks terminal vertices. By default their importers are not\n * expanded (RSC walks must not proceed past a route root into\n * framework internals); with `continuePastTerminals` the traversal\n * records the terminal and keeps walking — the SSR walk needs this so\n * an outer boundary that imports an inner boundary is still\n * discovered (one chain per boundary).\n */\nfunction walkImporters(\n graph: ChainGraph,\n start: string,\n stopAt: (key: string) => boolean,\n continuePastTerminals = false\n): { predecessors: Map<string, string | null>; terminals: string[] } {\n const startNodes = graph.getModulesByFile(start);\n const predecessors = new Map<string, string | null>();\n const terminals: string[] = [];\n if (!startNodes || startNodes.size === 0) return { predecessors, terminals };\n\n predecessors.set(start, null);\n const signatures = new Map<string, string>([[start, start]]);\n const nodesOf = new Map<string, ChainModuleNode[]>([[start, [...startNodes]]]);\n let frontier = [start];\n\n while (frontier.length > 0) {\n interface Candidate {\n sig: string;\n parent: string;\n observed: ChainModuleNode[];\n }\n const candidates = new Map<string, Candidate>();\n for (const key of frontier) {\n if (stopAt(key)) {\n terminals.push(key);\n if (!continuePastTerminals) continue;\n }\n for (const node of nodesOf.get(key) ?? []) {\n for (const importer of node.importers) {\n const importerKey = vertexKey(importer);\n if (!importerKey || isViteRscInternal(importerKey)) continue;\n if (predecessors.has(importerKey)) continue;\n // Every frontier vertex has a signature (set when its level\n // was fixed); the fallback only satisfies the type.\n const sig = (signatures.get(key) ?? key) + SIG_SEP + importerKey;\n const existing = candidates.get(importerKey);\n if (!existing) {\n candidates.set(importerKey, { sig, parent: key, observed: [importer] });\n } else {\n // Keep every observed node object (virtual ids have no file\n // index to re-fetch from), but the smallest signature wins\n // the predecessor slot.\n existing.observed.push(importer);\n if (sig < existing.sig) {\n existing.sig = sig;\n existing.parent = key;\n }\n }\n }\n }\n }\n // Fix the next level, ordered by signature so terminal discovery\n // order — and therefore chain order — is deterministic.\n const next = [...candidates.entries()].sort(([, a], [, b]) =>\n a.sig < b.sig ? -1 : a.sig > b.sig ? 1 : 0\n );\n frontier = [];\n for (const [importerKey, candidate] of next) {\n predecessors.set(importerKey, candidate.parent);\n signatures.set(importerKey, candidate.sig);\n // Re-fetch the file's FULL node set from the graph: the importer\n // edges seen so far may cover only one of several nodes per file\n // (query variants — ?direct, ?v=…), and expanding a partial set\n // would silently drop the sibling nodes' importers and dead-end\n // the chain. Virtual ids have no file index; use observed nodes.\n const fullNodes = graph.getModulesByFile(importerKey);\n nodesOf.set(\n importerKey,\n fullNodes && fullNodes.size > 0 ? [...fullNodes] : candidate.observed\n );\n frontier.push(importerKey);\n }\n }\n return { predecessors, terminals };\n}\n\n/** Follow predecessors from `from` back to the walk's start vertex. */\nfunction pathToStart(predecessors: Map<string, string | null>, from: string): string[] {\n const path: string[] = [];\n for (let key: string | null = from; key !== null; key = predecessors.get(key) ?? null) {\n path.push(key);\n }\n return path;\n}\n\nfunction isRouteRoot(key: string, ctx: ChainContext): boolean {\n // Manifest matching applies to virtual ids only — a real file whose\n // path happens to contain the substring must not become a root.\n if (!isAbsolute(key) && isRouteManifest(key)) return true;\n if (!isAbsolute(key)) return false;\n if (key !== ctx.appDir && !key.startsWith(ctx.appDir + '/')) return false;\n return isConventionSourceFile(key, ctx.pageExtensions);\n}\n\n/**\n * RSC-side walk: importers of `file` in the RSC graph up to the\n * semantic roots. Returns one chain PER reaching route entry (doc 43:\n * \"one shortest path per reaching entry\"), each with hops in forward\n * order (root → … → file), in discovery order (shallowest first,\n * signature tie-break). When no root was reached, a single partial\n * result (entry: null) carrying the deepest known path.\n */\nfunction rscSideChains(\n file: string,\n ctx: ChainContext\n): Array<{ entry: string | null; files: string[] }> {\n const { predecessors, terminals } = walkImporters(ctx.rsc, file, (key) => isRouteRoot(key, ctx));\n if (terminals.length > 0) {\n return terminals.map((root) => ({ entry: root, files: pathToStart(predecessors, root) }));\n }\n if (predecessors.size <= 1) {\n // Nothing above the file at all (or file absent from the graph).\n return [{ entry: null, files: [file] }];\n }\n // Dead end — no root found. Report from the deepest vertex on the\n // last-discovered shortest path so the partial chain is still useful.\n const keys = [...predecessors.keys()];\n const deepest = keys[keys.length - 1];\n return [{ entry: null, files: pathToStart(predecessors, deepest) }];\n}\n\n/** Map a source directive onto the doc-43 hop vocabulary. */\nfunction hopDirective(key: string, ctx: ChainContext): HopDirective {\n if (!isAbsolute(key)) return null;\n const directive = ctx.getDirective(key);\n if (directive === 'use client') return 'client';\n if (directive === 'use server') return 'server';\n return null;\n}\n\nfunction toChain(\n entry: string | null,\n boundary: string | null,\n files: string[],\n ctx: ChainContext\n): ImportChain {\n return {\n entry,\n boundary,\n hops: files.map((key) => ({\n id: key,\n directive: hopDirective(key, ctx),\n boundary: boundary !== null && key === boundary,\n })),\n };\n}\n\n/**\n * Stitch the import chain(s) for a target file.\n *\n * - Target in the SSR graph (client-side): walk SSR importers up to\n * each `'use client'` boundary that the RSC graph knows (nested\n * boundaries only reachable from other client components are walked\n * THROUGH — they exist in no RSC graph, so the chain must continue\n * to a boundary a server component actually references), then walk\n * RSC importers from that boundary to the semantic root. One chain\n * per boundary.\n * - Target in the RSC graph without `'use client'`: a pure server\n * chain (boundary: null). Shared modules get both kinds.\n * - Target IS an RSC-known boundary: an RSC-side chain from the target\n * itself, PLUS any outer-boundary chains the SSR walk finds — a\n * boundary imported by another boundary is pulled in by both. A\n * nested `'use client'` target the RSC graph does NOT know is\n * handled like any client-internal file — the SSR walk continues to\n * the boundary a server component references.\n */\nexport function stitchImportChains(rawTargetFile: string, rawCtx: ChainContext): ImportChain[] {\n // Vite module-node `file` values are slash-normalized even on\n // Windows, while node:path targets/appDir arrive backslashed there —\n // normalize both once so graph lookups and containment checks agree\n // (normalizePath only rewrites separators on Windows, so posix paths\n // pass through untouched).\n const targetFile = normalizePath(rawTargetFile);\n const ctx: ChainContext = { ...rawCtx, appDir: normalizePath(rawCtx.appDir) };\n\n const chains: ImportChain[] = [];\n const targetDirective = ctx.getDirective(targetFile);\n const targetInRsc = (ctx.rsc.getModulesByFile(targetFile)?.size ?? 0) > 0;\n\n if (targetDirective === 'use client' && targetInRsc) {\n for (const above of rscSideChains(targetFile, ctx)) {\n chains.push(toChain(above.entry, targetFile, above.files, ctx));\n }\n }\n\n // Client-side chains: one per RSC-known boundary above the target.\n const isRscKnownBoundary = (key: string): boolean =>\n isAbsolute(key) &&\n ctx.getDirective(key) === 'use client' &&\n (ctx.rsc.getModulesByFile(key)?.size ?? 0) > 0;\n\n // continuePastTerminals: an outer boundary that imports an inner\n // boundary must still be discovered — one chain per boundary.\n const ssrWalk = walkImporters(ctx.ssr, targetFile, isRscKnownBoundary, true);\n for (const boundary of [...ssrWalk.terminals].sort()) {\n // A boundary target records itself as a terminal; its own chain is\n // the RSC-side one already pushed above.\n if (boundary === targetFile) continue;\n const below = pathToStart(ssrWalk.predecessors, boundary);\n for (const above of rscSideChains(boundary, ctx)) {\n // Stitch, dropping the duplicated boundary vertex from the RSC side.\n chains.push(toChain(above.entry, boundary, [...above.files.slice(0, -1), ...below], ctx));\n }\n }\n\n // Pure server chains when the RSC graph reaches the target directly.\n if (targetInRsc && targetDirective !== 'use client') {\n for (const above of rscSideChains(targetFile, ctx)) {\n chains.push(toChain(above.entry, null, above.files, ctx));\n }\n }\n\n // SSR-side dead end with nothing else to show: mirror the RSC side's\n // honesty and emit a partial chain from the deepest importer instead\n // of returning [] as if the file were in no graph. A singleton walk\n // (target in the SSR graph with no importers at all) still emits its\n // one-hop partial — graph membership is information.\n if (chains.length === 0 && ssrWalk.predecessors.size > 0) {\n const keys = [...ssrWalk.predecessors.keys()];\n const deepest = keys[keys.length - 1];\n chains.push(toChain(null, null, pathToStart(ssrWalk.predecessors, deepest), ctx));\n }\n\n return chains;\n}\n\n/**\n * Render chains in doc 43's text shape — shared by `timber graph` and\n * `timber why` so both commands print identically:\n *\n * ```\n * app/page.tsx\n * → app/nav.tsx ← 'use client' [boundary]\n * → src/lib/icons/chevron.ts\n * ```\n *\n * Paths under `projectRoot` print relative; virtual ids print verbatim\n * (doc 43 §Relative-vs-Absolute Paths). A partial chain (entry: null)\n * is prefixed with an honest marker instead of silently posing as\n * complete.\n */\nexport function formatChains(chains: ImportChain[], projectRoot: string): string {\n const root = normalizePath(projectRoot);\n const lines: string[] = [];\n for (const chain of chains) {\n if (lines.length > 0) lines.push('');\n if (chain.entry === null) {\n lines.push(' (partial chain — no route root found)');\n }\n chain.hops.forEach((hop, index) => {\n const display =\n isAbsolute(hop.id) && hop.id.startsWith(root + '/') ? relative(root, hop.id) : hop.id;\n const indent = ' '.repeat(index + 1);\n const arrow = index === 0 ? '' : '→ ';\n let annotation = '';\n if (hop.directive === 'client') {\n annotation = ` ← 'use client'${hop.boundary ? ' [boundary]' : ''}`;\n } else if (hop.directive === 'server') {\n annotation = ` ← 'use server'`;\n }\n lines.push(`${indent}${arrow}${display}${annotation}`);\n });\n }\n return lines.join('\\n');\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2GA,IAAM,uBAAuB;;;;;;;;;;AAW7B,SAAgB,YAAY,MAAoC;CAC9D,IAAI,SAAS,KAAK,IAAI,GAAG,OAAO;CAChC,IAAI,aAAa,KAAK,IAAI,GAAG,OAAO;CACpC,OAAO;AACT;;;;;;;;;;;;;;AAeA,SAAgB,gBAAgB,MAAc,MAAyB;CACrE,IAAI,CAAC,qBAAqB,KAAK,IAAI,GAAG,OAAO;CAC7C,IAAI;CACJ,IAAI;EAKF,OAAO,SAAS,MAAM,EAAE,MAAM,YAAY,IAAI,EAAE,CAAC,CAAC,CAAC;CACrD,QAAQ;EACN,OAAO;CACT;CACA,IAAI,aAAa,MAAM,YAAY,GAAG,OAAO;CAC7C,IAAI,aAAa,MAAM,Y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U,MAClB,MAAM,KAAK,yCAAyC;EAEtD,MAAM,KAAK,SAAS,KAAK,UAAU;GACjC,MAAM,UACJ,WAAW,IAAI,EAAE,KAAK,IAAI,GAAG,WAAW,OAAO,GAAG,IAAI,SAAS,MAAM,IAAI,EAAE,IAAI,IAAI;GACrF,MAAM,SAAS,KAAK,OAAO,QAAQ,CAAC;GACpC,MAAM,QAAQ,UAAU,IAAI,KAAK;GACjC,IAAI,aAAa;GACjB,IAAI,IAAI,cAAc,UACpB,aAAa,mBAAmB,IAAI,WAAW,gBAAgB;QAC1D,IAAI,IAAI,cAAc,UAC3B,aAAa;GAEf,MAAM,KAAK,GAAG,SAAS,QAAQ,UAAU,YAAY;EACvD,CAAC;CACH;CACA,OAAO,MAAM,KAAK,IAAI;AACxB"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"poison-scan-vGV7Re0B.js","names":[],"sources":["../../src/analyze/poison-scan.ts"],"sourcesContent":["/**\n * poison-scan — report-only poisoning detection for `timber graph`.\n *\n * Matches a module's static import specifiers against the shared rule\n * lists in poison-rules.ts (the single source of truth — design/47 §3)\n * and reports a poisoning only when the implied exclusivity CONFLICTS\n * with where the module actually runs: a server-only signal in a\n * client-reachable module, or a client-only signal in a server-reachable\n * one. A `node:fs` import in a file only the RSC environment loads is\n * working code, not a finding.\n *\n * Scope: import-specifier signals only (explicit markers + the inferred\n * rules' `matchesImport`). The inferred browser-global identifier rules\n * need shadow-safe allowlisted-position AST matching and are a separate\n * ticket — reporting them from a text scan would flag legitimate code.\n *\n * Design docs: 47-module-environment-tooling.md §3.\n */\n\nimport { parseAst } from 'vite';\nimport { EXPLICIT_MARKERS, INFERRED_RULES } from './poison-rules.ts';\nimport { langForFile, type ModuleKind } from './classify.ts';\n\n/** One poisoning finding on a module, in the JSON-contract shape. */\nexport interface Poisoning {\n /** Rule id — an inferred rule's id, or the explicit marker specifier. */\n rule: string;\n /** The import specifier that matched. */\n specifier: string;\n /** Which exclusivity the signal implies for the containing module. */\n implies: 'server-only' | 'client-only';\n /** Human-readable description for reporter output. */\n description: string;\n}\n\n/** File extensions the specifier scan can parse. */\nconst PARSEABLE_EXTENSIONS = /\\.(?:ts|tsx|js|jsx|mjs|cjs|mts|cts)$/;\n\n/**\n * A NON-EMPTY specifier list where every entry is type-only. Empty or\n * absent lists return false — a bare `import 'pkg'` is a side-effect\n * import and very much runs.\n */\nfunction isAllSpecifiersTypeOnly(\n specifiers: Array<{ importKind?: string; exportKind?: string }> | undefined\n): boolean {\n if (!specifiers || specifiers.length === 0) return false;\n return specifiers.every((s) => s.importKind === 'type' || s.exportKind === 'type');\n}\n\n/**\n * Collect every static import/export source and string-literal dynamic\n * import from a module's original source. Sources that fail to parse\n * (or are not JS/TS at all) return [] — no specifiers is a safe\n * default for a report-only scan.\n */\nexport function collectImportSpecifiers(code: string, file: string): string[] {\n if (!PARSEABLE_EXTENSIONS.test(file)) return [];\n let program;\n try {\n // Language from the extension, never forced tsx — see langForFile.\n program = parseAst(code, { lang: langForFile(file) });\n } catch {\n return [];\n }\n const specifiers: string[] = [];\n const visit = (node: unknown): void => {\n if (Array.isArray(node)) {\n for (const child of node) visit(child);\n return;\n }\n if (typeof node !== 'object' || node === null) return;\n const record = node as Record<string, unknown> & {\n type?: string;\n importKind?: string;\n exportKind?: string;\n specifiers?: Array<{ importKind?: string; exportKind?: string }>;\n };\n if (\n (record.type === 'ImportDeclaration' ||\n record.type === 'ExportNamedDeclaration' ||\n record.type === 'ExportAllDeclaration') &&\n // Type-only imports/exports are erased at runtime — `import type\n // { Stats } from 'node:fs'` in client code is working code, and\n // flagging it would be a false positive in a report-only scan.\n // Covers both the declaration-level form (`import type {…}`,\n // importKind on the declaration) and the inline form\n // (`import { type Stats }`, where the declaration stays 'value'\n // and each SPECIFIER carries the kind) — a declaration whose\n // specifiers are all type-only is erased just the same.\n record.importKind !== 'type' &&\n record.exportKind !== 'type' &&\n !isAllSpecifiersTypeOnly(record.specifiers) &&\n typeof (record.source as { value?: unknown } | null)?.value === 'string'\n ) {\n specifiers.push((record.source as { value: string }).value);\n } else if (\n record.type === 'ImportExpression' &&\n (record.source as { type?: string; value?: unknown })?.type === 'Literal' &&\n typeof (record.source as { value?: unknown }).value === 'string'\n ) {\n specifiers.push((record.source as { value: string }).value);\n }\n for (const key of Object.keys(record)) {\n if (key === 'type') continue;\n visit(record[key]);\n }\n };\n visit(program.body);\n return specifiers;\n}\n\n/** Exclusivity signals a module's import specifiers carry. */\nexport function importSignals(specifiers: string[]): Poisoning[] {\n const signals: Poisoning[] = [];\n for (const specifier of specifiers) {\n for (const marker of EXPLICIT_MARKERS) {\n if (specifier === marker.specifier) {\n signals.push({\n rule: marker.specifier,\n specifier,\n implies: marker.specifier === 'server-only' ? 'server-only' : 'client-only',\n description: `imports the ${marker.specifier} poison-pill marker`,\n });\n }\n }\n for (const rule of INFERRED_RULES) {\n if (rule.matchesImport?.(specifier)) {\n signals.push({\n rule: rule.id,\n specifier,\n implies: rule.implies,\n description: rule.description,\n });\n }\n }\n }\n return signals;\n}\n\n/**\n * Filter a module's signals down to actual conflicts with its\n * classification. Environment reach follows the taxonomy: boundary /\n * client-internal / shared modules run client-side; server / shared /\n * server-action modules run server-side. Pending (provisional) modules\n * run nowhere confirmed, so nothing conflicts yet.\n */\nexport function poisoningsFor(\n kind: ModuleKind,\n pending: boolean,\n signals: Poisoning[]\n): Poisoning[] {\n if (pending || signals.length === 0) return [];\n const clientReachable =\n kind === 'client-boundary' || kind === 'client-internal' || kind === 'shared';\n const serverReachable = kind === 'server' || kind === 'shared' || kind === 'server-action';\n return signals.filter(\n (signal) =>\n (signal.implies === 'server-only' && clientReachable) ||\n (signal.implies === 'client-only' && serverReachable)\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAoCA,IAAM,uBAAuB;;;;;;AAO7B,SAAS,wBACP,YACS;CACT,IAAI,CAAC,cAAc,WAAW,WAAW,GAAG,OAAO;CACnD,OAAO,WAAW,OAAO,MAAM,EAAE,eAAe,UAAU,E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