Big News: Socket raises $60M Series C at a $1B valuation to secure software supply chains for AI-driven development.Announcement
Sign In

@tanstack/router-plugin

Package Overview
Dependencies
Maintainers
5
Versions
656
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@tanstack/router-plugin - npm Package Compare versions

Comparing version
1.168.6
to
1.168.7
+32
-233
dist/cjs/core/code-splitter/compilers.cjs

@@ -5,3 +5,2 @@ const require_runtime = require("../../_virtual/_rolldown/runtime.cjs");

const require_utils = require("../utils.cjs");
const require_path_ids = require("./path-ids.cjs");
const require_framework_options = require("./framework-options.cjs");

@@ -57,3 +56,3 @@ let _tanstack_router_utils = require("@tanstack/router-utils");

const params = new URLSearchParams();
params.append(require_constants.tsrSplit, require_path_ids.createIdentifier(grouping));
params.append(require_constants.tsrSplit, (0, _tanstack_router_utils.createIdentifier)(grouping));
return `${bareFilename}?${params.toString()}`;

@@ -73,65 +72,2 @@ }

/**
* Recursively walk an AST node and collect referenced identifier-like names.
* Much cheaper than babel.traverse — no path/scope overhead.
*
* Notes:
* - Uses @babel/types `isReferenced` to avoid collecting non-references like
* object keys, member expression properties, or binding identifiers.
* - Also handles JSX identifiers for component references.
*/
function collectIdentifiersFromNode(node) {
const ids = /* @__PURE__ */ new Set();
(function walk(n, parent, grandparent, parentKey) {
if (!n) return;
if (_babel_types.isIdentifier(n)) {
if (!parent || _babel_types.isReferenced(n, parent, grandparent)) ids.add(n.name);
return;
}
if (_babel_types.isJSXIdentifier(n)) {
if (parent && _babel_types.isJSXAttribute(parent) && parentKey === "name") return;
if (parent && _babel_types.isJSXMemberExpression(parent) && parentKey === "property") return;
const first = n.name[0];
if (first && first === first.toLowerCase()) return;
ids.add(n.name);
return;
}
for (const key of _babel_types.VISITOR_KEYS[n.type] || []) {
const child = n[key];
if (Array.isArray(child)) {
for (const c of child) if (c && typeof c.type === "string") walk(c, n, parent, key);
} else if (child && typeof child.type === "string") walk(child, n, parent, key);
}
})(node);
return ids;
}
/**
* Build a map from binding name → declaration AST node for all
* locally-declared module-level bindings. Built once, O(1) lookup.
*/
function buildDeclarationMap(ast) {
const map = /* @__PURE__ */ new Map();
for (const stmt of ast.program.body) {
const decl = _babel_types.isExportNamedDeclaration(stmt) && stmt.declaration ? stmt.declaration : stmt;
if (_babel_types.isVariableDeclaration(decl)) for (const declarator of decl.declarations) for (const name of collectIdentifiersFromPattern(declarator.id)) map.set(name, declarator);
else if (_babel_types.isFunctionDeclaration(decl) && decl.id) map.set(decl.id.name, decl);
else if (_babel_types.isClassDeclaration(decl) && decl.id) map.set(decl.id.name, decl);
}
return map;
}
/**
* Build a dependency graph: for each local binding, the set of other local
* bindings its declaration references. Built once via simple node walking.
*/
function buildDependencyGraph(declMap, localBindings) {
const graph = /* @__PURE__ */ new Map();
for (const [name, declNode] of declMap) {
if (!localBindings.has(name)) continue;
const allIds = collectIdentifiersFromNode(declNode);
const deps = /* @__PURE__ */ new Set();
for (const id of allIds) if (id !== name && localBindings.has(id)) deps.add(id);
graph.set(name, deps);
}
return graph;
}
/**
* Computes module-level bindings that are shared between split and non-split

@@ -148,3 +84,3 @@ * route properties. These bindings need to be extracted into a shared virtual

const localModuleLevelBindings = /* @__PURE__ */ new Set();
for (const node of ast.program.body) collectLocalBindingsFromStatement(node, localModuleLevelBindings);
for (const node of ast.program.body) (0, _tanstack_router_utils.collectLocalBindingsFromStatement)(node, localModuleLevelBindings);
localModuleLevelBindings.delete("Route");

@@ -184,7 +120,7 @@ if (localModuleLevelBindings.size === 0) return /* @__PURE__ */ new Set();

if (!hasNonSplit && splitGroupsPresent.size < 2) return /* @__PURE__ */ new Set();
const declMap = buildDeclarationMap(ast);
const depGraph = buildDependencyGraph(declMap, localModuleLevelBindings);
const declMap = (0, _tanstack_router_utils.buildDeclarationMap)(ast);
const depGraph = (0, _tanstack_router_utils.buildDependencyGraph)(declMap, localModuleLevelBindings);
const allLocalBindings = new Set(localModuleLevelBindings);
allLocalBindings.add("Route");
const fullDepGraph = buildDependencyGraph(declMap, allLocalBindings);
const fullDepGraph = (0, _tanstack_router_utils.buildDependencyGraph)(declMap, allLocalBindings);
const refsByGroup = /* @__PURE__ */ new Map();

@@ -197,5 +133,5 @@ for (const prop of routeOptions.properties) {

const groupIndex = findIndexForSplitNode(key);
const directRefs = collectModuleLevelRefsFromNode(prop.value, localModuleLevelBindings);
const directRefs = (0, _tanstack_router_utils.collectModuleLevelRefsFromNode)(prop.value, localModuleLevelBindings);
const allRefs = new Set(directRefs);
expandTransitively(allRefs, depGraph);
(0, _tanstack_router_utils.expandTransitively)(allRefs, depGraph);
for (const ref of allRefs) {

@@ -212,116 +148,9 @@ let groups = refsByGroup.get(ref);

for (const [name, groups] of refsByGroup) if (groups.size >= 2) shared.add(name);
expandSharedDestructuredDeclarators(ast, refsByGroup, shared);
(0, _tanstack_router_utils.expandSharedDestructuredDeclarators)(ast, refsByGroup, shared);
if (shared.size === 0) return shared;
expandDestructuredDeclarations(ast, shared);
removeBindingsDependingOnRoute(shared, fullDepGraph);
(0, _tanstack_router_utils.expandDestructuredDeclarations)(ast, shared);
(0, _tanstack_router_utils.removeBindingsTransitivelyDependingOn)(shared, fullDepGraph, ["Route"]);
return shared;
}
/**
* If bindings from the same destructured declarator are referenced by
* different groups, mark all bindings from that declarator as shared.
*/
function expandSharedDestructuredDeclarators(ast, refsByGroup, shared) {
for (const stmt of ast.program.body) {
const decl = _babel_types.isExportNamedDeclaration(stmt) && stmt.declaration ? stmt.declaration : stmt;
if (!_babel_types.isVariableDeclaration(decl)) continue;
for (const declarator of decl.declarations) {
if (!_babel_types.isObjectPattern(declarator.id) && !_babel_types.isArrayPattern(declarator.id)) continue;
const names = collectIdentifiersFromPattern(declarator.id);
const usedGroups = /* @__PURE__ */ new Set();
for (const name of names) {
const groups = refsByGroup.get(name);
if (!groups) continue;
for (const g of groups) usedGroups.add(g);
}
if (usedGroups.size >= 2) for (const name of names) shared.add(name);
}
}
}
/**
* Collect locally-declared module-level binding names from a statement.
* Pure node inspection, no traversal.
*/
function collectLocalBindingsFromStatement(node, bindings) {
const decl = _babel_types.isExportNamedDeclaration(node) && node.declaration ? node.declaration : node;
if (_babel_types.isVariableDeclaration(decl)) for (const declarator of decl.declarations) for (const name of collectIdentifiersFromPattern(declarator.id)) bindings.add(name);
else if (_babel_types.isFunctionDeclaration(decl) && decl.id) bindings.add(decl.id.name);
else if (_babel_types.isClassDeclaration(decl) && decl.id) bindings.add(decl.id.name);
}
/**
* Collect direct module-level binding names referenced from a given AST node.
* Uses a simple recursive walk instead of babel.traverse.
*/
function collectModuleLevelRefsFromNode(node, localModuleLevelBindings) {
const allIds = collectIdentifiersFromNode(node);
const refs = /* @__PURE__ */ new Set();
for (const name of allIds) if (localModuleLevelBindings.has(name)) refs.add(name);
return refs;
}
/**
* Expand the shared set transitively using a prebuilt dependency graph.
* No AST traversals — pure graph BFS.
*/
function expandTransitively(shared, depGraph) {
const queue = [...shared];
const visited = /* @__PURE__ */ new Set();
while (queue.length > 0) {
const name = queue.pop();
if (visited.has(name)) continue;
visited.add(name);
const deps = depGraph.get(name);
if (!deps) continue;
for (const dep of deps) if (!shared.has(dep)) {
shared.add(dep);
queue.push(dep);
}
}
}
/**
* Remove any bindings from `shared` that transitively depend on `Route`.
* The Route singleton must remain in the reference file; if a shared binding
* references it (directly or transitively), extracting that binding would
* duplicate Route in the shared module.
*
* Uses `depGraph` which must include `Route` as a node so the dependency
* chain is visible.
*/
function removeBindingsDependingOnRoute(shared, depGraph) {
const reverseGraph = /* @__PURE__ */ new Map();
for (const [name, deps] of depGraph) for (const dep of deps) {
let parents = reverseGraph.get(dep);
if (!parents) {
parents = /* @__PURE__ */ new Set();
reverseGraph.set(dep, parents);
}
parents.add(name);
}
const visited = /* @__PURE__ */ new Set();
const queue = ["Route"];
while (queue.length > 0) {
const cur = queue.pop();
if (visited.has(cur)) continue;
visited.add(cur);
const parents = reverseGraph.get(cur);
if (!parents) continue;
for (const parent of parents) if (!visited.has(parent)) queue.push(parent);
}
for (const name of [...shared]) if (visited.has(name)) shared.delete(name);
}
/**
* If any binding from a destructured declaration is shared,
* ensure all bindings from that same declaration are also shared.
* Pure node inspection of program.body, no traversal.
*/
function expandDestructuredDeclarations(ast, shared) {
for (const stmt of ast.program.body) {
const decl = _babel_types.isExportNamedDeclaration(stmt) && stmt.declaration ? stmt.declaration : stmt;
if (!_babel_types.isVariableDeclaration(decl)) continue;
for (const declarator of decl.declarations) {
if (!_babel_types.isObjectPattern(declarator.id) && !_babel_types.isArrayPattern(declarator.id)) continue;
const names = collectIdentifiersFromPattern(declarator.id);
if (names.some((n) => shared.has(n))) for (const n of names) shared.add(n);
}
}
}
/**
* Find which shared bindings are user-exported in the original source.

@@ -335,3 +164,3 @@ * These need to be re-exported from the shared module.

if (_babel_types.isVariableDeclaration(stmt.declaration)) {
for (const decl of stmt.declaration.declarations) for (const name of collectIdentifiersFromPattern(decl.id)) if (sharedBindings.has(name)) exported.add(name);
for (const decl of stmt.declaration.declarations) for (const name of (0, _tanstack_router_utils.collectIdentifiersFromPattern)(decl.id)) if (sharedBindings.has(name)) exported.add(name);
} else if (_babel_types.isFunctionDeclaration(stmt.declaration) && stmt.declaration.id) {

@@ -355,3 +184,3 @@ if (sharedBindings.has(stmt.declaration.id.name)) exported.add(stmt.declaration.id.name);

decl.declarations = decl.declarations.filter((declarator) => {
return !collectIdentifiersFromPattern(declarator.id).every((n) => sharedBindings.has(n));
return !(0, _tanstack_router_utils.collectIdentifiersFromPattern)(declarator.id).every((n) => sharedBindings.has(n));
});

@@ -424,2 +253,12 @@ if (decl.declarations.length === 0) return false;

const insertionPath = path.getStatementParent() ?? path;
opts.compilerPlugins?.forEach((plugin) => {
if ((plugin.onRouteOptions?.({
programPath,
callExpressionPath: path,
insertionPath,
routeOptions,
createRouteFn,
opts
}))?.modified) modified = true;
});
if (opts.deleteNodes && opts.deleteNodes.size > 0) routeOptions.properties = routeOptions.properties.filter((prop) => {

@@ -674,4 +513,4 @@ if (_babel_types.isObjectProperty(prop)) {

if (_babel_types.isIdentifier(decl.id)) return [_babel_types.importSpecifier(_babel_types.identifier(decl.id.name), _babel_types.identifier(decl.id.name))];
if (_babel_types.isObjectPattern(decl.id)) return collectIdentifiersFromPattern(decl.id).map((name) => _babel_types.importSpecifier(_babel_types.identifier(name), _babel_types.identifier(name)));
if (_babel_types.isArrayPattern(decl.id)) return collectIdentifiersFromPattern(decl.id).map((name) => _babel_types.importSpecifier(_babel_types.identifier(name), _babel_types.identifier(name)));
if (_babel_types.isObjectPattern(decl.id)) return (0, _tanstack_router_utils.collectIdentifiersFromPattern)(decl.id).map((name) => _babel_types.importSpecifier(_babel_types.identifier(name), _babel_types.identifier(name)));
if (_babel_types.isArrayPattern(decl.id)) return (0, _tanstack_router_utils.collectIdentifiersFromPattern)(decl.id).map((name) => _babel_types.importSpecifier(_babel_types.identifier(name), _babel_types.identifier(name)));
return [];

@@ -701,10 +540,3 @@ });

(0, _tanstack_router_utils.deadCodeElimination)(ast, refIdents);
{
const locallyBound = /* @__PURE__ */ new Set();
for (const stmt of ast.program.body) collectLocalBindingsFromStatement(stmt, locallyBound);
ast.program.body = ast.program.body.filter((stmt) => {
if (!_babel_types.isExpressionStatement(stmt)) return true;
return [...collectIdentifiersFromNode(stmt)].some((name) => locallyBound.has(name));
});
}
(0, _tanstack_router_utils.stripUnreferencedTopLevelExpressionStatements)(ast);
if (ast.program.body.length === 0) ast.program.directives = [];

@@ -728,26 +560,10 @@ const result = (0, _tanstack_router_utils.generateFromAst)(ast, {

const localBindings = /* @__PURE__ */ new Set();
for (const node of ast.program.body) collectLocalBindingsFromStatement(node, localBindings);
for (const node of ast.program.body) (0, _tanstack_router_utils.collectLocalBindingsFromStatement)(node, localBindings);
localBindings.delete("Route");
const depGraph = buildDependencyGraph(buildDeclarationMap(ast), localBindings);
const depGraph = (0, _tanstack_router_utils.buildDependencyGraph)((0, _tanstack_router_utils.buildDeclarationMap)(ast), localBindings);
const keepBindings = new Set(opts.sharedBindings);
keepBindings.delete("Route");
expandTransitively(keepBindings, depGraph);
ast.program.body = ast.program.body.filter((stmt) => {
if (_babel_types.isImportDeclaration(stmt)) return true;
const decl = _babel_types.isExportNamedDeclaration(stmt) && stmt.declaration ? stmt.declaration : stmt;
if (_babel_types.isVariableDeclaration(decl)) {
decl.declarations = decl.declarations.filter((declarator) => {
return collectIdentifiersFromPattern(declarator.id).some((n) => keepBindings.has(n));
});
if (decl.declarations.length === 0) return false;
if (_babel_types.isExportNamedDeclaration(stmt) && stmt.declaration) return true;
return true;
} else if (_babel_types.isFunctionDeclaration(decl) && decl.id) return keepBindings.has(decl.id.name);
else if (_babel_types.isClassDeclaration(decl) && decl.id) return keepBindings.has(decl.id.name);
return false;
});
ast.program.body = ast.program.body.map((stmt) => {
if (_babel_types.isExportNamedDeclaration(stmt) && stmt.declaration) return stmt.declaration;
return stmt;
});
(0, _tanstack_router_utils.expandTransitively)(keepBindings, depGraph);
(0, _tanstack_router_utils.retainModuleLevelDeclarations)(ast, keepBindings);
(0, _tanstack_router_utils.unwrapExportedDeclarations)(ast);
const exportSpecifiers = [...opts.sharedBindings].sort((a, b) => a.localeCompare(b)).map((name) => _babel_types.exportSpecifier(_babel_types.identifier(name), _babel_types.identifier(name)));

@@ -836,19 +652,2 @@ if (exportSpecifiers.length > 0) {

}
/**
* Recursively collects all identifier names from a destructuring pattern
* (ObjectPattern, ArrayPattern, AssignmentPattern, RestElement).
*/
function collectIdentifiersFromPattern(node) {
if (!node) return [];
if (_babel_types.isIdentifier(node)) return [node.name];
if (_babel_types.isAssignmentPattern(node)) return collectIdentifiersFromPattern(node.left);
if (_babel_types.isRestElement(node)) return collectIdentifiersFromPattern(node.argument);
if (_babel_types.isObjectPattern(node)) return node.properties.flatMap((prop) => {
if (_babel_types.isObjectProperty(prop)) return collectIdentifiersFromPattern(prop.value);
if (_babel_types.isRestElement(prop)) return collectIdentifiersFromPattern(prop.argument);
return [];
});
if (_babel_types.isArrayPattern(node)) return node.elements.flatMap((element) => collectIdentifiersFromPattern(element));
return [];
}
function resolveIdentifier(path, node) {

@@ -893,3 +692,3 @@ if (_babel_types.isIdentifier(node)) {

} else if (_babel_types.isObjectPattern(decl.id) || _babel_types.isArrayPattern(decl.id)) {
if (collectIdentifiersFromPattern(decl.id).includes(node.name)) found = true;
if ((0, _tanstack_router_utils.collectIdentifiersFromPattern)(decl.id).includes(node.name)) found = true;
}

@@ -931,3 +730,3 @@ }

} else if (_babel_types.isObjectPattern(decl.id) || _babel_types.isArrayPattern(decl.id)) {
if (collectIdentifiersFromPattern(decl.id).includes(node.name)) {
if ((0, _tanstack_router_utils.collectIdentifiersFromPattern)(decl.id).includes(node.name)) {
path.remove();

@@ -934,0 +733,0 @@ removed = true;

import { CompileCodeSplitReferenceRouteOptions, ReferenceRouteCompilerPlugin } from './plugins.cjs';
import { GeneratorResult, ParseAstOptions } from '@tanstack/router-utils';
import { CodeSplitGroupings, SplitRouteIdentNodes } from '../constants.cjs';
import * as t from '@babel/types';
export { buildDeclarationMap, buildDependencyGraph, collectIdentifiersFromNode, collectLocalBindingsFromStatement, collectModuleLevelRefsFromNode, expandDestructuredDeclarations, expandSharedDestructuredDeclarators, expandTransitively, removeBindingsTransitivelyDependingOn, } from '@tanstack/router-utils';
export declare function removeBindingsDependingOnRoute(bindings: Set<string>, dependencyGraph: Map<string, Set<string>>): void;
export declare function addSharedSearchParamToFilename(filename: string): string;
/**
* Recursively walk an AST node and collect referenced identifier-like names.
* Much cheaper than babel.traverse — no path/scope overhead.
*
* Notes:
* - Uses @babel/types `isReferenced` to avoid collecting non-references like
* object keys, member expression properties, or binding identifiers.
* - Also handles JSX identifiers for component references.
*/
export declare function collectIdentifiersFromNode(node: t.Node): Set<string>;
/**
* Build a map from binding name → declaration AST node for all
* locally-declared module-level bindings. Built once, O(1) lookup.
*/
export declare function buildDeclarationMap(ast: t.File): Map<string, t.Node>;
/**
* Build a dependency graph: for each local binding, the set of other local
* bindings its declaration references. Built once via simple node walking.
*/
export declare function buildDependencyGraph(declMap: Map<string, t.Node>, localBindings: Set<string>): Map<string, Set<string>>;
/**
* Computes module-level bindings that are shared between split and non-split

@@ -40,38 +21,2 @@ * route properties. These bindings need to be extracted into a shared virtual

}): Set<string>;
/**
* If bindings from the same destructured declarator are referenced by
* different groups, mark all bindings from that declarator as shared.
*/
export declare function expandSharedDestructuredDeclarators(ast: t.File, refsByGroup: Map<string, Set<number>>, shared: Set<string>): void;
/**
* Collect locally-declared module-level binding names from a statement.
* Pure node inspection, no traversal.
*/
export declare function collectLocalBindingsFromStatement(node: t.Statement | t.ModuleDeclaration, bindings: Set<string>): void;
/**
* Collect direct module-level binding names referenced from a given AST node.
* Uses a simple recursive walk instead of babel.traverse.
*/
export declare function collectModuleLevelRefsFromNode(node: t.Node, localModuleLevelBindings: Set<string>): Set<string>;
/**
* Expand the shared set transitively using a prebuilt dependency graph.
* No AST traversals — pure graph BFS.
*/
export declare function expandTransitively(shared: Set<string>, depGraph: Map<string, Set<string>>): void;
/**
* Remove any bindings from `shared` that transitively depend on `Route`.
* The Route singleton must remain in the reference file; if a shared binding
* references it (directly or transitively), extracting that binding would
* duplicate Route in the shared module.
*
* Uses `depGraph` which must include `Route` as a node so the dependency
* chain is visible.
*/
export declare function removeBindingsDependingOnRoute(shared: Set<string>, depGraph: Map<string, Set<string>>): void;
/**
* If any binding from a destructured declaration is shared,
* ensure all bindings from that same declaration are also shared.
* Pure node inspection of program.body, no traversal.
*/
export declare function expandDestructuredDeclarations(ast: t.File, shared: Set<string>): void;
export declare function compileCodeSplitReferenceRoute(opts: ParseAstOptions & CompileCodeSplitReferenceRouteOptions & {

@@ -78,0 +23,0 @@ compilerPlugins?: Array<ReferenceRouteCompilerPlugin>;

+1
-0

@@ -41,2 +41,3 @@ import { default as babel } from '@babel/core';

getStableRouteOptionKeys?: () => Array<string>;
onRouteOptions?: (ctx: ReferenceRouteCompilerPluginContext) => void | ReferenceRouteCompilerPluginResult;
onAddHmr?: (ctx: ReferenceRouteCompilerPluginContext) => void | ReferenceRouteCompilerPluginResult;

@@ -43,0 +44,0 @@ onUnsplittableRoute?: (ctx: ReferenceRouteCompilerPluginContext) => void | ReferenceRouteCompilerPluginResult;

@@ -19,3 +19,3 @@ require("../_virtual/_rolldown/runtime.cjs");

var codeSplittingOptionsSchema = zod.z.object({
splitBehavior: zod.z.function().optional(),
splitBehavior: zod.z.custom((value) => typeof value === "function").optional(),
defaultBehavior: splitGroupingsSchema.optional(),

@@ -22,0 +22,0 @@ deleteNodes: zod.z.array(zod.z.string()).optional(),

@@ -1,1 +0,1 @@

{"version":3,"file":"config.cjs","names":[],"sources":["../../../src/core/config.ts"],"sourcesContent":["import { z } from 'zod'\nimport {\n configSchema as generatorConfigSchema,\n getConfig as getGeneratorConfig,\n} from '@tanstack/router-generator'\nimport type {\n CreateFileRoute,\n RegisteredRouter,\n RouteIds,\n} from '@tanstack/router-core'\nimport type { CodeSplitGroupings } from './constants'\n\nexport const splitGroupingsSchema = z\n .array(\n z.array(\n z.union([\n z.literal('loader'),\n z.literal('component'),\n z.literal('pendingComponent'),\n z.literal('errorComponent'),\n z.literal('notFoundComponent'),\n ]),\n ),\n {\n message:\n \" Must be an Array of Arrays containing the split groupings. i.e. [['component'], ['pendingComponent'], ['errorComponent', 'notFoundComponent']]\",\n },\n )\n .superRefine((val, ctx) => {\n const flattened = val.flat()\n const unique = [...new Set(flattened)]\n\n // Elements must be unique,\n // ie. this shouldn't be allows [['component'], ['component', 'loader']]\n if (unique.length !== flattened.length) {\n ctx.addIssue({\n code: 'custom',\n message:\n \" Split groupings must be unique and not repeated. i.e. i.e. [['component'], ['pendingComponent'], ['errorComponent', 'notFoundComponent']].\" +\n `\\n You input was: ${JSON.stringify(val)}.`,\n })\n }\n })\n\nexport type CodeSplittingOptions = {\n /**\n * Use this function to programmatically control the code splitting behavior\n * based on the `routeId` for each route.\n *\n * If you just need to change the default behavior, you can use the `defaultBehavior` option.\n * @param params\n */\n splitBehavior?: (params: {\n routeId: RouteIds<RegisteredRouter['routeTree']>\n }) => CodeSplitGroupings | undefined | void\n\n /**\n * The default/global configuration to control your code splitting behavior per route.\n * @default [['component'],['pendingComponent'],['errorComponent'],['notFoundComponent']]\n */\n defaultBehavior?: CodeSplitGroupings\n\n /**\n * The nodes that shall be deleted from the route.\n * @default undefined\n */\n deleteNodes?: Array<DeletableNodes>\n\n /**\n * @default true\n */\n addHmr?: boolean\n}\n\nexport type HmrStyle = 'vite' | 'webpack'\n\nexport type HmrOptions = {\n /**\n * Selects the HMR runtime style to emit code for.\n * - `'vite'` (default): ESM `import.meta.hot` with Vite accept-callback semantics.\n * - `'webpack'`: `import.meta.webpackHot` with webpack / Rspack `module.hot` re-execution semantics.\n *\n * Bundler-specific plugin entries (e.g. `rspack.ts`, `webpack.ts`) set this explicitly.\n */\n style?: HmrStyle\n}\n\nconst codeSplittingOptionsSchema = z.object({\n splitBehavior: z.function().optional(),\n defaultBehavior: splitGroupingsSchema.optional(),\n deleteNodes: z.array(z.string()).optional(),\n addHmr: z.boolean().optional().default(true),\n})\n\ntype FileRouteKeys = keyof (Parameters<\n CreateFileRoute<any, any, any, any, any>\n>[0] & {})\nexport type DeletableNodes = FileRouteKeys | (string & {})\n\nexport const configSchema = generatorConfigSchema.extend({\n enableRouteGeneration: z.boolean().optional(),\n codeSplittingOptions: z\n .custom<CodeSplittingOptions>((v) => {\n return codeSplittingOptionsSchema.parse(v)\n })\n .optional(),\n plugin: z\n .object({\n hmr: z\n .object({\n style: z.enum(['vite', 'webpack']).optional(),\n })\n .optional(),\n vite: z\n .object({\n environmentName: z.string().optional(),\n })\n .optional(),\n })\n .optional(),\n})\n\nexport const getConfig = (inlineConfig: Partial<Config>, root: string) => {\n const config = getGeneratorConfig(inlineConfig, root)\n\n return configSchema.parse({ ...inlineConfig, ...config })\n}\n\nexport type Config = z.infer<typeof configSchema>\nexport type ConfigInput = z.input<typeof configSchema>\nexport type ConfigOutput = z.output<typeof configSchema>\n"],"mappings":";;;;AAYA,IAAa,uBAAuB,IAAA,EACjC,MACC,IAAA,EA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KAAK;AAErD,QAAO,aAAa,MAAM;EAAE,GAAG;EAAc,GAAG;EAAQ,CAAC"}
{"version":3,"file":"config.cjs","names":[],"sources":["../../../src/core/config.ts"],"sourcesContent":["import { z } from 'zod'\nimport {\n configSchema as generatorConfigSchema,\n getConfig as getGeneratorConfig,\n} from '@tanstack/router-generator'\nimport type {\n CreateFileRoute,\n RegisteredRouter,\n RouteIds,\n} from '@tanstack/router-core'\nimport type { CodeSplitGroupings } from './constants'\nimport type { ReferenceRouteCompilerPlugin } from './code-splitter/plugins'\n\nexport const splitGroupingsSchema = z\n .array(\n z.array(\n z.union([\n z.literal('loader'),\n z.literal('component'),\n z.literal('pendingComponent'),\n z.literal('errorComponent'),\n z.literal('notFoundComponent'),\n ]),\n ),\n {\n message:\n \" Must be an Array of Arrays containing the split groupings. i.e. [['component'], ['pendingComponent'], ['errorComponent', 'notFoundComponent']]\",\n },\n )\n .superRefine((val, ctx) => {\n const flattened = val.flat()\n const unique = [...new Set(flattened)]\n\n // Elements must be unique,\n // ie. this shouldn't be allows [['component'], ['component', 'loader']]\n if (unique.length !== flattened.length) {\n ctx.addIssue({\n code: 'custom',\n message:\n \" Split groupings must be unique and not repeated. i.e. i.e. [['component'], ['pendingComponent'], ['errorComponent', 'notFoundComponent']].\" +\n `\\n You input was: ${JSON.stringify(val)}.`,\n })\n }\n })\n\nexport type CodeSplittingOptions = {\n /**\n * Use this function to programmatically control the code splitting behavior\n * based on the `routeId` for each route.\n *\n * If you just need to change the default behavior, you can use the `defaultBehavior` option.\n * @param params\n */\n splitBehavior?: (params: {\n routeId: RouteIds<RegisteredRouter['routeTree']>\n }) => CodeSplitGroupings | undefined | void\n\n /**\n * The default/global configuration to control your code splitting behavior per route.\n * @default [['component'],['pendingComponent'],['errorComponent'],['notFoundComponent']]\n */\n defaultBehavior?: CodeSplitGroupings\n\n /**\n * The nodes that shall be deleted from the route.\n * @default undefined\n */\n deleteNodes?: Array<DeletableNodes>\n\n /**\n * @default true\n */\n addHmr?: boolean\n\n /**\n * Internal compiler plugins used by framework integrations.\n * @internal\n */\n compilerPlugins?: Array<ReferenceRouteCompilerPlugin>\n}\n\nexport type HmrStyle = 'vite' | 'webpack'\n\nexport type HmrOptions = {\n /**\n * Selects the HMR runtime style to emit code for.\n * - `'vite'` (default): ESM `import.meta.hot` with Vite accept-callback semantics.\n * - `'webpack'`: `import.meta.webpackHot` with webpack / Rspack `module.hot` re-execution semantics.\n *\n * Bundler-specific plugin entries (e.g. `rspack.ts`, `webpack.ts`) set this explicitly.\n */\n style?: HmrStyle\n}\n\nconst codeSplittingOptionsSchema = z.object({\n splitBehavior: z\n .custom<\n CodeSplittingOptions['splitBehavior']\n >((value) => typeof value === 'function')\n .optional(),\n defaultBehavior: splitGroupingsSchema.optional(),\n deleteNodes: z.array(z.string()).optional(),\n addHmr: z.boolean().optional().default(true),\n})\n\ntype FileRouteKeys = keyof (Parameters<\n CreateFileRoute<any, any, any, any, any>\n>[0] & {})\nexport type DeletableNodes = FileRouteKeys | (string & {})\n\nexport const configSchema = generatorConfigSchema.extend({\n enableRouteGeneration: z.boolean().optional(),\n codeSplittingOptions: z\n .custom<CodeSplittingOptions>((v) => {\n return codeSplittingOptionsSchema.parse(v)\n })\n .optional(),\n plugin: z\n .object({\n hmr: z\n .object({\n style: z.enum(['vite', 'webpack']).optional(),\n })\n .optional(),\n vite: z\n .object({\n environmentName: z.string().optional(),\n })\n .optional(),\n })\n .optional(),\n})\n\nexport const getConfig = (inlineConfig: Partial<Config>, root: string) => {\n const config = getGeneratorConfig(inlineConfig, root)\n\n return configSchema.parse({ ...inlineConfig, ...config })\n}\n\nexport type Config = z.infer<typeof configSchema>\nexport type ConfigInput = z.input<typeof configSchema>\nexport type ConfigOutput = z.output<typeof configSchema>\n"],"mappings":";;;;AAaA,IAAa,uBAAuB,IAAA,EACjC,MACC,IAAA,EAAE,MACA,IAAA,EAAE,MAAM;CACN,IAAA,EAAE,QAAQ,SAAS;CACnB,IAAA,EAAE,QAAQ,YA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CAAC"}
import { z } from 'zod';
import { CreateFileRoute, RegisteredRouter, RouteIds } from '@tanstack/router-core';
import { CodeSplitGroupings } from './constants.cjs';
export declare const splitGroupingsSchema: z.ZodEffects<z.ZodArray<z.ZodArray<z.ZodUnion<[z.ZodLiteral<"loader">, z.ZodLiteral<"component">, z.ZodLiteral<"pendingComponent">, z.ZodLiteral<"errorComponent">, z.ZodLiteral<"notFoundComponent">]>, "many">, "many">, ("loader" | "component" | "pendingComponent" | "errorComponent" | "notFoundComponent")[][], ("loader" | "component" | "pendingComponent" | "errorComponent" | "notFoundComponent")[][]>;
export declare const splitGroupingsSchema: z.ZodArray<z.ZodArray<z.ZodUnion<readonly [z.ZodLiteral<"loader">, z.ZodLiteral<"component">, z.ZodLiteral<"pendingComponent">, z.ZodLiteral<"errorComponent">, z.ZodLiteral<"notFoundComponent">]>>>;
export type CodeSplittingOptions = {

@@ -45,4 +45,8 @@ /**

export declare const configSchema: z.ZodObject<{
target: z.ZodDefault<z.ZodOptional<z.ZodEnum<["react", "solid", "vue"]>>>;
virtualRouteConfig: z.ZodOptional<z.ZodUnion<[z.ZodType<import('@tanstack/virtual-file-routes').VirtualRootRoute, z.ZodTypeDef, import('@tanstack/virtual-file-routes').VirtualRootRoute>, z.ZodString]>>;
target: z.ZodDefault<z.ZodOptional<z.ZodEnum<{
vue: "vue";
react: "react";
solid: "solid";
}>>>;
virtualRouteConfig: z.ZodOptional<z.ZodUnion<[z.ZodType<import('@tanstack/virtual-file-routes').VirtualRootRoute, unknown, z.core.$ZodTypeInternals<import('@tanstack/virtual-file-routes').VirtualRootRoute, unknown>>, z.ZodString]>>;
routeFilePrefix: z.ZodOptional<z.ZodString>;

@@ -52,33 +56,32 @@ routeFileIgnorePrefix: z.ZodDefault<z.ZodOptional<z.ZodString>>;

routesDirectory: z.ZodDefault<z.ZodOptional<z.ZodString>>;
quoteStyle: z.ZodDefault<z.ZodOptional<z.ZodEnum<["single", "double"]>>>;
quoteStyle: z.ZodDefault<z.ZodOptional<z.ZodEnum<{
single: "single";
double: "double";
}>>>;
semicolons: z.ZodDefault<z.ZodOptional<z.ZodBoolean>>;
disableLogging: z.ZodDefault<z.ZodOptional<z.ZodBoolean>>;
routeTreeFileHeader: z.ZodDefault<z.ZodOptional<z.ZodArray<z.ZodString, "many">>>;
indexToken: z.ZodDefault<z.ZodOptional<z.ZodUnion<[z.ZodString, z.ZodType<RegExp, z.ZodTypeDef, RegExp>, z.ZodObject<{
routeTreeFileHeader: z.ZodDefault<z.ZodOptional<z.ZodArray<z.ZodString>>>;
indexToken: z.ZodDefault<z.ZodOptional<z.ZodUnion<readonly [z.ZodString, z.ZodCustom<RegExp, RegExp>, z.ZodObject<{
regex: z.ZodString;
flags: z.ZodOptional<z.ZodString>;
}, "strip", z.ZodTypeAny, {
regex: string;
flags?: string | undefined;
}, {
regex: string;
flags?: string | undefined;
}>]>>>;
routeToken: z.ZodDefault<z.ZodOptional<z.ZodUnion<[z.ZodString, z.ZodType<RegExp, z.ZodTypeDef, RegExp>, z.ZodObject<{
}, z.core.$strip>]>>>;
routeToken: z.ZodDefault<z.ZodOptional<z.ZodUnion<readonly [z.ZodString, z.ZodCustom<RegExp, RegExp>, z.ZodObject<{
regex: z.ZodString;
flags: z.ZodOptional<z.ZodString>;
}, "strip", z.ZodTypeAny, {
regex: string;
flags?: string | undefined;
}, {
regex: string;
flags?: string | undefined;
}>]>>>;
pathParamsAllowedCharacters: z.ZodOptional<z.ZodArray<z.ZodEnum<[";", ":", "@", "&", "=", "+", "$", ","]>, "many">>;
} & {
}, z.core.$strip>]>>>;
pathParamsAllowedCharacters: z.ZodOptional<z.ZodArray<z.ZodEnum<{
":": ":";
$: "$";
";": ";";
"@": "@";
"&": "&";
"=": "=";
"+": "+";
",": ",";
}>>>;
generatedRouteTree: z.ZodDefault<z.ZodOptional<z.ZodString>>;
disableTypes: z.ZodDefault<z.ZodOptional<z.ZodBoolean>>;
addExtensions: z.ZodEffects<z.ZodDefault<z.ZodOptional<z.ZodUnion<[z.ZodBoolean, z.ZodString]>>>, string | boolean, string | boolean | undefined>;
addExtensions: z.ZodPipe<z.ZodDefault<z.ZodOptional<z.ZodUnion<readonly [z.ZodBoolean, z.ZodString]>>>, z.ZodTransform<string | boolean, string | boolean>>;
enableRouteTreeFormatting: z.ZodDefault<z.ZodOptional<z.ZodBoolean>>;
routeTreeFileFooter: z.ZodOptional<z.ZodUnion<[z.ZodDefault<z.ZodOptional<z.ZodArray<z.ZodString, "many">>>, z.ZodFunction<z.ZodTuple<[], z.ZodUnknown>, z.ZodArray<z.ZodString, "many">>]>>;
routeTreeFileFooter: z.ZodOptional<z.ZodUnion<readonly [z.ZodDefault<z.ZodOptional<z.ZodArray<z.ZodString>>>, z.ZodCustom<() => Array<string>, () => Array<string>>]>>;
autoCodeSplitting: z.ZodOptional<z.ZodBoolean>;

@@ -88,54 +91,25 @@ customScaffolding: z.ZodOptional<z.ZodObject<{

lazyRouteTemplate: z.ZodOptional<z.ZodString>;
}, "strip", z.ZodTypeAny, {
routeTemplate?: string | undefined;
lazyRouteTemplate?: string | undefined;
}, {
routeTemplate?: string | undefined;
lazyRouteTemplate?: string | undefined;
}>>;
}, z.core.$strip>>;
experimental: z.ZodOptional<z.ZodObject<{
enableCodeSplitting: z.ZodOptional<z.ZodBoolean>;
}, "strip", z.ZodTypeAny, {
enableCodeSplitting?: boolean | undefined;
}, {
enableCodeSplitting?: boolean | undefined;
}>>;
plugins: z.ZodOptional<z.ZodArray<z.ZodType<import('@tanstack/router-generator').GeneratorPlugin, z.ZodTypeDef, import('@tanstack/router-generator').GeneratorPlugin>, "many">>;
}, z.core.$strip>>;
plugins: z.ZodOptional<z.ZodArray<z.ZodCustom<import('@tanstack/router-generator').GeneratorPlugin, import('@tanstack/router-generator').GeneratorPlugin>>>;
tmpDir: z.ZodDefault<z.ZodOptional<z.ZodString>>;
importRoutesUsingAbsolutePaths: z.ZodDefault<z.ZodOptional<z.ZodBoolean>>;
} & {
enableRouteGeneration: z.ZodOptional<z.ZodBoolean>;
codeSplittingOptions: z.ZodOptional<z.ZodType<CodeSplittingOptions, z.ZodTypeDef, CodeSplittingOptions>>;
codeSplittingOptions: z.ZodOptional<z.ZodCustom<CodeSplittingOptions, CodeSplittingOptions>>;
plugin: z.ZodOptional<z.ZodObject<{
hmr: z.ZodOptional<z.ZodObject<{
style: z.ZodOptional<z.ZodEnum<["vite", "webpack"]>>;
}, "strip", z.ZodTypeAny, {
style?: "vite" | "webpack" | undefined;
}, {
style?: "vite" | "webpack" | undefined;
}>>;
style: z.ZodOptional<z.ZodEnum<{
vite: "vite";
webpack: "webpack";
}>>;
}, z.core.$strip>>;
vite: z.ZodOptional<z.ZodObject<{
environmentName: z.ZodOptional<z.ZodString>;
}, "strip", z.ZodTypeAny, {
environmentName?: string | undefined;
}, {
environmentName?: string | undefined;
}>>;
}, "strip", z.ZodTypeAny, {
vite?: {
environmentName?: string | undefined;
} | undefined;
hmr?: {
style?: "vite" | "webpack" | undefined;
} | undefined;
}, {
vite?: {
environmentName?: string | undefined;
} | undefined;
hmr?: {
style?: "vite" | "webpack" | undefined;
} | undefined;
}>>;
}, "strip", z.ZodTypeAny, {
target: "react" | "solid" | "vue";
}, z.core.$strip>>;
}, z.core.$strip>>;
}, z.core.$strip>;
export declare const getConfig: (inlineConfig: Partial<Config>, root: string) => {
target: "vue" | "react" | "solid";
routeFileIgnorePrefix: string;

@@ -161,17 +135,7 @@ routesDirectory: string;

importRoutesUsingAbsolutePaths: boolean;
enableRouteGeneration?: boolean | undefined;
codeSplittingOptions?: CodeSplittingOptions | undefined;
plugin?: {
vite?: {
environmentName?: string | undefined;
} | undefined;
hmr?: {
style?: "vite" | "webpack" | undefined;
} | undefined;
} | undefined;
virtualRouteConfig?: string | import('@tanstack/virtual-file-routes').VirtualRootRoute | undefined;
routeFilePrefix?: string | undefined;
routeFileIgnorePattern?: string | undefined;
pathParamsAllowedCharacters?: (";" | ":" | "@" | "&" | "=" | "+" | "$" | ",")[] | undefined;
routeTreeFileFooter?: string[] | ((...args: unknown[]) => string[]) | undefined;
pathParamsAllowedCharacters?: (":" | "$" | ";" | "@" | "&" | "=" | "+" | ",")[] | undefined;
routeTreeFileFooter?: string[] | (() => Array<string>) | undefined;
autoCodeSplitting?: boolean | undefined;

@@ -186,95 +150,12 @@ customScaffolding?: {

plugins?: import('@tanstack/router-generator').GeneratorPlugin[] | undefined;
}, {
enableRouteGeneration?: boolean | undefined;
codeSplittingOptions?: CodeSplittingOptions | undefined;
plugin?: {
vite?: {
environmentName?: string | undefined;
} | undefined;
hmr?: {
style?: "vite" | "webpack" | undefined;
} | undefined;
} | undefined;
target?: "react" | "solid" | "vue" | undefined;
virtualRouteConfig?: string | import('@tanstack/virtual-file-routes').VirtualRootRoute | undefined;
routeFilePrefix?: string | undefined;
routeFileIgnorePrefix?: string | undefined;
routeFileIgnorePattern?: string | undefined;
routesDirectory?: string | undefined;
quoteStyle?: "single" | "double" | undefined;
semicolons?: boolean | undefined;
disableLogging?: boolean | undefined;
routeTreeFileHeader?: string[] | undefined;
indexToken?: string | RegExp | {
regex: string;
flags?: string | undefined;
} | undefined;
routeToken?: string | RegExp | {
regex: string;
flags?: string | undefined;
} | undefined;
pathParamsAllowedCharacters?: (";" | ":" | "@" | "&" | "=" | "+" | "$" | ",")[] | undefined;
generatedRouteTree?: string | undefined;
disableTypes?: boolean | undefined;
addExtensions?: string | boolean | undefined;
enableRouteTreeFormatting?: boolean | undefined;
routeTreeFileFooter?: string[] | ((...args: unknown[]) => string[]) | undefined;
autoCodeSplitting?: boolean | undefined;
customScaffolding?: {
routeTemplate?: string | undefined;
lazyRouteTemplate?: string | undefined;
} | undefined;
experimental?: {
enableCodeSplitting?: boolean | undefined;
} | undefined;
plugins?: import('@tanstack/router-generator').GeneratorPlugin[] | undefined;
tmpDir?: string | undefined;
importRoutesUsingAbsolutePaths?: boolean | undefined;
}>;
export declare const getConfig: (inlineConfig: Partial<Config>, root: string) => {
target: "react" | "solid" | "vue";
routeFileIgnorePrefix: string;
routesDirectory: string;
quoteStyle: "single" | "double";
semicolons: boolean;
disableLogging: boolean;
routeTreeFileHeader: string[];
indexToken: string | RegExp | {
regex: string;
flags?: string | undefined;
};
routeToken: string | RegExp | {
regex: string;
flags?: string | undefined;
};
generatedRouteTree: string;
disableTypes: boolean;
addExtensions: string | boolean;
enableRouteTreeFormatting: boolean;
tmpDir: string;
importRoutesUsingAbsolutePaths: boolean;
enableRouteGeneration?: boolean | undefined;
codeSplittingOptions?: CodeSplittingOptions | undefined;
plugin?: {
vite?: {
environmentName?: string | undefined;
} | undefined;
hmr?: {
style?: "vite" | "webpack" | undefined;
} | undefined;
} | undefined;
virtualRouteConfig?: string | import('@tanstack/virtual-file-routes').VirtualRootRoute | undefined;
routeFilePrefix?: string | undefined;
routeFileIgnorePattern?: string | undefined;
pathParamsAllowedCharacters?: (";" | ":" | "@" | "&" | "=" | "+" | "$" | ",")[] | undefined;
routeTreeFileFooter?: string[] | ((...args: unknown[]) => string[]) | undefined;
autoCodeSplitting?: boolean | undefined;
customScaffolding?: {
routeTemplate?: string | undefined;
lazyRouteTemplate?: string | undefined;
} | undefined;
experimental?: {
enableCodeSplitting?: boolean | undefined;
} | undefined;
plugins?: import('@tanstack/router-generator').GeneratorPlugin[] | undefined;
};

@@ -281,0 +162,0 @@ export type Config = z.infer<typeof configSchema>;

@@ -5,3 +5,2 @@ require("../_virtual/_rolldown/runtime.cjs");

const require_utils = require("./utils.cjs");
const require_path_ids = require("./code-splitter/path-ids.cjs");
const require_compilers = require("./code-splitter/compilers.cjs");

@@ -70,3 +69,3 @@ const require_framework_plugins = require("./code-splitter/plugins/framework-plugins.cjs");

if (!res.success) {
const message = res.error.errors.map((e) => e.message).join(". ");
const message = res.error.issues.map((e) => e.message).join(". ");
throw new Error(`The groupings for the route "${id}" are invalid.\n${message}`);

@@ -79,3 +78,3 @@ }

if (!res.success) {
const message = res.error.errors.map((e) => e.message).join(". ");
const message = res.error.issues.map((e) => e.message).join(". ");
throw new Error(`The groupings returned when using \`splitBehavior\` for the route "${id}" are invalid.\n${message}`);

@@ -105,7 +104,7 @@ }

sharedBindings: sharedBindings.size > 0 ? sharedBindings : void 0,
compilerPlugins: require_framework_plugins.getReferenceRouteCompilerPlugins({
compilerPlugins: [...require_framework_plugins.getReferenceRouteCompilerPlugins({
targetFramework: userConfig.target,
addHmr,
hmrStyle
})
}) ?? [], ...userConfig.codeSplittingOptions?.compilerPlugins ?? []]
});

@@ -127,3 +126,3 @@ if (compiledReferenceRoute === null) {

if (!splitValue) throw new Error(`The split value for the virtual route "${id}" was not found.`);
const rawGrouping = require_path_ids.decodeIdentifier(splitValue);
const rawGrouping = (0, _tanstack_router_utils.decodeIdentifier)(splitValue);
const grouping = [...new Set(rawGrouping)].filter((p) => require_constants.splitRouteIdentNodes.includes(p));

@@ -130,0 +129,0 @@ const baseId = id.split("?")[0];

@@ -1,1 +0,1 @@

{"version":3,"file":"router-code-splitter-plugin.cjs","names":[],"sources":["../../../src/core/router-code-splitter-plugin.ts"],"sourcesContent":["/**\n * It is important to familiarize yourself with how the code-splitting works in this plugin.\n * https://github.com/TanStack/router/pull/3355\n */\n\nimport { fileURLToPath, pathToFileURL } from 'node:url'\nimport { logDiff } from '@tanstack/router-utils'\nimport { getConfig, splitGroupingsSchema } from './config'\nimport {\n compileCodeSplitReferenceRoute,\n compileCodeSplitSharedRoute,\n compileCodeSplitVirtualRoute,\n computeSharedBindings,\n detectCodeSplitGroupingsFromRoute,\n} from './code-splitter/compilers'\nimport { getReferenceRouteCompilerPlugins } from './code-splitter/plugins/framework-plugins'\nimport {\n defaultCodeSplitGroupings,\n splitRouteIdentNodes,\n tsrShared,\n tsrSplit,\n} from './constants'\nimport { decodeIdentifier } from './code-splitter/path-ids'\nimport { debug, normalizePath, routeFactoryCallCodeFilter } from './utils'\nimport { createRouterPluginContext } from './router-plugin-context'\nimport type { CodeSplitGroupings, SplitRouteIdentNodes } from './constants'\nimport type { GetRoutesByFileMapResultValue } from '@tanstack/router-generator'\nimport type { Config } from './config'\nimport type { RouterPluginContext } from './router-plugin-context'\nimport type {\n UnpluginFactory,\n TransformResult as UnpluginTransformResult,\n} from 'unplugin'\n\nconst CODE_SPLITTER_PLUGIN_NAME =\n 'tanstack-router:code-splitter:compile-reference-file'\n\ntype TransformationPluginInfo = {\n pluginNames: Array<string>\n pkg: string\n usage: string\n}\n\n/**\n * JSX transformation plugins grouped by framework.\n * These plugins must come AFTER the TanStack Router plugin in the Vite config.\n */\nconst TRANSFORMATION_PLUGINS_BY_FRAMEWORK: Record<\n string,\n Array<TransformationPluginInfo>\n> = {\n react: [\n {\n // Babel-based React plugin\n pluginNames: ['vite:react-babel', 'vite:react-refresh'],\n pkg: '@vitejs/plugin-react',\n usage: 'react()',\n },\n {\n // SWC-based React plugin\n pluginNames: ['vite:react-swc', 'vite:react-swc:resolve-runtime'],\n pkg: '@vitejs/plugin-react-swc',\n usage: 'reactSwc()',\n },\n {\n // OXC-based React plugin (deprecated but should still be handled)\n pluginNames: ['vite:react-oxc:config', 'vite:react-oxc:refresh-runtime'],\n pkg: '@vitejs/plugin-react-oxc',\n usage: 'reactOxc()',\n },\n ],\n solid: [\n {\n pluginNames: ['solid'],\n pkg: 'vite-plugin-solid',\n usage: 'solid()',\n },\n ],\n}\n\nexport function createRouterCodeSplitterPlugin(\n options: Partial<Config | (() => Config)> | undefined = {},\n routerPluginContext: RouterPluginContext,\n): ReturnType<UnpluginFactory<Partial<Config | (() => Config)> | undefined>> {\n let ROOT: string = process.cwd()\n let userConfig: Config\n\n function initUserConfig() {\n if (typeof options === 'function') {\n userConfig = options()\n } else {\n userConfig = getConfig(options, ROOT)\n }\n }\n const isProduction = process.env.NODE_ENV === 'production'\n // Map from normalized route file path → set of shared binding names.\n // Populated by the reference compiler, consumed by virtual and shared compilers.\n const sharedBindingsMap = new Map<string, Set<string>>()\n\n const getGlobalCodeSplitGroupings = () => {\n return (\n userConfig.codeSplittingOptions?.defaultBehavior ||\n defaultCodeSplitGroupings\n )\n }\n const getShouldSplitFn = () => {\n return userConfig.codeSplittingOptions?.splitBehavior\n }\n\n const handleCompilingReferenceFile = (\n code: string,\n id: string,\n generatorNodeInfo: GetRoutesByFileMapResultValue,\n ): UnpluginTransformResult => {\n if (debug) console.info('Compiling Route: ', id)\n\n const fromCode = detectCodeSplitGroupingsFromRoute({\n code,\n filename: id,\n })\n\n if (fromCode.groupings !== undefined) {\n const res = splitGroupingsSchema.safeParse(fromCode.groupings)\n if (!res.success) {\n const message = res.error.errors.map((e) => e.message).join('. ')\n throw new Error(\n `The groupings for the route \"${id}\" are invalid.\\n${message}`,\n )\n }\n }\n\n const userShouldSplitFn = getShouldSplitFn()\n\n const pluginSplitBehavior = userShouldSplitFn?.({\n routeId: generatorNodeInfo.routeId,\n }) as CodeSplitGroupings | undefined\n\n if (pluginSplitBehavior) {\n const res = splitGroupingsSchema.safeParse(pluginSplitBehavior)\n if (!res.success) {\n const message = res.error.errors.map((e) => e.message).join('. ')\n throw new Error(\n `The groupings returned when using \\`splitBehavior\\` for the route \"${id}\" are invalid.\\n${message}`,\n )\n }\n }\n\n const splitGroupings: CodeSplitGroupings =\n fromCode.groupings ?? pluginSplitBehavior ?? getGlobalCodeSplitGroupings()\n\n // Compute shared bindings before compiling the reference route\n const sharedBindings = computeSharedBindings({\n code,\n filename: id,\n codeSplitGroupings: splitGroupings,\n })\n if (sharedBindings.size > 0) {\n sharedBindingsMap.set(id, sharedBindings)\n } else {\n sharedBindingsMap.delete(id)\n }\n\n const addHmr =\n (userConfig.codeSplittingOptions?.addHmr ?? true) && !isProduction\n const hmrStyle = userConfig.plugin?.hmr?.style ?? 'vite'\n\n const compiledReferenceRoute = compileCodeSplitReferenceRoute({\n code,\n codeSplitGroupings: splitGroupings,\n targetFramework: userConfig.target,\n filename: id,\n id,\n deleteNodes: userConfig.codeSplittingOptions?.deleteNodes\n ? new Set(userConfig.codeSplittingOptions.deleteNodes)\n : undefined,\n addHmr,\n hmrStyle,\n hmrRouteId: generatorNodeInfo.routeId,\n sharedBindings: sharedBindings.size > 0 ? sharedBindings : undefined,\n compilerPlugins: getReferenceRouteCompilerPlugins({\n targetFramework: userConfig.target,\n addHmr,\n hmrStyle,\n }),\n })\n\n if (compiledReferenceRoute === null) {\n if (debug) {\n console.info(\n `No changes made to route \"${id}\", skipping code-splitting.`,\n )\n }\n return null\n }\n if (debug) {\n logDiff(code, compiledReferenceRoute.code)\n console.log('Output:\\n', compiledReferenceRoute.code + '\\n\\n')\n }\n\n return compiledReferenceRoute\n }\n\n const handleCompilingVirtualFile = (\n code: string,\n id: string,\n ): UnpluginTransformResult => {\n if (debug) console.info('Splitting Route: ', id)\n\n const [_, ...pathnameParts] = id.split('?')\n\n const searchParams = new URLSearchParams(pathnameParts.join('?'))\n const splitValue = searchParams.get(tsrSplit)\n\n if (!splitValue) {\n throw new Error(\n `The split value for the virtual route \"${id}\" was not found.`,\n )\n }\n\n const rawGrouping = decodeIdentifier(splitValue)\n const grouping = [...new Set(rawGrouping)].filter((p) =>\n splitRouteIdentNodes.includes(p as any),\n ) as Array<SplitRouteIdentNodes>\n\n const baseId = id.split('?')[0]!\n const resolvedSharedBindings = sharedBindingsMap.get(baseId)\n\n const result = compileCodeSplitVirtualRoute({\n code,\n filename: id,\n splitTargets: grouping,\n sharedBindings: resolvedSharedBindings,\n })\n\n if (debug) {\n logDiff(code, result.code)\n console.log('Output:\\n', result.code + '\\n\\n')\n }\n\n return result\n }\n\n return [\n {\n name: 'tanstack-router:code-splitter:compile-reference-file',\n enforce: 'pre',\n\n transform: {\n filter: {\n id: {\n exclude: [tsrSplit, tsrShared],\n // this is necessary for webpack / rspack to avoid matching .html files\n include: /\\.(m|c)?(j|t)sx?$/,\n },\n code: {\n include: routeFactoryCallCodeFilter,\n },\n },\n handler(code, id) {\n const normalizedId = normalizePath(id)\n const generatorFileInfo =\n routerPluginContext.routesByFile.get(normalizedId)\n if (generatorFileInfo) {\n return handleCompilingReferenceFile(\n code,\n normalizedId,\n generatorFileInfo,\n )\n }\n\n return null\n },\n },\n\n vite: {\n configResolved(config) {\n ROOT = config.root\n initUserConfig()\n\n // Validate plugin order - router must come before JSX transformation plugins\n const routerPluginIndex = config.plugins.findIndex(\n (p) => p.name === CODE_SPLITTER_PLUGIN_NAME,\n )\n\n if (routerPluginIndex === -1) return\n\n const frameworkPlugins =\n TRANSFORMATION_PLUGINS_BY_FRAMEWORK[userConfig.target]\n if (!frameworkPlugins) return\n\n for (const transformPlugin of frameworkPlugins) {\n const transformPluginIndex = config.plugins.findIndex((p) =>\n transformPlugin.pluginNames.includes(p.name),\n )\n\n if (\n transformPluginIndex !== -1 &&\n transformPluginIndex < routerPluginIndex\n ) {\n throw new Error(\n `Plugin order error: '${transformPlugin.pkg}' is placed before '@tanstack/router-plugin'.\\n\\n` +\n `The TanStack Router plugin must come BEFORE JSX transformation plugins.\\n\\n` +\n `Please update your Vite config:\\n\\n` +\n ` plugins: [\\n` +\n ` tanstackRouter(),\\n` +\n ` ${transformPlugin.usage},\\n` +\n ` ]\\n`,\n )\n }\n }\n },\n applyToEnvironment(environment) {\n if (userConfig.plugin?.vite?.environmentName) {\n return userConfig.plugin.vite.environmentName === environment.name\n }\n return true\n },\n },\n\n rspack() {\n ROOT = process.cwd()\n initUserConfig()\n },\n\n webpack() {\n ROOT = process.cwd()\n initUserConfig()\n },\n },\n {\n name: 'tanstack-router:code-splitter:compile-virtual-file',\n enforce: 'pre',\n\n transform: {\n filter: {\n id: /tsr-split/,\n },\n handler(code, id) {\n const url = pathToFileURL(id)\n url.searchParams.delete('v')\n const normalizedId = normalizePath(fileURLToPath(url))\n return handleCompilingVirtualFile(code, normalizedId)\n },\n },\n\n vite: {\n applyToEnvironment(environment) {\n if (userConfig.plugin?.vite?.environmentName) {\n return userConfig.plugin.vite.environmentName === environment.name\n }\n return true\n },\n },\n },\n {\n name: 'tanstack-router:code-splitter:compile-shared-file',\n enforce: 'pre',\n\n transform: {\n filter: {\n id: /tsr-shared/,\n },\n handler(code, id) {\n const url = pathToFileURL(id)\n url.searchParams.delete('v')\n const normalizedId = normalizePath(fileURLToPath(url))\n const [baseId] = normalizedId.split('?')\n\n if (!baseId) return null\n\n const sharedBindings = sharedBindingsMap.get(baseId)\n if (!sharedBindings || sharedBindings.size === 0) return null\n\n if (debug) console.info('Compiling Shared Module: ', id)\n\n const result = compileCodeSplitSharedRoute({\n code,\n sharedBindings,\n filename: normalizedId,\n })\n\n if (debug) {\n logDiff(code, result.code)\n console.log('Output:\\n', result.code + '\\n\\n')\n }\n\n return result\n },\n },\n\n vite: {\n applyToEnvironment(environment) {\n if (userConfig.plugin?.vite?.environmentName) {\n return userConfig.plugin.vite.environmentName === environment.name\n }\n return true\n },\n },\n },\n ]\n}\n\nexport const unpluginRouterCodeSplitterFactory: UnpluginFactory<\n Partial<Config | (() => Config)> | undefined\n> = (options = {}) => {\n return createRouterCodeSplitterPlugin(options, createRouterPluginContext())\n}\n"],"mappings":";;;;;;;;;;;;;;;AAkCA,IAAM,4BACJ;;;;;AAYF,IAAM,sCAGF;CACF,OAAO;EACL;GAEE,aAAa,CAAC,oBAAoB,qBAAqB;GACvD,KAAK;GACL,OAAO;GACR;EACD;GAEE,aAAa,CAAC,kBAAkB,iCAAiC;GACjE,KAAK;GACL,OAAO;GACR;EACD;GAEE,aAAa,CAAC,yBAAyB,iCAAiC;GACxE,KAAK;GACL,OAAO;GACR;EACF;CACD,OAAO,CACL;EACE,aAAa,CAAC,QAAQ;EACtB,KAAK;EACL,OAAO;EACR,CACF;CACF;AAED,SAAgB,+BACd,UAAwD,EAAE,EAC1D,qBAC2E;CAC3E,IAAI,OAAe,QAAQ,KAAK;CAChC,IAAI;CAEJ,SAAS,iBAAiB;AACxB,MAAI,OAAO,YAAY,WACrB,cAAa,SAAS;MAEtB,cAAa,eAAA,UAAU,SAAS,KAAK;;CAGzC,MAAM,eAAA,QAAA,IAAA,aAAwC;CAG9C,MAAM,oCAAoB,IAAI,KAA0B;CAExD,MAAM,oCAAoC;AACxC,SACE,WAAW,s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QAAQ,MAAM,gBAC3B,QAAO,WAAW,OAAO,KAAK,oBAAoB,YAAY;AAEhE,WAAO;MAEV;GACF;EACD;GACE,MAAM;GACN,SAAS;GAET,WAAW;IACT,QAAQ,EACN,IAAI,cACL;IACD,QAAQ,MAAM,IAAI;KAChB,MAAM,OAAA,GAAA,SAAA,eAAoB,GAAG;AAC7B,SAAI,aAAa,OAAO,IAAI;KAC5B,MAAM,eAAe,cAAA,eAAA,GAAA,SAAA,eAA4B,IAAI,CAAC;KACtD,MAAM,CAAC,UAAU,aAAa,MAAM,IAAI;AAExC,SAAI,CAAC,OAAQ,QAAO;KAEpB,MAAM,iBAAiB,kBAAkB,IAAI,OAAO;AACpD,SAAI,CAAC,kBAAkB,eAAe,SAAS,EAAG,QAAO;AAEzD,SAAI,cAAA,MAAO,SAAQ,KAAK,6BAA6B,GAAG;KAExD,MAAM,SAAS,kBAAA,4BAA4B;MACzC;MACA;MACA,UAAU;MACX,CAAC;AAEF,SAAI,cAAA,OAAO;AACT,OAAA,GAAA,uBAAA,SAAQ,MAAM,OAAO,KAAK;AAC1B,cAAQ,IAAI,aAAa,OAAO,OAAO,OAAO;;AAGhD,YAAO;;IAEV;GAED,MAAM,EACJ,mBAAmB,aAAa;AAC9B,QAAI,WAAW,QAAQ,MAAM,gBAC3B,QAAO,WAAW,OAAO,KAAK,oBAAoB,YAAY;AAEhE,WAAO;MAEV;GACF;EACF;;AAGH,IAAa,qCAER,UAAU,EAAE,KAAK;AACpB,QAAO,+BAA+B,SAAS,8BAAA,2BAA2B,CAAC"}
{"version":3,"file":"router-code-splitter-plugin.cjs","names":[],"sources":["../../../src/core/router-code-splitter-plugin.ts"],"sourcesContent":["/**\n * It is important to familiarize yourself with how the code-splitting works in this plugin.\n * https://github.com/TanStack/router/pull/3355\n */\n\nimport { fileURLToPath, pathToFileURL } from 'node:url'\nimport { decodeIdentifier, logDiff } from '@tanstack/router-utils'\nimport { getConfig, splitGroupingsSchema } from './config'\nimport {\n compileCodeSplitReferenceRoute,\n compileCodeSplitSharedRoute,\n compileCodeSplitVirtualRoute,\n computeSharedBindings,\n detectCodeSplitGroupingsFromRoute,\n} from './code-splitter/compilers'\nimport { getReferenceRouteCompilerPlugins } from './code-splitter/plugins/framework-plugins'\nimport {\n defaultCodeSplitGroupings,\n splitRouteIdentNodes,\n tsrShared,\n tsrSplit,\n} from './constants'\nimport { debug, normalizePath, routeFactoryCallCodeFilter } from './utils'\nimport { createRouterPluginContext } from './router-plugin-context'\nimport type { CodeSplitGroupings, SplitRouteIdentNodes } from './constants'\nimport type { GetRoutesByFileMapResultValue } from '@tanstack/router-generator'\nimport type { Config } from './config'\nimport type { RouterPluginContext } from './router-plugin-context'\nimport type {\n UnpluginFactory,\n TransformResult as UnpluginTransformResult,\n} from 'unplugin'\n\nconst CODE_SPLITTER_PLUGIN_NAME =\n 'tanstack-router:code-splitter:compile-reference-file'\n\ntype TransformationPluginInfo = {\n pluginNames: Array<string>\n pkg: string\n usage: string\n}\n\n/**\n * JSX transformation plugins grouped by framework.\n * These plugins must come AFTER the TanStack Router plugin in the Vite config.\n */\nconst TRANSFORMATION_PLUGINS_BY_FRAMEWORK: Record<\n string,\n Array<TransformationPluginInfo>\n> = {\n react: [\n {\n // Babel-based React plugin\n pluginNames: ['vite:react-babel', 'vite:react-refresh'],\n pkg: '@vitejs/plugin-react',\n usage: 'react()',\n },\n {\n // SWC-based React plugin\n pluginNames: ['vite:react-swc', 'vite:react-swc:resolve-runtime'],\n pkg: '@vitejs/plugin-react-swc',\n usage: 'reactSwc()',\n },\n {\n // OXC-based React plugin (deprecated but should still be handled)\n pluginNames: ['vite:react-oxc:config', 'vite:react-oxc:refresh-runtime'],\n pkg: '@vitejs/plugin-react-oxc',\n usage: 'reactOxc()',\n },\n ],\n solid: [\n {\n pluginNames: ['solid'],\n pkg: 'vite-plugin-solid',\n usage: 'solid()',\n },\n ],\n}\n\nexport function createRouterCodeSplitterPlugin(\n options: Partial<Config | (() => Config)> | undefined = {},\n routerPluginContext: RouterPluginContext,\n): ReturnType<UnpluginFactory<Partial<Config | (() => Config)> | undefined>> {\n let ROOT: string = process.cwd()\n let userConfig: Config\n\n function initUserConfig() {\n if (typeof options === 'function') {\n userConfig = options()\n } else {\n userConfig = getConfig(options, ROOT)\n }\n }\n const isProduction = process.env.NODE_ENV === 'production'\n // Map from normalized route file path → set of shared binding names.\n // Populated by the reference compiler, consumed by virtual and shared compilers.\n const sharedBindingsMap = new Map<string, Set<string>>()\n\n const getGlobalCodeSplitGroupings = () => {\n return (\n userConfig.codeSplittingOptions?.defaultBehavior ||\n defaultCodeSplitGroupings\n )\n }\n const getShouldSplitFn = () => {\n return userConfig.codeSplittingOptions?.splitBehavior\n }\n\n const handleCompilingReferenceFile = (\n code: string,\n id: string,\n generatorNodeInfo: GetRoutesByFileMapResultValue,\n ): UnpluginTransformResult => {\n if (debug) console.info('Compiling Route: ', id)\n\n const fromCode = detectCodeSplitGroupingsFromRoute({\n code,\n filename: id,\n })\n\n if (fromCode.groupings !== undefined) {\n const res = splitGroupingsSchema.safeParse(fromCode.groupings)\n if (!res.success) {\n const message = res.error.issues.map((e) => e.message).join('. ')\n throw new Error(\n `The groupings for the route \"${id}\" are invalid.\\n${message}`,\n )\n }\n }\n\n const userShouldSplitFn = getShouldSplitFn()\n\n const pluginSplitBehavior = userShouldSplitFn?.({\n routeId: generatorNodeInfo.routeId,\n }) as CodeSplitGroupings | undefined\n\n if (pluginSplitBehavior) {\n const res = splitGroupingsSchema.safeParse(pluginSplitBehavior)\n if (!res.success) {\n const message = res.error.issues.map((e) => e.message).join('. ')\n throw new Error(\n `The groupings returned when using \\`splitBehavior\\` for the route \"${id}\" are invalid.\\n${message}`,\n )\n }\n }\n\n const splitGroupings: CodeSplitGroupings =\n fromCode.groupings ?? pluginSplitBehavior ?? getGlobalCodeSplitGroupings()\n\n // Compute shared bindings before compiling the reference route\n const sharedBindings = computeSharedBindings({\n code,\n filename: id,\n codeSplitGroupings: splitGroupings,\n })\n if (sharedBindings.size > 0) {\n sharedBindingsMap.set(id, sharedBindings)\n } else {\n sharedBindingsMap.delete(id)\n }\n\n const addHmr =\n (userConfig.codeSplittingOptions?.addHmr ?? true) && !isProduction\n const hmrStyle = userConfig.plugin?.hmr?.style ?? 'vite'\n\n const compiledReferenceRoute = compileCodeSplitReferenceRoute({\n code,\n codeSplitGroupings: splitGroupings,\n targetFramework: userConfig.target,\n filename: id,\n id,\n deleteNodes: userConfig.codeSplittingOptions?.deleteNodes\n ? new Set(userConfig.codeSplittingOptions.deleteNodes)\n : undefined,\n addHmr,\n hmrStyle,\n hmrRouteId: generatorNodeInfo.routeId,\n sharedBindings: sharedBindings.size > 0 ? sharedBindings : undefined,\n compilerPlugins: [\n ...(getReferenceRouteCompilerPlugins({\n targetFramework: userConfig.target,\n addHmr,\n hmrStyle,\n }) ?? []),\n ...(userConfig.codeSplittingOptions?.compilerPlugins ?? []),\n ],\n })\n\n if (compiledReferenceRoute === null) {\n if (debug) {\n console.info(\n `No changes made to route \"${id}\", skipping code-splitting.`,\n )\n }\n return null\n }\n if (debug) {\n logDiff(code, compiledReferenceRoute.code)\n console.log('Output:\\n', compiledReferenceRoute.code + '\\n\\n')\n }\n\n return compiledReferenceRoute\n }\n\n const handleCompilingVirtualFile = (\n code: string,\n id: string,\n ): UnpluginTransformResult => {\n if (debug) console.info('Splitting Route: ', id)\n\n const [_, ...pathnameParts] = id.split('?')\n\n const searchParams = new URLSearchParams(pathnameParts.join('?'))\n const splitValue = searchParams.get(tsrSplit)\n\n if (!splitValue) {\n throw new Error(\n `The split value for the virtual route \"${id}\" was not found.`,\n )\n }\n\n const rawGrouping = decodeIdentifier(splitValue)\n const grouping = [...new Set(rawGrouping)].filter((p) =>\n splitRouteIdentNodes.includes(p as any),\n ) as Array<SplitRouteIdentNodes>\n\n const baseId = id.split('?')[0]!\n const resolvedSharedBindings = sharedBindingsMap.get(baseId)\n\n const result = compileCodeSplitVirtualRoute({\n code,\n filename: id,\n splitTargets: grouping,\n sharedBindings: resolvedSharedBindings,\n })\n\n if (debug) {\n logDiff(code, result.code)\n console.log('Output:\\n', result.code + '\\n\\n')\n }\n\n return result\n }\n\n return [\n {\n name: 'tanstack-router:code-splitter:compile-reference-file',\n enforce: 'pre',\n\n transform: {\n filter: {\n id: {\n exclude: [tsrSplit, tsrShared],\n // this is necessary for webpack / rspack to avoid matching .html files\n include: /\\.(m|c)?(j|t)sx?$/,\n },\n code: {\n include: routeFactoryCallCodeFilter,\n },\n },\n handler(code, id) {\n const normalizedId = normalizePath(id)\n const generatorFileInfo =\n routerPluginContext.routesByFile.get(normalizedId)\n if (generatorFileInfo) {\n return handleCompilingReferenceFile(\n code,\n normalizedId,\n generatorFileInfo,\n )\n }\n\n return null\n },\n },\n\n vite: {\n configResolved(config) {\n ROOT = config.root\n initUserConfig()\n\n // Validate plugin order - router must come before JSX transformation plugins\n const routerPluginIndex = config.plugins.findIndex(\n (p) => p.name === CODE_SPLITTER_PLUGIN_NAME,\n )\n\n if (routerPluginIndex === -1) return\n\n const frameworkPlugins =\n TRANSFORMATION_PLUGINS_BY_FRAMEWORK[userConfig.target]\n if (!frameworkPlugins) return\n\n for (const transformPlugin of frameworkPlugins) {\n const transformPluginIndex = config.plugins.findIndex((p) =>\n transformPlugin.pluginNames.includes(p.name),\n )\n\n if (\n transformPluginIndex !== -1 &&\n transformPluginIndex < routerPluginIndex\n ) {\n throw new Error(\n `Plugin order error: '${transformPlugin.pkg}' is placed before '@tanstack/router-plugin'.\\n\\n` +\n `The TanStack Router plugin must come BEFORE JSX transformation plugins.\\n\\n` +\n `Please update your Vite config:\\n\\n` +\n ` plugins: [\\n` +\n ` tanstackRouter(),\\n` +\n ` ${transformPlugin.usage},\\n` +\n ` ]\\n`,\n )\n }\n }\n },\n applyToEnvironment(environment) {\n if (userConfig.plugin?.vite?.environmentName) {\n return userConfig.plugin.vite.environmentName === environment.name\n }\n return true\n },\n },\n\n rspack() {\n ROOT = process.cwd()\n initUserConfig()\n },\n\n webpack() {\n ROOT = process.cwd()\n initUserConfig()\n },\n },\n {\n name: 'tanstack-router:code-splitter:compile-virtual-file',\n enforce: 'pre',\n\n transform: {\n filter: {\n id: /tsr-split/,\n },\n handler(code, id) {\n const url = pathToFileURL(id)\n url.searchParams.delete('v')\n const normalizedId = normalizePath(fileURLToPath(url))\n return handleCompilingVirtualFile(code, normalizedId)\n },\n },\n\n vite: {\n applyToEnvironment(environment) {\n if (userConfig.plugin?.vite?.environmentName) {\n return userConfig.plugin.vite.environmentName === environment.name\n }\n return true\n },\n },\n },\n {\n name: 'tanstack-router:code-splitter:compile-shared-file',\n enforce: 'pre',\n\n transform: {\n filter: {\n id: /tsr-shared/,\n },\n handler(code, id) {\n const url = pathToFileURL(id)\n url.searchParams.delete('v')\n const normalizedId = normalizePath(fileURLToPath(url))\n const [baseId] = normalizedId.split('?')\n\n if (!baseId) return null\n\n const sharedBindings = sharedBindingsMap.get(baseId)\n if (!sharedBindings || sharedBindings.size === 0) return null\n\n if (debug) console.info('Compiling Shared Module: ', id)\n\n const result = compileCodeSplitSharedRoute({\n code,\n sharedBindings,\n filename: normalizedId,\n })\n\n if (debug) {\n logDiff(code, result.code)\n console.log('Output:\\n', result.code + '\\n\\n')\n }\n\n return result\n },\n },\n\n vite: {\n applyToEnvironment(environment) {\n if (userConfig.plugin?.vite?.environmentName) {\n return userConfig.plugin.vite.environmentName === environment.name\n }\n return true\n },\n },\n },\n ]\n}\n\nexport const unpluginRouterCodeSplitterFactory: UnpluginFactory<\n Partial<Config | (() => Config)> | undefined\n> = (options = {}) => {\n return createRouterCodeSplitterPlugin(options, createRouterPluginContext())\n}\n"],"mappings":";;;;;;;;;;;;;;AAiCA,IAAM,4BACJ;;;;;AAYF,IAAM,sCAGF;CACF,OAAO;EACL;GAEE,aAAa,CAAC,oBAAoB,qBAAqB;GACvD,KAAK;GACL,OAAO;GACR;EACD;GAEE,aAAa,CAAC,kBAAkB,iCAAiC;GACjE,KAAK;GACL,OAAO;GACR;EACD;GAEE,a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;AAGhD,YAAO;;IAEV;GAED,MAAM,EACJ,mBAAmB,aAAa;AAC9B,QAAI,WAAW,QAAQ,MAAM,gBAC3B,QAAO,WAAW,OAAO,KAAK,oBAAoB,YAAY;AAEhE,WAAO;MAEV;GACF;EACF;;AAGH,IAAa,qCAER,UAAU,EAAE,KAAK;AACpB,QAAO,+BAA+B,SAAS,8BAAA,2BAA2B,CAAC"}

@@ -34,3 +34,3 @@ import { configSchema, CodeSplittingOptions, Config } from './core/config.cjs';

declare const TanStackRouterEsbuild: (options?: Partial<{
target: "react" | "solid" | "vue";
target: "vue" | "react" | "solid";
routeFileIgnorePrefix: string;

@@ -56,17 +56,7 @@ routesDirectory: string;

importRoutesUsingAbsolutePaths: boolean;
enableRouteGeneration?: boolean | undefined;
codeSplittingOptions?: CodeSplittingOptions | undefined;
plugin?: {
vite?: {
environmentName?: string | undefined;
} | undefined;
hmr?: {
style?: "vite" | "webpack" | undefined;
} | undefined;
} | undefined;
virtualRouteConfig?: string | import('@tanstack/virtual-file-routes').VirtualRootRoute | undefined;
routeFilePrefix?: string | undefined;
routeFileIgnorePattern?: string | undefined;
pathParamsAllowedCharacters?: (";" | ":" | "@" | "&" | "=" | "+" | "$" | ",")[] | undefined;
routeTreeFileFooter?: string[] | ((...args: unknown[]) => string[]) | undefined;
pathParamsAllowedCharacters?: (":" | "$" | ";" | "@" | "&" | "=" | "+" | ",")[] | undefined;
routeTreeFileFooter?: string[] | (() => Array<string>) | undefined;
autoCodeSplitting?: boolean | undefined;

@@ -81,5 +71,15 @@ customScaffolding?: {

plugins?: import('@tanstack/router-generator').GeneratorPlugin[] | undefined;
enableRouteGeneration?: boolean | undefined;
codeSplittingOptions?: CodeSplittingOptions | undefined;
plugin?: {
hmr?: {
style?: "vite" | "webpack" | undefined;
} | undefined;
vite?: {
environmentName?: string | undefined;
} | undefined;
} | undefined;
} | (() => Config)> | undefined) => import('unplugin').EsbuildPlugin;
declare const tanstackRouter: (options?: Partial<{
target: "react" | "solid" | "vue";
target: "vue" | "react" | "solid";
routeFileIgnorePrefix: string;

@@ -105,17 +105,7 @@ routesDirectory: string;

importRoutesUsingAbsolutePaths: boolean;
enableRouteGeneration?: boolean | undefined;
codeSplittingOptions?: CodeSplittingOptions | undefined;
plugin?: {
vite?: {
environmentName?: string | undefined;
} | undefined;
hmr?: {
style?: "vite" | "webpack" | undefined;
} | undefined;
} | undefined;
virtualRouteConfig?: string | import('@tanstack/virtual-file-routes').VirtualRootRoute | undefined;
routeFilePrefix?: string | undefined;
routeFileIgnorePattern?: string | undefined;
pathParamsAllowedCharacters?: (";" | ":" | "@" | "&" | "=" | "+" | "$" | ",")[] | undefined;
routeTreeFileFooter?: string[] | ((...args: unknown[]) => string[]) | undefined;
pathParamsAllowedCharacters?: (":" | "$" | ";" | "@" | "&" | "=" | "+" | ",")[] | undefined;
routeTreeFileFooter?: string[] | (() => Array<string>) | undefined;
autoCodeSplitting?: boolean | undefined;

@@ -130,2 +120,12 @@ customScaffolding?: {

plugins?: import('@tanstack/router-generator').GeneratorPlugin[] | undefined;
enableRouteGeneration?: boolean | undefined;
codeSplittingOptions?: CodeSplittingOptions | undefined;
plugin?: {
hmr?: {
style?: "vite" | "webpack" | undefined;
} | undefined;
vite?: {
environmentName?: string | undefined;
} | undefined;
} | undefined;
} | (() => Config)> | undefined) => import('unplugin').EsbuildPlugin;

@@ -132,0 +132,0 @@ export default TanStackRouterEsbuild;

Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
const require_config = require("./core/config.cjs");
const require_constants = require("./core/constants.cjs");
const require_utils = require("./core/utils.cjs");
const require_router_plugin_context = require("./core/router-plugin-context.cjs");

@@ -11,2 +12,3 @@ const require_router_code_splitter_plugin = require("./core/router-code-splitter-plugin.cjs");

exports.getConfig = require_config.getConfig;
exports.getObjectPropertyKeyName = require_utils.getObjectPropertyKeyName;
exports.splitRouteIdentNodes = require_constants.splitRouteIdentNodes;

@@ -13,0 +15,0 @@ exports.tsrSplit = require_constants.tsrSplit;

@@ -7,2 +7,4 @@ export { configSchema, getConfig } from './core/config.cjs';

export type { RouterPluginContext } from './core/router-plugin-context.cjs';
export { getObjectPropertyKeyName } from './core/utils.cjs';
export type { ReferenceRouteCompilerPlugin, ReferenceRouteCompilerPluginContext, } from './core/code-splitter/plugins.cjs';
export { tsrSplit, splitRouteIdentNodes, defaultCodeSplitGroupings, } from './core/constants.cjs';

@@ -34,3 +34,3 @@ import { configSchema, getConfig, CodeSplittingOptions, Config } from './core/config.cjs';

declare const tanstackRouter: (options?: Partial<{
target: "react" | "solid" | "vue";
target: "vue" | "react" | "solid";
routeFileIgnorePrefix: string;

@@ -56,17 +56,7 @@ routesDirectory: string;

importRoutesUsingAbsolutePaths: boolean;
enableRouteGeneration?: boolean | undefined;
codeSplittingOptions?: CodeSplittingOptions | undefined;
plugin?: {
vite?: {
environmentName?: string | undefined;
} | undefined;
hmr?: {
style?: "vite" | "webpack" | undefined;
} | undefined;
} | undefined;
virtualRouteConfig?: string | import('@tanstack/virtual-file-routes').VirtualRootRoute | undefined;
routeFilePrefix?: string | undefined;
routeFileIgnorePattern?: string | undefined;
pathParamsAllowedCharacters?: (";" | ":" | "@" | "&" | "=" | "+" | "$" | ",")[] | undefined;
routeTreeFileFooter?: string[] | ((...args: unknown[]) => string[]) | undefined;
pathParamsAllowedCharacters?: (":" | "$" | ";" | "@" | "&" | "=" | "+" | ",")[] | undefined;
routeTreeFileFooter?: string[] | (() => Array<string>) | undefined;
autoCodeSplitting?: boolean | undefined;

@@ -81,2 +71,12 @@ customScaffolding?: {

plugins?: import('@tanstack/router-generator').GeneratorPlugin[] | undefined;
enableRouteGeneration?: boolean | undefined;
codeSplittingOptions?: CodeSplittingOptions | undefined;
plugin?: {
hmr?: {
style?: "vite" | "webpack" | undefined;
} | undefined;
vite?: {
environmentName?: string | undefined;
} | undefined;
} | undefined;
} | (() => Config)> | undefined) => import('vite').Plugin<any> | import('vite').Plugin<any>[];

@@ -87,3 +87,3 @@ /**

declare const TanStackRouterVite: (options?: Partial<{
target: "react" | "solid" | "vue";
target: "vue" | "react" | "solid";
routeFileIgnorePrefix: string;

@@ -109,17 +109,7 @@ routesDirectory: string;

importRoutesUsingAbsolutePaths: boolean;
enableRouteGeneration?: boolean | undefined;
codeSplittingOptions?: CodeSplittingOptions | undefined;
plugin?: {
vite?: {
environmentName?: string | undefined;
} | undefined;
hmr?: {
style?: "vite" | "webpack" | undefined;
} | undefined;
} | undefined;
virtualRouteConfig?: string | import('@tanstack/virtual-file-routes').VirtualRootRoute | undefined;
routeFilePrefix?: string | undefined;
routeFileIgnorePattern?: string | undefined;
pathParamsAllowedCharacters?: (";" | ":" | "@" | "&" | "=" | "+" | "$" | ",")[] | undefined;
routeTreeFileFooter?: string[] | ((...args: unknown[]) => string[]) | undefined;
pathParamsAllowedCharacters?: (":" | "$" | ";" | "@" | "&" | "=" | "+" | ",")[] | undefined;
routeTreeFileFooter?: string[] | (() => Array<string>) | undefined;
autoCodeSplitting?: boolean | undefined;

@@ -134,2 +124,12 @@ customScaffolding?: {

plugins?: import('@tanstack/router-generator').GeneratorPlugin[] | undefined;
enableRouteGeneration?: boolean | undefined;
codeSplittingOptions?: CodeSplittingOptions | undefined;
plugin?: {
hmr?: {
style?: "vite" | "webpack" | undefined;
} | undefined;
vite?: {
environmentName?: string | undefined;
} | undefined;
} | undefined;
} | (() => Config)> | undefined) => import('vite').Plugin<any> | import('vite').Plugin<any>[];

@@ -136,0 +136,0 @@ export default tanstackRouter;

import { CompileCodeSplitReferenceRouteOptions, ReferenceRouteCompilerPlugin } from './plugins.js';
import { GeneratorResult, ParseAstOptions } from '@tanstack/router-utils';
import { CodeSplitGroupings, SplitRouteIdentNodes } from '../constants.js';
import * as t from '@babel/types';
export { buildDeclarationMap, buildDependencyGraph, collectIdentifiersFromNode, collectLocalBindingsFromStatement, collectModuleLevelRefsFromNode, expandDestructuredDeclarations, expandSharedDestructuredDeclarators, expandTransitively, removeBindingsTransitivelyDependingOn, } from '@tanstack/router-utils';
export declare function removeBindingsDependingOnRoute(bindings: Set<string>, dependencyGraph: Map<string, Set<string>>): void;
export declare function addSharedSearchParamToFilename(filename: string): string;
/**
* Recursively walk an AST node and collect referenced identifier-like names.
* Much cheaper than babel.traverse — no path/scope overhead.
*
* Notes:
* - Uses @babel/types `isReferenced` to avoid collecting non-references like
* object keys, member expression properties, or binding identifiers.
* - Also handles JSX identifiers for component references.
*/
export declare function collectIdentifiersFromNode(node: t.Node): Set<string>;
/**
* Build a map from binding name → declaration AST node for all
* locally-declared module-level bindings. Built once, O(1) lookup.
*/
export declare function buildDeclarationMap(ast: t.File): Map<string, t.Node>;
/**
* Build a dependency graph: for each local binding, the set of other local
* bindings its declaration references. Built once via simple node walking.
*/
export declare function buildDependencyGraph(declMap: Map<string, t.Node>, localBindings: Set<string>): Map<string, Set<string>>;
/**
* Computes module-level bindings that are shared between split and non-split

@@ -40,38 +21,2 @@ * route properties. These bindings need to be extracted into a shared virtual

}): Set<string>;
/**
* If bindings from the same destructured declarator are referenced by
* different groups, mark all bindings from that declarator as shared.
*/
export declare function expandSharedDestructuredDeclarators(ast: t.File, refsByGroup: Map<string, Set<number>>, shared: Set<string>): void;
/**
* Collect locally-declared module-level binding names from a statement.
* Pure node inspection, no traversal.
*/
export declare function collectLocalBindingsFromStatement(node: t.Statement | t.ModuleDeclaration, bindings: Set<string>): void;
/**
* Collect direct module-level binding names referenced from a given AST node.
* Uses a simple recursive walk instead of babel.traverse.
*/
export declare function collectModuleLevelRefsFromNode(node: t.Node, localModuleLevelBindings: Set<string>): Set<string>;
/**
* Expand the shared set transitively using a prebuilt dependency graph.
* No AST traversals — pure graph BFS.
*/
export declare function expandTransitively(shared: Set<string>, depGraph: Map<string, Set<string>>): void;
/**
* Remove any bindings from `shared` that transitively depend on `Route`.
* The Route singleton must remain in the reference file; if a shared binding
* references it (directly or transitively), extracting that binding would
* duplicate Route in the shared module.
*
* Uses `depGraph` which must include `Route` as a node so the dependency
* chain is visible.
*/
export declare function removeBindingsDependingOnRoute(shared: Set<string>, depGraph: Map<string, Set<string>>): void;
/**
* If any binding from a destructured declaration is shared,
* ensure all bindings from that same declaration are also shared.
* Pure node inspection of program.body, no traversal.
*/
export declare function expandDestructuredDeclarations(ast: t.File, shared: Set<string>): void;
export declare function compileCodeSplitReferenceRoute(opts: ParseAstOptions & CompileCodeSplitReferenceRouteOptions & {

@@ -78,0 +23,0 @@ compilerPlugins?: Array<ReferenceRouteCompilerPlugin>;

import { tsrShared, tsrSplit } from "../constants.js";
import { createRouteHmrStatement } from "../hmr/select-adapter.js";
import { getObjectPropertyKeyName } from "../utils.js";
import { createIdentifier } from "./path-ids.js";
import { getFrameworkOptions } from "./framework-options.js";
import { deadCodeElimination, findReferencedIdentifiers, generateFromAst, parseAst } from "@tanstack/router-utils";
import { buildDeclarationMap, buildDependencyGraph, collectIdentifiersFromPattern, collectLocalBindingsFromStatement, collectModuleLevelRefsFromNode, createIdentifier, deadCodeElimination, expandDestructuredDeclarations, expandSharedDestructuredDeclarators, expandTransitively, findReferencedIdentifiers, generateFromAst, parseAst, removeBindingsTransitivelyDependingOn, retainModuleLevelDeclarations, stripUnreferencedTopLevelExpressionStatements, unwrapExportedDeclarations } from "@tanstack/router-utils";
import * as t from "@babel/types";

@@ -67,65 +66,2 @@ import * as babel from "@babel/core";

/**
* Recursively walk an AST node and collect referenced identifier-like names.
* Much cheaper than babel.traverse — no path/scope overhead.
*
* Notes:
* - Uses @babel/types `isReferenced` to avoid collecting non-references like
* object keys, member expression properties, or binding identifiers.
* - Also handles JSX identifiers for component references.
*/
function collectIdentifiersFromNode(node) {
const ids = /* @__PURE__ */ new Set();
(function walk(n, parent, grandparent, parentKey) {
if (!n) return;
if (t.isIdentifier(n)) {
if (!parent || t.isReferenced(n, parent, grandparent)) ids.add(n.name);
return;
}
if (t.isJSXIdentifier(n)) {
if (parent && t.isJSXAttribute(parent) && parentKey === "name") return;
if (parent && t.isJSXMemberExpression(parent) && parentKey === "property") return;
const first = n.name[0];
if (first && first === first.toLowerCase()) return;
ids.add(n.name);
return;
}
for (const key of t.VISITOR_KEYS[n.type] || []) {
const child = n[key];
if (Array.isArray(child)) {
for (const c of child) if (c && typeof c.type === "string") walk(c, n, parent, key);
} else if (child && typeof child.type === "string") walk(child, n, parent, key);
}
})(node);
return ids;
}
/**
* Build a map from binding name → declaration AST node for all
* locally-declared module-level bindings. Built once, O(1) lookup.
*/
function buildDeclarationMap(ast) {
const map = /* @__PURE__ */ new Map();
for (const stmt of ast.program.body) {
const decl = t.isExportNamedDeclaration(stmt) && stmt.declaration ? stmt.declaration : stmt;
if (t.isVariableDeclaration(decl)) for (const declarator of decl.declarations) for (const name of collectIdentifiersFromPattern(declarator.id)) map.set(name, declarator);
else if (t.isFunctionDeclaration(decl) && decl.id) map.set(decl.id.name, decl);
else if (t.isClassDeclaration(decl) && decl.id) map.set(decl.id.name, decl);
}
return map;
}
/**
* Build a dependency graph: for each local binding, the set of other local
* bindings its declaration references. Built once via simple node walking.
*/
function buildDependencyGraph(declMap, localBindings) {
const graph = /* @__PURE__ */ new Map();
for (const [name, declNode] of declMap) {
if (!localBindings.has(name)) continue;
const allIds = collectIdentifiersFromNode(declNode);
const deps = /* @__PURE__ */ new Set();
for (const id of allIds) if (id !== name && localBindings.has(id)) deps.add(id);
graph.set(name, deps);
}
return graph;
}
/**
* Computes module-level bindings that are shared between split and non-split

@@ -206,113 +142,6 @@ * route properties. These bindings need to be extracted into a shared virtual

expandDestructuredDeclarations(ast, shared);
removeBindingsDependingOnRoute(shared, fullDepGraph);
removeBindingsTransitivelyDependingOn(shared, fullDepGraph, ["Route"]);
return shared;
}
/**
* If bindings from the same destructured declarator are referenced by
* different groups, mark all bindings from that declarator as shared.
*/
function expandSharedDestructuredDeclarators(ast, refsByGroup, shared) {
for (const stmt of ast.program.body) {
const decl = t.isExportNamedDeclaration(stmt) && stmt.declaration ? stmt.declaration : stmt;
if (!t.isVariableDeclaration(decl)) continue;
for (const declarator of decl.declarations) {
if (!t.isObjectPattern(declarator.id) && !t.isArrayPattern(declarator.id)) continue;
const names = collectIdentifiersFromPattern(declarator.id);
const usedGroups = /* @__PURE__ */ new Set();
for (const name of names) {
const groups = refsByGroup.get(name);
if (!groups) continue;
for (const g of groups) usedGroups.add(g);
}
if (usedGroups.size >= 2) for (const name of names) shared.add(name);
}
}
}
/**
* Collect locally-declared module-level binding names from a statement.
* Pure node inspection, no traversal.
*/
function collectLocalBindingsFromStatement(node, bindings) {
const decl = t.isExportNamedDeclaration(node) && node.declaration ? node.declaration : node;
if (t.isVariableDeclaration(decl)) for (const declarator of decl.declarations) for (const name of collectIdentifiersFromPattern(declarator.id)) bindings.add(name);
else if (t.isFunctionDeclaration(decl) && decl.id) bindings.add(decl.id.name);
else if (t.isClassDeclaration(decl) && decl.id) bindings.add(decl.id.name);
}
/**
* Collect direct module-level binding names referenced from a given AST node.
* Uses a simple recursive walk instead of babel.traverse.
*/
function collectModuleLevelRefsFromNode(node, localModuleLevelBindings) {
const allIds = collectIdentifiersFromNode(node);
const refs = /* @__PURE__ */ new Set();
for (const name of allIds) if (localModuleLevelBindings.has(name)) refs.add(name);
return refs;
}
/**
* Expand the shared set transitively using a prebuilt dependency graph.
* No AST traversals — pure graph BFS.
*/
function expandTransitively(shared, depGraph) {
const queue = [...shared];
const visited = /* @__PURE__ */ new Set();
while (queue.length > 0) {
const name = queue.pop();
if (visited.has(name)) continue;
visited.add(name);
const deps = depGraph.get(name);
if (!deps) continue;
for (const dep of deps) if (!shared.has(dep)) {
shared.add(dep);
queue.push(dep);
}
}
}
/**
* Remove any bindings from `shared` that transitively depend on `Route`.
* The Route singleton must remain in the reference file; if a shared binding
* references it (directly or transitively), extracting that binding would
* duplicate Route in the shared module.
*
* Uses `depGraph` which must include `Route` as a node so the dependency
* chain is visible.
*/
function removeBindingsDependingOnRoute(shared, depGraph) {
const reverseGraph = /* @__PURE__ */ new Map();
for (const [name, deps] of depGraph) for (const dep of deps) {
let parents = reverseGraph.get(dep);
if (!parents) {
parents = /* @__PURE__ */ new Set();
reverseGraph.set(dep, parents);
}
parents.add(name);
}
const visited = /* @__PURE__ */ new Set();
const queue = ["Route"];
while (queue.length > 0) {
const cur = queue.pop();
if (visited.has(cur)) continue;
visited.add(cur);
const parents = reverseGraph.get(cur);
if (!parents) continue;
for (const parent of parents) if (!visited.has(parent)) queue.push(parent);
}
for (const name of [...shared]) if (visited.has(name)) shared.delete(name);
}
/**
* If any binding from a destructured declaration is shared,
* ensure all bindings from that same declaration are also shared.
* Pure node inspection of program.body, no traversal.
*/
function expandDestructuredDeclarations(ast, shared) {
for (const stmt of ast.program.body) {
const decl = t.isExportNamedDeclaration(stmt) && stmt.declaration ? stmt.declaration : stmt;
if (!t.isVariableDeclaration(decl)) continue;
for (const declarator of decl.declarations) {
if (!t.isObjectPattern(declarator.id) && !t.isArrayPattern(declarator.id)) continue;
const names = collectIdentifiersFromPattern(declarator.id);
if (names.some((n) => shared.has(n))) for (const n of names) shared.add(n);
}
}
}
/**
* Find which shared bindings are user-exported in the original source.

@@ -413,2 +242,12 @@ * These need to be re-exported from the shared module.

const insertionPath = path.getStatementParent() ?? path;
opts.compilerPlugins?.forEach((plugin) => {
if ((plugin.onRouteOptions?.({
programPath,
callExpressionPath: path,
insertionPath,
routeOptions,
createRouteFn,
opts
}))?.modified) modified = true;
});
if (opts.deleteNodes && opts.deleteNodes.size > 0) routeOptions.properties = routeOptions.properties.filter((prop) => {

@@ -689,10 +528,3 @@ if (t.isObjectProperty(prop)) {

deadCodeElimination(ast, refIdents);
{
const locallyBound = /* @__PURE__ */ new Set();
for (const stmt of ast.program.body) collectLocalBindingsFromStatement(stmt, locallyBound);
ast.program.body = ast.program.body.filter((stmt) => {
if (!t.isExpressionStatement(stmt)) return true;
return [...collectIdentifiersFromNode(stmt)].some((name) => locallyBound.has(name));
});
}
stripUnreferencedTopLevelExpressionStatements(ast);
if (ast.program.body.length === 0) ast.program.directives = [];

@@ -722,20 +554,4 @@ const result = generateFromAst(ast, {

expandTransitively(keepBindings, depGraph);
ast.program.body = ast.program.body.filter((stmt) => {
if (t.isImportDeclaration(stmt)) return true;
const decl = t.isExportNamedDeclaration(stmt) && stmt.declaration ? stmt.declaration : stmt;
if (t.isVariableDeclaration(decl)) {
decl.declarations = decl.declarations.filter((declarator) => {
return collectIdentifiersFromPattern(declarator.id).some((n) => keepBindings.has(n));
});
if (decl.declarations.length === 0) return false;
if (t.isExportNamedDeclaration(stmt) && stmt.declaration) return true;
return true;
} else if (t.isFunctionDeclaration(decl) && decl.id) return keepBindings.has(decl.id.name);
else if (t.isClassDeclaration(decl) && decl.id) return keepBindings.has(decl.id.name);
return false;
});
ast.program.body = ast.program.body.map((stmt) => {
if (t.isExportNamedDeclaration(stmt) && stmt.declaration) return stmt.declaration;
return stmt;
});
retainModuleLevelDeclarations(ast, keepBindings);
unwrapExportedDeclarations(ast);
const exportSpecifiers = [...opts.sharedBindings].sort((a, b) => a.localeCompare(b)).map((name) => t.exportSpecifier(t.identifier(name), t.identifier(name)));

@@ -824,19 +640,2 @@ if (exportSpecifiers.length > 0) {

}
/**
* Recursively collects all identifier names from a destructuring pattern
* (ObjectPattern, ArrayPattern, AssignmentPattern, RestElement).
*/
function collectIdentifiersFromPattern(node) {
if (!node) return [];
if (t.isIdentifier(node)) return [node.name];
if (t.isAssignmentPattern(node)) return collectIdentifiersFromPattern(node.left);
if (t.isRestElement(node)) return collectIdentifiersFromPattern(node.argument);
if (t.isObjectPattern(node)) return node.properties.flatMap((prop) => {
if (t.isObjectProperty(prop)) return collectIdentifiersFromPattern(prop.value);
if (t.isRestElement(prop)) return collectIdentifiersFromPattern(prop.argument);
return [];
});
if (t.isArrayPattern(node)) return node.elements.flatMap((element) => collectIdentifiersFromPattern(element));
return [];
}
function resolveIdentifier(path, node) {

@@ -843,0 +642,0 @@ if (t.isIdentifier(node)) {

@@ -41,2 +41,3 @@ import { default as babel } from '@babel/core';

getStableRouteOptionKeys?: () => Array<string>;
onRouteOptions?: (ctx: ReferenceRouteCompilerPluginContext) => void | ReferenceRouteCompilerPluginResult;
onAddHmr?: (ctx: ReferenceRouteCompilerPluginContext) => void | ReferenceRouteCompilerPluginResult;

@@ -43,0 +44,0 @@ onUnsplittableRoute?: (ctx: ReferenceRouteCompilerPluginContext) => void | ReferenceRouteCompilerPluginResult;

import { z } from 'zod';
import { CreateFileRoute, RegisteredRouter, RouteIds } from '@tanstack/router-core';
import { CodeSplitGroupings } from './constants.js';
export declare const splitGroupingsSchema: z.ZodEffects<z.ZodArray<z.ZodArray<z.ZodUnion<[z.ZodLiteral<"loader">, z.ZodLiteral<"component">, z.ZodLiteral<"pendingComponent">, z.ZodLiteral<"errorComponent">, z.ZodLiteral<"notFoundComponent">]>, "many">, "many">, ("loader" | "component" | "pendingComponent" | "errorComponent" | "notFoundComponent")[][], ("loader" | "component" | "pendingComponent" | "errorComponent" | "notFoundComponent")[][]>;
export declare const splitGroupingsSchema: z.ZodArray<z.ZodArray<z.ZodUnion<readonly [z.ZodLiteral<"loader">, z.ZodLiteral<"component">, z.ZodLiteral<"pendingComponent">, z.ZodLiteral<"errorComponent">, z.ZodLiteral<"notFoundComponent">]>>>;
export type CodeSplittingOptions = {

@@ -45,4 +45,8 @@ /**

export declare const configSchema: z.ZodObject<{
target: z.ZodDefault<z.ZodOptional<z.ZodEnum<["react", "solid", "vue"]>>>;
virtualRouteConfig: z.ZodOptional<z.ZodUnion<[z.ZodType<import('@tanstack/virtual-file-routes').VirtualRootRoute, z.ZodTypeDef, import('@tanstack/virtual-file-routes').VirtualRootRoute>, z.ZodString]>>;
target: z.ZodDefault<z.ZodOptional<z.ZodEnum<{
vue: "vue";
react: "react";
solid: "solid";
}>>>;
virtualRouteConfig: z.ZodOptional<z.ZodUnion<[z.ZodType<import('@tanstack/virtual-file-routes').VirtualRootRoute, unknown, z.core.$ZodTypeInternals<import('@tanstack/virtual-file-routes').VirtualRootRoute, unknown>>, z.ZodString]>>;
routeFilePrefix: z.ZodOptional<z.ZodString>;

@@ -52,33 +56,32 @@ routeFileIgnorePrefix: z.ZodDefault<z.ZodOptional<z.ZodString>>;

routesDirectory: z.ZodDefault<z.ZodOptional<z.ZodString>>;
quoteStyle: z.ZodDefault<z.ZodOptional<z.ZodEnum<["single", "double"]>>>;
quoteStyle: z.ZodDefault<z.ZodOptional<z.ZodEnum<{
single: "single";
double: "double";
}>>>;
semicolons: z.ZodDefault<z.ZodOptional<z.ZodBoolean>>;
disableLogging: z.ZodDefault<z.ZodOptional<z.ZodBoolean>>;
routeTreeFileHeader: z.ZodDefault<z.ZodOptional<z.ZodArray<z.ZodString, "many">>>;
indexToken: z.ZodDefault<z.ZodOptional<z.ZodUnion<[z.ZodString, z.ZodType<RegExp, z.ZodTypeDef, RegExp>, z.ZodObject<{
routeTreeFileHeader: z.ZodDefault<z.ZodOptional<z.ZodArray<z.ZodString>>>;
indexToken: z.ZodDefault<z.ZodOptional<z.ZodUnion<readonly [z.ZodString, z.ZodCustom<RegExp, RegExp>, z.ZodObject<{
regex: z.ZodString;
flags: z.ZodOptional<z.ZodString>;
}, "strip", z.ZodTypeAny, {
regex: string;
flags?: string | undefined;
}, {
regex: string;
flags?: string | undefined;
}>]>>>;
routeToken: z.ZodDefault<z.ZodOptional<z.ZodUnion<[z.ZodString, z.ZodType<RegExp, z.ZodTypeDef, RegExp>, z.ZodObject<{
}, z.core.$strip>]>>>;
routeToken: z.ZodDefault<z.ZodOptional<z.ZodUnion<readonly [z.ZodString, z.ZodCustom<RegExp, RegExp>, z.ZodObject<{
regex: z.ZodString;
flags: z.ZodOptional<z.ZodString>;
}, "strip", z.ZodTypeAny, {
regex: string;
flags?: string | undefined;
}, {
regex: string;
flags?: string | undefined;
}>]>>>;
pathParamsAllowedCharacters: z.ZodOptional<z.ZodArray<z.ZodEnum<[";", ":", "@", "&", "=", "+", "$", ","]>, "many">>;
} & {
}, z.core.$strip>]>>>;
pathParamsAllowedCharacters: z.ZodOptional<z.ZodArray<z.ZodEnum<{
":": ":";
$: "$";
";": ";";
"@": "@";
"&": "&";
"=": "=";
"+": "+";
",": ",";
}>>>;
generatedRouteTree: z.ZodDefault<z.ZodOptional<z.ZodString>>;
disableTypes: z.ZodDefault<z.ZodOptional<z.ZodBoolean>>;
addExtensions: z.ZodEffects<z.ZodDefault<z.ZodOptional<z.ZodUnion<[z.ZodBoolean, z.ZodString]>>>, string | boolean, string | boolean | undefined>;
addExtensions: z.ZodPipe<z.ZodDefault<z.ZodOptional<z.ZodUnion<readonly [z.ZodBoolean, z.ZodString]>>>, z.ZodTransform<string | boolean, string | boolean>>;
enableRouteTreeFormatting: z.ZodDefault<z.ZodOptional<z.ZodBoolean>>;
routeTreeFileFooter: z.ZodOptional<z.ZodUnion<[z.ZodDefault<z.ZodOptional<z.ZodArray<z.ZodString, "many">>>, z.ZodFunction<z.ZodTuple<[], z.ZodUnknown>, z.ZodArray<z.ZodString, "many">>]>>;
routeTreeFileFooter: z.ZodOptional<z.ZodUnion<readonly [z.ZodDefault<z.ZodOptional<z.ZodArray<z.ZodString>>>, z.ZodCustom<() => Array<string>, () => Array<string>>]>>;
autoCodeSplitting: z.ZodOptional<z.ZodBoolean>;

@@ -88,54 +91,25 @@ customScaffolding: z.ZodOptional<z.ZodObject<{

lazyRouteTemplate: z.ZodOptional<z.ZodString>;
}, "strip", z.ZodTypeAny, {
routeTemplate?: string | undefined;
lazyRouteTemplate?: string | undefined;
}, {
routeTemplate?: string | undefined;
lazyRouteTemplate?: string | undefined;
}>>;
}, z.core.$strip>>;
experimental: z.ZodOptional<z.ZodObject<{
enableCodeSplitting: z.ZodOptional<z.ZodBoolean>;
}, "strip", z.ZodTypeAny, {
enableCodeSplitting?: boolean | undefined;
}, {
enableCodeSplitting?: boolean | undefined;
}>>;
plugins: z.ZodOptional<z.ZodArray<z.ZodType<import('@tanstack/router-generator').GeneratorPlugin, z.ZodTypeDef, import('@tanstack/router-generator').GeneratorPlugin>, "many">>;
}, z.core.$strip>>;
plugins: z.ZodOptional<z.ZodArray<z.ZodCustom<import('@tanstack/router-generator').GeneratorPlugin, import('@tanstack/router-generator').GeneratorPlugin>>>;
tmpDir: z.ZodDefault<z.ZodOptional<z.ZodString>>;
importRoutesUsingAbsolutePaths: z.ZodDefault<z.ZodOptional<z.ZodBoolean>>;
} & {
enableRouteGeneration: z.ZodOptional<z.ZodBoolean>;
codeSplittingOptions: z.ZodOptional<z.ZodType<CodeSplittingOptions, z.ZodTypeDef, CodeSplittingOptions>>;
codeSplittingOptions: z.ZodOptional<z.ZodCustom<CodeSplittingOptions, CodeSplittingOptions>>;
plugin: z.ZodOptional<z.ZodObject<{
hmr: z.ZodOptional<z.ZodObject<{
style: z.ZodOptional<z.ZodEnum<["vite", "webpack"]>>;
}, "strip", z.ZodTypeAny, {
style?: "vite" | "webpack" | undefined;
}, {
style?: "vite" | "webpack" | undefined;
}>>;
style: z.ZodOptional<z.ZodEnum<{
vite: "vite";
webpack: "webpack";
}>>;
}, z.core.$strip>>;
vite: z.ZodOptional<z.ZodObject<{
environmentName: z.ZodOptional<z.ZodString>;
}, "strip", z.ZodTypeAny, {
environmentName?: string | undefined;
}, {
environmentName?: string | undefined;
}>>;
}, "strip", z.ZodTypeAny, {
vite?: {
environmentName?: string | undefined;
} | undefined;
hmr?: {
style?: "vite" | "webpack" | undefined;
} | undefined;
}, {
vite?: {
environmentName?: string | undefined;
} | undefined;
hmr?: {
style?: "vite" | "webpack" | undefined;
} | undefined;
}>>;
}, "strip", z.ZodTypeAny, {
target: "react" | "solid" | "vue";
}, z.core.$strip>>;
}, z.core.$strip>>;
}, z.core.$strip>;
export declare const getConfig: (inlineConfig: Partial<Config>, root: string) => {
target: "vue" | "react" | "solid";
routeFileIgnorePrefix: string;

@@ -161,17 +135,7 @@ routesDirectory: string;

importRoutesUsingAbsolutePaths: boolean;
enableRouteGeneration?: boolean | undefined;
codeSplittingOptions?: CodeSplittingOptions | undefined;
plugin?: {
vite?: {
environmentName?: string | undefined;
} | undefined;
hmr?: {
style?: "vite" | "webpack" | undefined;
} | undefined;
} | undefined;
virtualRouteConfig?: string | import('@tanstack/virtual-file-routes').VirtualRootRoute | undefined;
routeFilePrefix?: string | undefined;
routeFileIgnorePattern?: string | undefined;
pathParamsAllowedCharacters?: (";" | ":" | "@" | "&" | "=" | "+" | "$" | ",")[] | undefined;
routeTreeFileFooter?: string[] | ((...args: unknown[]) => string[]) | undefined;
pathParamsAllowedCharacters?: (":" | "$" | ";" | "@" | "&" | "=" | "+" | ",")[] | undefined;
routeTreeFileFooter?: string[] | (() => Array<string>) | undefined;
autoCodeSplitting?: boolean | undefined;

@@ -186,95 +150,12 @@ customScaffolding?: {

plugins?: import('@tanstack/router-generator').GeneratorPlugin[] | undefined;
}, {
enableRouteGeneration?: boolean | undefined;
codeSplittingOptions?: CodeSplittingOptions | undefined;
plugin?: {
vite?: {
environmentName?: string | undefined;
} | undefined;
hmr?: {
style?: "vite" | "webpack" | undefined;
} | undefined;
} | undefined;
target?: "react" | "solid" | "vue" | undefined;
virtualRouteConfig?: string | import('@tanstack/virtual-file-routes').VirtualRootRoute | undefined;
routeFilePrefix?: string | undefined;
routeFileIgnorePrefix?: string | undefined;
routeFileIgnorePattern?: string | undefined;
routesDirectory?: string | undefined;
quoteStyle?: "single" | "double" | undefined;
semicolons?: boolean | undefined;
disableLogging?: boolean | undefined;
routeTreeFileHeader?: string[] | undefined;
indexToken?: string | RegExp | {
regex: string;
flags?: string | undefined;
} | undefined;
routeToken?: string | RegExp | {
regex: string;
flags?: string | undefined;
} | undefined;
pathParamsAllowedCharacters?: (";" | ":" | "@" | "&" | "=" | "+" | "$" | ",")[] | undefined;
generatedRouteTree?: string | undefined;
disableTypes?: boolean | undefined;
addExtensions?: string | boolean | undefined;
enableRouteTreeFormatting?: boolean | undefined;
routeTreeFileFooter?: string[] | ((...args: unknown[]) => string[]) | undefined;
autoCodeSplitting?: boolean | undefined;
customScaffolding?: {
routeTemplate?: string | undefined;
lazyRouteTemplate?: string | undefined;
} | undefined;
experimental?: {
enableCodeSplitting?: boolean | undefined;
} | undefined;
plugins?: import('@tanstack/router-generator').GeneratorPlugin[] | undefined;
tmpDir?: string | undefined;
importRoutesUsingAbsolutePaths?: boolean | undefined;
}>;
export declare const getConfig: (inlineConfig: Partial<Config>, root: string) => {
target: "react" | "solid" | "vue";
routeFileIgnorePrefix: string;
routesDirectory: string;
quoteStyle: "single" | "double";
semicolons: boolean;
disableLogging: boolean;
routeTreeFileHeader: string[];
indexToken: string | RegExp | {
regex: string;
flags?: string | undefined;
};
routeToken: string | RegExp | {
regex: string;
flags?: string | undefined;
};
generatedRouteTree: string;
disableTypes: boolean;
addExtensions: string | boolean;
enableRouteTreeFormatting: boolean;
tmpDir: string;
importRoutesUsingAbsolutePaths: boolean;
enableRouteGeneration?: boolean | undefined;
codeSplittingOptions?: CodeSplittingOptions | undefined;
plugin?: {
vite?: {
environmentName?: string | undefined;
} | undefined;
hmr?: {
style?: "vite" | "webpack" | undefined;
} | undefined;
} | undefined;
virtualRouteConfig?: string | import('@tanstack/virtual-file-routes').VirtualRootRoute | undefined;
routeFilePrefix?: string | undefined;
routeFileIgnorePattern?: string | undefined;
pathParamsAllowedCharacters?: (";" | ":" | "@" | "&" | "=" | "+" | "$" | ",")[] | undefined;
routeTreeFileFooter?: string[] | ((...args: unknown[]) => string[]) | undefined;
autoCodeSplitting?: boolean | undefined;
customScaffolding?: {
routeTemplate?: string | undefined;
lazyRouteTemplate?: string | undefined;
} | undefined;
experimental?: {
enableCodeSplitting?: boolean | undefined;
} | undefined;
plugins?: import('@tanstack/router-generator').GeneratorPlugin[] | undefined;
};

@@ -281,0 +162,0 @@ export type Config = z.infer<typeof configSchema>;

@@ -18,3 +18,3 @@ import { z } from "zod";

var codeSplittingOptionsSchema = z.object({
splitBehavior: z.function().optional(),
splitBehavior: z.custom((value) => typeof value === "function").optional(),
defaultBehavior: splitGroupingsSchema.optional(),

@@ -21,0 +21,0 @@ deleteNodes: z.array(z.string()).optional(),

@@ -1,1 +0,1 @@

{"version":3,"file":"config.js","names":[],"sources":["../../../src/core/config.ts"],"sourcesContent":["import { z } from 'zod'\nimport {\n configSchema as generatorConfigSchema,\n getConfig as getGeneratorConfig,\n} from '@tanstack/router-generator'\nimport type {\n CreateFileRoute,\n RegisteredRouter,\n RouteIds,\n} from '@tanstack/router-core'\nimport type { CodeSplitGroupings } from './constants'\n\nexport const splitGroupingsSchema = z\n .array(\n z.array(\n z.union([\n z.literal('loader'),\n z.literal('component'),\n z.literal('pendingComponent'),\n z.literal('errorComponent'),\n z.literal('notFoundComponent'),\n ]),\n ),\n {\n message:\n \" Must be an Array of Arrays containing the split groupings. i.e. [['component'], ['pendingComponent'], ['errorComponent', 'notFoundComponent']]\",\n },\n )\n .superRefine((val, ctx) => {\n const flattened = val.flat()\n const unique = [...new Set(flattened)]\n\n // Elements must be unique,\n // ie. this shouldn't be allows [['component'], ['component', 'loader']]\n if (unique.length !== flattened.length) {\n ctx.addIssue({\n code: 'custom',\n message:\n \" Split groupings must be unique and not repeated. i.e. i.e. [['component'], ['pendingComponent'], ['errorComponent', 'notFoundComponent']].\" +\n `\\n You input was: ${JSON.stringify(val)}.`,\n })\n }\n })\n\nexport type CodeSplittingOptions = {\n /**\n * Use this function to programmatically control the code splitting behavior\n * based on the `routeId` for each route.\n *\n * If you just need to change the default behavior, you can use the `defaultBehavior` option.\n * @param params\n */\n splitBehavior?: (params: {\n routeId: RouteIds<RegisteredRouter['routeTree']>\n }) => CodeSplitGroupings | undefined | void\n\n /**\n * The default/global configuration to control your code splitting behavior per route.\n * @default [['component'],['pendingComponent'],['errorComponent'],['notFoundComponent']]\n */\n defaultBehavior?: CodeSplitGroupings\n\n /**\n * The nodes that shall be deleted from the route.\n * @default undefined\n */\n deleteNodes?: Array<DeletableNodes>\n\n /**\n * @default true\n */\n addHmr?: boolean\n}\n\nexport type HmrStyle = 'vite' | 'webpack'\n\nexport type HmrOptions = {\n /**\n * Selects the HMR runtime style to emit code for.\n * - `'vite'` (default): ESM `import.meta.hot` with Vite accept-callback semantics.\n * - `'webpack'`: `import.meta.webpackHot` with webpack / Rspack `module.hot` re-execution semantics.\n *\n * Bundler-specific plugin entries (e.g. `rspack.ts`, `webpack.ts`) set this explicitly.\n */\n style?: HmrStyle\n}\n\nconst codeSplittingOptionsSchema = z.object({\n splitBehavior: z.function().optional(),\n defaultBehavior: splitGroupingsSchema.optional(),\n deleteNodes: z.array(z.string()).optional(),\n addHmr: z.boolean().optional().default(true),\n})\n\ntype FileRouteKeys = keyof (Parameters<\n CreateFileRoute<any, any, any, any, any>\n>[0] & {})\nexport type DeletableNodes = FileRouteKeys | (string & {})\n\nexport const configSchema = generatorConfigSchema.extend({\n enableRouteGeneration: z.boolean().optional(),\n codeSplittingOptions: z\n .custom<CodeSplittingOptions>((v) => {\n return codeSplittingOptionsSchema.parse(v)\n })\n .optional(),\n plugin: z\n .object({\n hmr: z\n .object({\n style: z.enum(['vite', 'webpack']).optional(),\n })\n .optional(),\n vite: z\n .object({\n environmentName: z.string().optional(),\n })\n .optional(),\n })\n .optional(),\n})\n\nexport const getConfig = (inlineConfig: Partial<Config>, root: string) => {\n const config = getGeneratorConfig(inlineConfig, root)\n\n return configSchema.parse({ ...inlineConfig, ...config })\n}\n\nexport type Config = z.infer<typeof configSchema>\nexport type ConfigInput = z.input<typeof configSchema>\nexport type ConfigOutput = z.output<typeof configSchema>\n"],"mappings":";;;AAYA,IAAa,uBAAuB,EACjC,MACC,EAAE,MACA,EAAE,MAAM;CACN,EAAE,QAAQ,SAAS;CACnB,EAAE,QAAQ,YAAY;CACtB,EAAE,QAAQ,mBAAmB;CAC7B,EAAE,QAAQ,iBAAiB;CAC3B,EAAE,QAAQ,oBAAoB;CAC/B,CAAC,CACH,EACD,EACE,SACE,oJACH,CACF,CACA,aAAa,KAAK,QAAQ;CACzB,MAAM,YAAY,IAAI,MAAM;AAK5B,KAJe,CAAC,GAAG,IAAI,IAAI,UAAU,CAAC,CAI3B,WAAW,UAAU,OAC9B,KAAI,SAAS;EACX,MAAM;EACN,SACE,kKACsB,KAAK,UAAU,IAAI,CAAC;EAC7C,CAAC;EAEJ;AA6CJ,IAAM,6BAA6B,EAAE,OAAO;CAC1C,eAAe,EAAE,UAAU,CAAC,UAAU;CACtC,iBAAiB,qBAAqB,UAAU;CAChD,aAAa,EAAE,MAAM,EAAE,QAAQ,CAAC,CAAC,UAAU;CAC3C,QAAQ,EAAE,SAAS,CAAC,UAAU,CAAC,QAAQ,KAAK;CAC7C,CAAC;AAOF,IAAa,iBAAe,aAAsB,OAAO;CACvD,uBAAuB,EAAE,SAAS,CAAC,UAAU;CAC7C,sBAAsB,EACnB,QAA8B,MAAM;AACnC,SAAO,2BAA2B,MAAM,EAAE;GAC1C,CACD,UAAU;CACb,QAAQ,EACL,OAAO;EACN,KAAK,EACF,OAAO,EACN,OAAO,EAAE,KAAK,CAAC,QAAQ,UAAU,CAAC,CAAC,UAAU,EAC9C,CAAC,CACD,UAAU;EACb,MAAM,EACH,OAAO,EACN,iBAAiB,EAAE,QAAQ,CAAC,UAAU,EACvC,CAAC,CACD,UAAU;EACd,CAAC,CACD,UAAU;CACd,CAAC;AAEF,IAAa,eAAa,cAA+B,SAAiB;CACxE,MAAM,SAAS,UAAmB,cAAc,KAAK;AAErD,QAAO,eAAa,MAAM;EAAE,GAAG;EAAc,GAAG;EAAQ,CAAC"}
{"version":3,"file":"config.js","names":[],"sources":["../../../src/core/config.ts"],"sourcesContent":["import { z } from 'zod'\nimport {\n configSchema as generatorConfigSchema,\n getConfig as getGeneratorConfig,\n} from '@tanstack/router-generator'\nimport type {\n CreateFileRoute,\n RegisteredRouter,\n RouteIds,\n} from '@tanstack/router-core'\nimport type { CodeSplitGroupings } from './constants'\nimport type { ReferenceRouteCompilerPlugin } from './code-splitter/plugins'\n\nexport const splitGroupingsSchema = z\n .array(\n z.array(\n z.union([\n z.literal('loader'),\n z.literal('component'),\n z.literal('pendingComponent'),\n z.literal('errorComponent'),\n z.literal('notFoundComponent'),\n ]),\n ),\n {\n message:\n \" Must be an Array of Arrays containing the split groupings. i.e. [['component'], ['pendingComponent'], ['errorComponent', 'notFoundComponent']]\",\n },\n )\n .superRefine((val, ctx) => {\n const flattened = val.flat()\n const unique = [...new Set(flattened)]\n\n // Elements must be unique,\n // ie. this shouldn't be allows [['component'], ['component', 'loader']]\n if (unique.length !== flattened.length) {\n ctx.addIssue({\n code: 'custom',\n message:\n \" Split groupings must be unique and not repeated. i.e. i.e. [['component'], ['pendingComponent'], ['errorComponent', 'notFoundComponent']].\" +\n `\\n You input was: ${JSON.stringify(val)}.`,\n })\n }\n })\n\nexport type CodeSplittingOptions = {\n /**\n * Use this function to programmatically control the code splitting behavior\n * based on the `routeId` for each route.\n *\n * If you just need to change the default behavior, you can use the `defaultBehavior` option.\n * @param params\n */\n splitBehavior?: (params: {\n routeId: RouteIds<RegisteredRouter['routeTree']>\n }) => CodeSplitGroupings | undefined | void\n\n /**\n * The default/global configuration to control your code splitting behavior per route.\n * @default [['component'],['pendingComponent'],['errorComponent'],['notFoundComponent']]\n */\n defaultBehavior?: CodeSplitGroupings\n\n /**\n * The nodes that shall be deleted from the route.\n * @default undefined\n */\n deleteNodes?: Array<DeletableNodes>\n\n /**\n * @default true\n */\n addHmr?: boolean\n\n /**\n * Internal compiler plugins used by framework integrations.\n * @internal\n */\n compilerPlugins?: Array<ReferenceRouteCompilerPlugin>\n}\n\nexport type HmrStyle = 'vite' | 'webpack'\n\nexport type HmrOptions = {\n /**\n * Selects the HMR runtime style to emit code for.\n * - `'vite'` (default): ESM `import.meta.hot` with Vite accept-callback semantics.\n * - `'webpack'`: `import.meta.webpackHot` with webpack / Rspack `module.hot` re-execution semantics.\n *\n * Bundler-specific plugin entries (e.g. `rspack.ts`, `webpack.ts`) set this explicitly.\n */\n style?: HmrStyle\n}\n\nconst codeSplittingOptionsSchema = z.object({\n splitBehavior: z\n .custom<\n CodeSplittingOptions['splitBehavior']\n >((value) => typeof value === 'function')\n .optional(),\n defaultBehavior: splitGroupingsSchema.optional(),\n deleteNodes: z.array(z.string()).optional(),\n addHmr: z.boolean().optional().default(true),\n})\n\ntype FileRouteKeys = keyof (Parameters<\n CreateFileRoute<any, any, any, any, any>\n>[0] & {})\nexport type DeletableNodes = FileRouteKeys | (string & {})\n\nexport const configSchema = generatorConfigSchema.extend({\n enableRouteGeneration: z.boolean().optional(),\n codeSplittingOptions: z\n .custom<CodeSplittingOptions>((v) => {\n return codeSplittingOptionsSchema.parse(v)\n })\n .optional(),\n plugin: z\n .object({\n hmr: z\n .object({\n style: z.enum(['vite', 'webpack']).optional(),\n })\n .optional(),\n vite: z\n .object({\n environmentName: z.string().optional(),\n })\n .optional(),\n })\n .optional(),\n})\n\nexport const getConfig = (inlineConfig: Partial<Config>, root: string) => {\n const config = getGeneratorConfig(inlineConfig, root)\n\n return configSchema.parse({ ...inlineConfig, ...config })\n}\n\nexport type Config = z.infer<typeof configSchema>\nexport type ConfigInput = z.input<typeof configSchema>\nexport type ConfigOutput = z.output<typeof configSchema>\n"],"mappings":";;;AAaA,IAAa,uBAAuB,EACjC,MACC,EAAE,MACA,EAAE,MAAM;CACN,EAAE,QAAQ,SAAS;CACnB,EAAE,QAAQ,YAAY;CACtB,EAAE,QAAQ,mBAAmB;CAC7B,EAAE,QAAQ,iBAAiB;CAC3B,EAAE,QAAQ,oBAAoB;CAC/B,CAAC,CACH,EACD,EACE,SACE,oJACH,CACF,CACA,aAAa,KAAK,QAAQ;CACzB,MAAM,YAAY,IAAI,MAAM;AAK5B,KAJe,CAAC,GAAG,IAAI,IAAI,UAAU,CAAC,CAI3B,WAAW,UAAU,OAC9B,KAAI,SAAS;EACX,MAAM;EACN,SACE,kKACsB,KAAK,UAAU,IAAI,CAAC;EAC7C,CAAC;EAEJ;AAmDJ,IAAM,6BAA6B,EAAE,OAAO;CAC1C,eAAe,EACZ,QAEE,UAAU,OAAO,UAAU,WAAW,CACxC,UAAU;CACb,iBAAiB,qBAAqB,UAAU;CAChD,aAAa,EAAE,MAAM,EAAE,QAAQ,CAAC,CAAC,UAAU;CAC3C,QAAQ,EAAE,SAAS,CAAC,UAAU,CAAC,QAAQ,KAAK;CAC7C,CAAC;AAOF,IAAa,iBAAe,aAAsB,OAAO;CACvD,uBAAuB,EAAE,SAAS,CAAC,UAAU;CAC7C,sBAAsB,EACnB,QAA8B,MAAM;AACnC,SAAO,2BAA2B,MAAM,EAAE;GAC1C,CACD,UAAU;CACb,QAAQ,EACL,OAAO;EACN,KAAK,EACF,OAAO,EACN,OAAO,EAAE,KAAK,CAAC,QAAQ,UAAU,CAAC,CAAC,UAAU,EAC9C,CAAC,CACD,UAAU;EACb,MAAM,EACH,OAAO,EACN,iBAAiB,EAAE,QAAQ,CAAC,UAAU,EACvC,CAAC,CACD,UAAU;EACd,CAAC,CACD,UAAU;CACd,CAAC;AAEF,IAAa,eAAa,cAA+B,SAAiB;CACxE,MAAM,SAAS,UAAmB,cAAc,KAAK;AAErD,QAAO,eAAa,MAAM;EAAE,GAAG;EAAc,GAAG;EAAQ,CAAC"}
import { getConfig, splitGroupingsSchema } from "./config.js";
import { defaultCodeSplitGroupings, splitRouteIdentNodes, tsrShared, tsrSplit } from "./constants.js";
import { debug, normalizePath, routeFactoryCallCodeFilter } from "./utils.js";
import { decodeIdentifier } from "./code-splitter/path-ids.js";
import { compileCodeSplitReferenceRoute, compileCodeSplitSharedRoute, compileCodeSplitVirtualRoute, computeSharedBindings, detectCodeSplitGroupingsFromRoute } from "./code-splitter/compilers.js";

@@ -9,3 +8,3 @@ import { getReferenceRouteCompilerPlugins } from "./code-splitter/plugins/framework-plugins.js";

import { fileURLToPath, pathToFileURL } from "node:url";
import { logDiff } from "@tanstack/router-utils";
import { decodeIdentifier, logDiff } from "@tanstack/router-utils";
//#region src/core/router-code-splitter-plugin.ts

@@ -69,3 +68,3 @@ /**

if (!res.success) {
const message = res.error.errors.map((e) => e.message).join(". ");
const message = res.error.issues.map((e) => e.message).join(". ");
throw new Error(`The groupings for the route "${id}" are invalid.\n${message}`);

@@ -78,3 +77,3 @@ }

if (!res.success) {
const message = res.error.errors.map((e) => e.message).join(". ");
const message = res.error.issues.map((e) => e.message).join(". ");
throw new Error(`The groupings returned when using \`splitBehavior\` for the route "${id}" are invalid.\n${message}`);

@@ -104,7 +103,7 @@ }

sharedBindings: sharedBindings.size > 0 ? sharedBindings : void 0,
compilerPlugins: getReferenceRouteCompilerPlugins({
compilerPlugins: [...getReferenceRouteCompilerPlugins({
targetFramework: userConfig.target,
addHmr,
hmrStyle
})
}) ?? [], ...userConfig.codeSplittingOptions?.compilerPlugins ?? []]
});

@@ -111,0 +110,0 @@ if (compiledReferenceRoute === null) {

@@ -1,1 +0,1 @@

{"version":3,"file":"router-code-splitter-plugin.js","names":[],"sources":["../../../src/core/router-code-splitter-plugin.ts"],"sourcesContent":["/**\n * It is important to familiarize yourself with how the code-splitting works in this plugin.\n * https://github.com/TanStack/router/pull/3355\n */\n\nimport { fileURLToPath, pathToFileURL } from 'node:url'\nimport { logDiff } from '@tanstack/router-utils'\nimport { getConfig, splitGroupingsSchema } from './config'\nimport {\n compileCodeSplitReferenceRoute,\n compileCodeSplitSharedRoute,\n compileCodeSplitVirtualRoute,\n computeSharedBindings,\n detectCodeSplitGroupingsFromRoute,\n} from './code-splitter/compilers'\nimport { getReferenceRouteCompilerPlugins } from './code-splitter/plugins/framework-plugins'\nimport {\n defaultCodeSplitGroupings,\n splitRouteIdentNodes,\n tsrShared,\n tsrSplit,\n} from './constants'\nimport { decodeIdentifier } from './code-splitter/path-ids'\nimport { debug, normalizePath, routeFactoryCallCodeFilter } from './utils'\nimport { createRouterPluginContext } from './router-plugin-context'\nimport type { CodeSplitGroupings, SplitRouteIdentNodes } from './constants'\nimport type { GetRoutesByFileMapResultValue } from '@tanstack/router-generator'\nimport type { Config } from './config'\nimport type { RouterPluginContext } from './router-plugin-context'\nimport type {\n UnpluginFactory,\n TransformResult as UnpluginTransformResult,\n} from 'unplugin'\n\nconst CODE_SPLITTER_PLUGIN_NAME =\n 'tanstack-router:code-splitter:compile-reference-file'\n\ntype TransformationPluginInfo = {\n pluginNames: Array<string>\n pkg: string\n usage: string\n}\n\n/**\n * JSX transformation plugins grouped by framework.\n * These plugins must come AFTER the TanStack Router plugin in the Vite config.\n */\nconst TRANSFORMATION_PLUGINS_BY_FRAMEWORK: Record<\n string,\n Array<TransformationPluginInfo>\n> = {\n react: [\n {\n // Babel-based React plugin\n pluginNames: ['vite:react-babel', 'vite:react-refresh'],\n pkg: '@vitejs/plugin-react',\n usage: 'react()',\n },\n {\n // SWC-based React plugin\n pluginNames: ['vite:react-swc', 'vite:react-swc:resolve-runtime'],\n pkg: '@vitejs/plugin-react-swc',\n usage: 'reactSwc()',\n },\n {\n // OXC-based React plugin (deprecated but should still be handled)\n pluginNames: ['vite:react-oxc:config', 'vite:react-oxc:refresh-runtime'],\n pkg: '@vitejs/plugin-react-oxc',\n usage: 'reactOxc()',\n },\n ],\n solid: [\n {\n pluginNames: ['solid'],\n pkg: 'vite-plugin-solid',\n usage: 'solid()',\n },\n ],\n}\n\nexport function createRouterCodeSplitterPlugin(\n options: Partial<Config | (() => Config)> | undefined = {},\n routerPluginContext: RouterPluginContext,\n): ReturnType<UnpluginFactory<Partial<Config | (() => Config)> | undefined>> {\n let ROOT: string = process.cwd()\n let userConfig: Config\n\n function initUserConfig() {\n if (typeof options === 'function') {\n userConfig = options()\n } else {\n userConfig = getConfig(options, ROOT)\n }\n }\n const isProduction = process.env.NODE_ENV === 'production'\n // Map from normalized route file path → set of shared binding names.\n // Populated by the reference compiler, consumed by virtual and shared compilers.\n const sharedBindingsMap = new Map<string, Set<string>>()\n\n const getGlobalCodeSplitGroupings = () => {\n return (\n userConfig.codeSplittingOptions?.defaultBehavior ||\n defaultCodeSplitGroupings\n )\n }\n const getShouldSplitFn = () => {\n return userConfig.codeSplittingOptions?.splitBehavior\n }\n\n const handleCompilingReferenceFile = (\n code: string,\n id: string,\n generatorNodeInfo: GetRoutesByFileMapResultValue,\n ): UnpluginTransformResult => {\n if (debug) console.info('Compiling Route: ', id)\n\n const fromCode = detectCodeSplitGroupingsFromRoute({\n code,\n filename: id,\n })\n\n if (fromCode.groupings !== undefined) {\n const res = splitGroupingsSchema.safeParse(fromCode.groupings)\n if (!res.success) {\n const message = res.error.errors.map((e) => e.message).join('. ')\n throw new Error(\n `The groupings for the route \"${id}\" are invalid.\\n${message}`,\n )\n }\n }\n\n const userShouldSplitFn = getShouldSplitFn()\n\n const pluginSplitBehavior = userShouldSplitFn?.({\n routeId: generatorNodeInfo.routeId,\n }) as CodeSplitGroupings | undefined\n\n if (pluginSplitBehavior) {\n const res = splitGroupingsSchema.safeParse(pluginSplitBehavior)\n if (!res.success) {\n const message = res.error.errors.map((e) => e.message).join('. ')\n throw new Error(\n `The groupings returned when using \\`splitBehavior\\` for the route \"${id}\" are invalid.\\n${message}`,\n )\n }\n }\n\n const splitGroupings: CodeSplitGroupings =\n fromCode.groupings ?? pluginSplitBehavior ?? getGlobalCodeSplitGroupings()\n\n // Compute shared bindings before compiling the reference route\n const sharedBindings = computeSharedBindings({\n code,\n filename: id,\n codeSplitGroupings: splitGroupings,\n })\n if (sharedBindings.size > 0) {\n sharedBindingsMap.set(id, sharedBindings)\n } else {\n sharedBindingsMap.delete(id)\n }\n\n const addHmr =\n (userConfig.codeSplittingOptions?.addHmr ?? true) && !isProduction\n const hmrStyle = userConfig.plugin?.hmr?.style ?? 'vite'\n\n const compiledReferenceRoute = compileCodeSplitReferenceRoute({\n code,\n codeSplitGroupings: splitGroupings,\n targetFramework: userConfig.target,\n filename: id,\n id,\n deleteNodes: userConfig.codeSplittingOptions?.deleteNodes\n ? new Set(userConfig.codeSplittingOptions.deleteNodes)\n : undefined,\n addHmr,\n hmrStyle,\n hmrRouteId: generatorNodeInfo.routeId,\n sharedBindings: sharedBindings.size > 0 ? sharedBindings : undefined,\n compilerPlugins: getReferenceRouteCompilerPlugins({\n targetFramework: userConfig.target,\n addHmr,\n hmrStyle,\n }),\n })\n\n if (compiledReferenceRoute === null) {\n if (debug) {\n console.info(\n `No changes made to route \"${id}\", skipping code-splitting.`,\n )\n }\n return null\n }\n if (debug) {\n logDiff(code, compiledReferenceRoute.code)\n console.log('Output:\\n', compiledReferenceRoute.code + '\\n\\n')\n }\n\n return compiledReferenceRoute\n }\n\n const handleCompilingVirtualFile = (\n code: string,\n id: string,\n ): UnpluginTransformResult => {\n if (debug) console.info('Splitting Route: ', id)\n\n const [_, ...pathnameParts] = id.split('?')\n\n const searchParams = new URLSearchParams(pathnameParts.join('?'))\n const splitValue = searchParams.get(tsrSplit)\n\n if (!splitValue) {\n throw new Error(\n `The split value for the virtual route \"${id}\" was not found.`,\n )\n }\n\n const rawGrouping = decodeIdentifier(splitValue)\n const grouping = [...new Set(rawGrouping)].filter((p) =>\n splitRouteIdentNodes.includes(p as any),\n ) as Array<SplitRouteIdentNodes>\n\n const baseId = id.split('?')[0]!\n const resolvedSharedBindings = sharedBindingsMap.get(baseId)\n\n const result = compileCodeSplitVirtualRoute({\n code,\n filename: id,\n splitTargets: grouping,\n sharedBindings: resolvedSharedBindings,\n })\n\n if (debug) {\n logDiff(code, result.code)\n console.log('Output:\\n', result.code + '\\n\\n')\n }\n\n return result\n }\n\n return [\n {\n name: 'tanstack-router:code-splitter:compile-reference-file',\n enforce: 'pre',\n\n transform: {\n filter: {\n id: {\n exclude: [tsrSplit, tsrShared],\n // this is necessary for webpack / rspack to avoid matching .html files\n include: /\\.(m|c)?(j|t)sx?$/,\n },\n code: {\n include: routeFactoryCallCodeFilter,\n },\n },\n handler(code, id) {\n const normalizedId = normalizePath(id)\n const generatorFileInfo =\n routerPluginContext.routesByFile.get(normalizedId)\n if (generatorFileInfo) {\n return handleCompilingReferenceFile(\n code,\n normalizedId,\n generatorFileInfo,\n )\n }\n\n return null\n },\n },\n\n vite: {\n configResolved(config) {\n ROOT = config.root\n initUserConfig()\n\n // Validate plugin order - router must come before JSX transformation plugins\n const routerPluginIndex = config.plugins.findIndex(\n (p) => p.name === CODE_SPLITTER_PLUGIN_NAME,\n )\n\n if (routerPluginIndex === -1) return\n\n const frameworkPlugins =\n TRANSFORMATION_PLUGINS_BY_FRAMEWORK[userConfig.target]\n if (!frameworkPlugins) return\n\n for (const transformPlugin of frameworkPlugins) {\n const transformPluginIndex = config.plugins.findIndex((p) =>\n transformPlugin.pluginNames.includes(p.name),\n )\n\n if (\n transformPluginIndex !== -1 &&\n transformPluginIndex < routerPluginIndex\n ) {\n throw new Error(\n `Plugin order error: '${transformPlugin.pkg}' is placed before '@tanstack/router-plugin'.\\n\\n` +\n `The TanStack Router plugin must come BEFORE JSX transformation plugins.\\n\\n` +\n `Please update your Vite config:\\n\\n` +\n ` plugins: [\\n` +\n ` tanstackRouter(),\\n` +\n ` ${transformPlugin.usage},\\n` +\n ` ]\\n`,\n )\n }\n }\n },\n applyToEnvironment(environment) {\n if (userConfig.plugin?.vite?.environmentName) {\n return userConfig.plugin.vite.environmentName === environment.name\n }\n return true\n },\n },\n\n rspack() {\n ROOT = process.cwd()\n initUserConfig()\n },\n\n webpack() {\n ROOT = process.cwd()\n initUserConfig()\n },\n },\n {\n name: 'tanstack-router:code-splitter:compile-virtual-file',\n enforce: 'pre',\n\n transform: {\n filter: {\n id: /tsr-split/,\n },\n handler(code, id) {\n const url = pathToFileURL(id)\n url.searchParams.delete('v')\n const normalizedId = normalizePath(fileURLToPath(url))\n return handleCompilingVirtualFile(code, normalizedId)\n },\n },\n\n vite: {\n applyToEnvironment(environment) {\n if (userConfig.plugin?.vite?.environmentName) {\n return userConfig.plugin.vite.environmentName === environment.name\n }\n return true\n },\n },\n },\n {\n name: 'tanstack-router:code-splitter:compile-shared-file',\n enforce: 'pre',\n\n transform: {\n filter: {\n id: /tsr-shared/,\n },\n handler(code, id) {\n const url = pathToFileURL(id)\n url.searchParams.delete('v')\n const normalizedId = normalizePath(fileURLToPath(url))\n const [baseId] = normalizedId.split('?')\n\n if (!baseId) return null\n\n const sharedBindings = sharedBindingsMap.get(baseId)\n if (!sharedBindings || sharedBindings.size === 0) return null\n\n if (debug) console.info('Compiling Shared Module: ', id)\n\n const result = compileCodeSplitSharedRoute({\n code,\n sharedBindings,\n filename: normalizedId,\n })\n\n if (debug) {\n logDiff(code, result.code)\n console.log('Output:\\n', result.code + '\\n\\n')\n }\n\n return result\n },\n },\n\n vite: {\n applyToEnvironment(environment) {\n if (userConfig.plugin?.vite?.environmentName) {\n return userConfig.plugin.vite.environmentName === environment.name\n }\n return true\n },\n },\n },\n ]\n}\n\nexport const unpluginRouterCodeSplitterFactory: UnpluginFactory<\n Partial<Config | (() => Config)> | undefined\n> = (options = {}) => {\n return createRouterCodeSplitterPlugin(options, createRouterPluginContext())\n}\n"],"mappings":";;;;;;;;;;;;;;AAkCA,IAAM,4BACJ;;;;;AAYF,IAAM,sCAGF;CACF,OAAO;EACL;GAEE,aAAa,CAAC,oBAAoB,qBAAqB;GACvD,KAAK;GACL,OAAO;GACR;EACD;GAEE,aAAa,CAAC,kBAAkB,iCAAiC;GACjE,KAAK;GACL,OAAO;GACR;EACD;GAEE,aAAa,CAAC,yBAAyB,iCAAiC;GACxE,KAAK;GACL,OAAO;GACR;EACF;CACD,OAAO,CACL;EACE,aAAa,CAAC,QAAQ;EACtB,KAAK;EACL,OAAO;EACR,CACF;CACF;AAED,SAAgB,+BACd,UAAwD,EAAE,EAC1D,qBAC2E;CAC3E,IAAI,OAAe,QAAQ,KAAK;CAChC,IAAI;CAEJ,SAAS,iBAAiB;AACxB,MAAI,OAAO,YAAY,WACrB,cAAa,SAAS;MAEtB,cAAa,UAAU,SAAS,KAAK;;CAGzC,MAAM,eAAA,QAAA,IAAA,aAAwC;CAG9C,MAAM,oCAAoB,IAAI,KAA0B;CAExD,MAAM,oCAAoC;AACxC,SACE,WAAW,sBAAsB,mBACjC;;CAGJ,MAAM,yBAAyB;AAC7B,SAAO,WAAW,sBAAsB;;CAG1C,MAAM,gCACJ,MACA,IACA,sBAC4B;AAC5B,MAAI,MAAO,SAAQ,KAAK,qBAAqB,GAAG;EAEhD,MAAM,WAAW,kCAAkC;GACjD;GACA,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ACpD,SAAI,CAAC,kBAAkB,eAAe,SAAS,EAAG,QAAO;AAEzD,SAAI,MAAO,SAAQ,KAAK,6BAA6B,GAAG;KAExD,MAAM,SAAS,4BAA4B;MACzC;MACA;MACA,UAAU;MACX,CAAC;AAEF,SAAI,OAAO;AACT,cAAQ,MAAM,OAAO,KAAK;AAC1B,cAAQ,IAAI,aAAa,OAAO,OAAO,OAAO;;AAGhD,YAAO;;IAEV;GAED,MAAM,EACJ,mBAAmB,aAAa;AAC9B,QAAI,WAAW,QAAQ,MAAM,gBAC3B,QAAO,WAAW,OAAO,KAAK,oBAAoB,YAAY;AAEhE,WAAO;MAEV;GACF;EACF;;AAGH,IAAa,qCAER,UAAU,EAAE,KAAK;AACpB,QAAO,+BAA+B,SAAS,2BAA2B,CAAC"}
{"version":3,"file":"router-code-splitter-plugin.js","names":[],"sources":["../../../src/core/router-code-splitter-plugin.ts"],"sourcesContent":["/**\n * It is important to familiarize yourself with how the code-splitting works in this plugin.\n * https://github.com/TanStack/router/pull/3355\n */\n\nimport { fileURLToPath, pathToFileURL } from 'node:url'\nimport { decodeIdentifier, logDiff } from '@tanstack/router-utils'\nimport { getConfig, splitGroupingsSchema } from './config'\nimport {\n compileCodeSplitReferenceRoute,\n compileCodeSplitSharedRoute,\n compileCodeSplitVirtualRoute,\n computeSharedBindings,\n detectCodeSplitGroupingsFromRoute,\n} from './code-splitter/compilers'\nimport { getReferenceRouteCompilerPlugins } from './code-splitter/plugins/framework-plugins'\nimport {\n defaultCodeSplitGroupings,\n splitRouteIdentNodes,\n tsrShared,\n tsrSplit,\n} from './constants'\nimport { debug, normalizePath, routeFactoryCallCodeFilter } from './utils'\nimport { createRouterPluginContext } from './router-plugin-context'\nimport type { CodeSplitGroupings, SplitRouteIdentNodes } from './constants'\nimport type { GetRoutesByFileMapResultValue } from '@tanstack/router-generator'\nimport type { Config } from './config'\nimport type { RouterPluginContext } from './router-plugin-context'\nimport type {\n UnpluginFactory,\n TransformResult as UnpluginTransformResult,\n} from 'unplugin'\n\nconst CODE_SPLITTER_PLUGIN_NAME =\n 'tanstack-router:code-splitter:compile-reference-file'\n\ntype TransformationPluginInfo = {\n pluginNames: Array<string>\n pkg: string\n usage: string\n}\n\n/**\n * JSX transformation plugins grouped by framework.\n * These plugins must come AFTER the TanStack Router plugin in the Vite config.\n */\nconst TRANSFORMATION_PLUGINS_BY_FRAMEWORK: Record<\n string,\n Array<TransformationPluginInfo>\n> = {\n react: [\n {\n // Babel-based React plugin\n pluginNames: ['vite:react-babel', 'vite:react-refresh'],\n pkg: '@vitejs/plugin-react',\n usage: 'react()',\n },\n {\n // SWC-based React plugin\n pluginNames: ['vite:react-swc', 'vite:react-swc:resolve-runtime'],\n pkg: '@vitejs/plugin-react-swc',\n usage: 'reactSwc()',\n },\n {\n // OXC-based React plugin (deprecated but should still be handled)\n pluginNames: ['vite:react-oxc:config', 'vite:react-oxc:refresh-runtime'],\n pkg: '@vitejs/plugin-react-oxc',\n usage: 'reactOxc()',\n },\n ],\n solid: [\n {\n pluginNames: ['solid'],\n pkg: 'vite-plugin-solid',\n usage: 'solid()',\n },\n ],\n}\n\nexport function createRouterCodeSplitterPlugin(\n options: Partial<Config | (() => Config)> | undefined = {},\n routerPluginContext: RouterPluginContext,\n): ReturnType<UnpluginFactory<Partial<Config | (() => Config)> | undefined>> {\n let ROOT: string = process.cwd()\n let userConfig: Config\n\n function initUserConfig() {\n if (typeof options === 'function') {\n userConfig = options()\n } else {\n userConfig = getConfig(options, ROOT)\n }\n }\n const isProduction = process.env.NODE_ENV === 'production'\n // Map from normalized route file path → set of shared binding names.\n // Populated by the reference compiler, consumed by virtual and shared compilers.\n const sharedBindingsMap = new Map<string, Set<string>>()\n\n const getGlobalCodeSplitGroupings = () => {\n return (\n userConfig.codeSplittingOptions?.defaultBehavior ||\n defaultCodeSplitGroupings\n )\n }\n const getShouldSplitFn = () => {\n return userConfig.codeSplittingOptions?.splitBehavior\n }\n\n const handleCompilingReferenceFile = (\n code: string,\n id: string,\n generatorNodeInfo: GetRoutesByFileMapResultValue,\n ): UnpluginTransformResult => {\n if (debug) console.info('Compiling Route: ', id)\n\n const fromCode = detectCodeSplitGroupingsFromRoute({\n code,\n filename: id,\n })\n\n if (fromCode.groupings !== undefined) {\n const res = splitGroupingsSchema.safeParse(fromCode.groupings)\n if (!res.success) {\n const message = res.error.issues.map((e) => e.message).join('. ')\n throw new Error(\n `The groupings for the route \"${id}\" are invalid.\\n${message}`,\n )\n }\n }\n\n const userShouldSplitFn = getShouldSplitFn()\n\n const pluginSplitBehavior = userShouldSplitFn?.({\n routeId: generatorNodeInfo.routeId,\n }) as CodeSplitGroupings | undefined\n\n if (pluginSplitBehavior) {\n const res = splitGroupingsSchema.safeParse(pluginSplitBehavior)\n if (!res.success) {\n const message = res.error.issues.map((e) => e.message).join('. ')\n throw new Error(\n `The groupings returned when using \\`splitBehavior\\` for the route \"${id}\" are invalid.\\n${message}`,\n )\n }\n }\n\n const splitGroupings: CodeSplitGroupings =\n fromCode.groupings ?? pluginSplitBehavior ?? getGlobalCodeSplitGroupings()\n\n // Compute shared bindings before compiling the reference route\n const sharedBindings = computeSharedBindings({\n code,\n filename: id,\n codeSplitGroupings: splitGroupings,\n })\n if (sharedBindings.size > 0) {\n sharedBindingsMap.set(id, sharedBindings)\n } else {\n sharedBindingsMap.delete(id)\n }\n\n const addHmr =\n (userConfig.codeSplittingOptions?.addHmr ?? true) && !isProduction\n const hmrStyle = userConfig.plugin?.hmr?.style ?? 'vite'\n\n const compiledReferenceRoute = compileCodeSplitReferenceRoute({\n code,\n codeSplitGroupings: splitGroupings,\n targetFramework: userConfig.target,\n filename: id,\n id,\n deleteNodes: userConfig.codeSplittingOptions?.deleteNodes\n ? new Set(userConfig.codeSplittingOptions.deleteNodes)\n : undefined,\n addHmr,\n hmrStyle,\n hmrRouteId: generatorNodeInfo.routeId,\n sharedBindings: sharedBindings.size > 0 ? sharedBindings : undefined,\n compilerPlugins: [\n ...(getReferenceRouteCompilerPlugins({\n targetFramework: userConfig.target,\n addHmr,\n hmrStyle,\n }) ?? []),\n ...(userConfig.codeSplittingOptions?.compilerPlugins ?? []),\n ],\n })\n\n if (compiledReferenceRoute === null) {\n if (debug) {\n console.info(\n `No changes made to route \"${id}\", skipping code-splitting.`,\n )\n }\n return null\n }\n if (debug) {\n logDiff(code, compiledReferenceRoute.code)\n console.log('Output:\\n', compiledReferenceRoute.code + '\\n\\n')\n }\n\n return compiledReferenceRoute\n }\n\n const handleCompilingVirtualFile = (\n code: string,\n id: string,\n ): UnpluginTransformResult => {\n if (debug) console.info('Splitting Route: ', id)\n\n const [_, ...pathnameParts] = id.split('?')\n\n const searchParams = new URLSearchParams(pathnameParts.join('?'))\n const splitValue = searchParams.get(tsrSplit)\n\n if (!splitValue) {\n throw new Error(\n `The split value for the virtual route \"${id}\" was not found.`,\n )\n }\n\n const rawGrouping = decodeIdentifier(splitValue)\n const grouping = [...new Set(rawGrouping)].filter((p) =>\n splitRouteIdentNodes.includes(p as any),\n ) as Array<SplitRouteIdentNodes>\n\n const baseId = id.split('?')[0]!\n const resolvedSharedBindings = sharedBindingsMap.get(baseId)\n\n const result = compileCodeSplitVirtualRoute({\n code,\n filename: id,\n splitTargets: grouping,\n sharedBindings: resolvedSharedBindings,\n })\n\n if (debug) {\n logDiff(code, result.code)\n console.log('Output:\\n', result.code + '\\n\\n')\n }\n\n return result\n }\n\n return [\n {\n name: 'tanstack-router:code-splitter:compile-reference-file',\n enforce: 'pre',\n\n transform: {\n filter: {\n id: {\n exclude: [tsrSplit, tsrShared],\n // this is necessary for webpack / rspack to avoid matching .html files\n include: /\\.(m|c)?(j|t)sx?$/,\n },\n code: {\n include: routeFactoryCallCodeFilter,\n },\n },\n handler(code, id) {\n const normalizedId = normalizePath(id)\n const generatorFileInfo =\n routerPluginContext.routesByFile.get(normalizedId)\n if (generatorFileInfo) {\n return handleCompilingReferenceFile(\n code,\n normalizedId,\n generatorFileInfo,\n )\n }\n\n return null\n },\n },\n\n vite: {\n configResolved(config) {\n ROOT = config.root\n initUserConfig()\n\n // Validate plugin order - router must come before JSX transformation plugins\n const routerPluginIndex = config.plugins.findIndex(\n (p) => p.name === CODE_SPLITTER_PLUGIN_NAME,\n )\n\n if (routerPluginIndex === -1) return\n\n const frameworkPlugins =\n TRANSFORMATION_PLUGINS_BY_FRAMEWORK[userConfig.target]\n if (!frameworkPlugins) return\n\n for (const transformPlugin of frameworkPlugins) {\n const transformPluginIndex = config.plugins.findIndex((p) =>\n transformPlugin.pluginNames.includes(p.name),\n )\n\n if (\n transformPluginIndex !== -1 &&\n transformPluginIndex < routerPluginIndex\n ) {\n throw new Error(\n `Plugin order error: '${transformPlugin.pkg}' is placed before '@tanstack/router-plugin'.\\n\\n` +\n `The TanStack Router plugin must come BEFORE JSX transformation plugins.\\n\\n` +\n `Please update your Vite config:\\n\\n` +\n ` plugins: [\\n` +\n ` tanstackRouter(),\\n` +\n ` ${transformPlugin.usage},\\n` +\n ` ]\\n`,\n )\n }\n }\n },\n applyToEnvironment(environment) {\n if (userConfig.plugin?.vite?.environmentName) {\n return userConfig.plugin.vite.environmentName === environment.name\n }\n return true\n },\n },\n\n rspack() {\n ROOT = process.cwd()\n initUserConfig()\n },\n\n webpack() {\n ROOT = process.cwd()\n initUserConfig()\n },\n },\n {\n name: 'tanstack-router:code-splitter:compile-virtual-file',\n enforce: 'pre',\n\n transform: {\n filter: {\n id: /tsr-split/,\n },\n handler(code, id) {\n const url = pathToFileURL(id)\n url.searchParams.delete('v')\n const normalizedId = normalizePath(fileURLToPath(url))\n return handleCompilingVirtualFile(code, normalizedId)\n },\n },\n\n vite: {\n applyToEnvironment(environment) {\n if (userConfig.plugin?.vite?.environmentName) {\n return userConfig.plugin.vite.environmentName === environment.name\n }\n return true\n },\n },\n },\n {\n name: 'tanstack-router:code-splitter:compile-shared-file',\n enforce: 'pre',\n\n transform: {\n filter: {\n id: /tsr-shared/,\n },\n handler(code, id) {\n const url = pathToFileURL(id)\n url.searchParams.delete('v')\n const normalizedId = normalizePath(fileURLToPath(url))\n const [baseId] = normalizedId.split('?')\n\n if (!baseId) return null\n\n const sharedBindings = sharedBindingsMap.get(baseId)\n if (!sharedBindings || sharedBindings.size === 0) return null\n\n if (debug) console.info('Compiling Shared Module: ', id)\n\n const result = compileCodeSplitSharedRoute({\n code,\n sharedBindings,\n filename: normalizedId,\n })\n\n if (debug) {\n logDiff(code, result.code)\n console.log('Output:\\n', result.code + '\\n\\n')\n }\n\n return result\n },\n },\n\n vite: {\n applyToEnvironment(environment) {\n if (userConfig.plugin?.vite?.environmentName) {\n return userConfig.plugin.vite.environmentName === environment.name\n }\n return true\n },\n },\n },\n ]\n}\n\nexport const unpluginRouterCodeSplitterFactory: UnpluginFactory<\n Partial<Config | (() => Config)> | undefined\n> = (options = {}) => {\n return createRouterCodeSplitterPlugin(options, createRouterPluginContext())\n}\n"],"mappings":";;;;;;;;;;;;;AAiCA,IAAM,4BACJ;;;;;AAYF,IAAM,sCAGF;CACF,OAAO;EACL;GAEE,aAAa,CAAC,oBAAoB,qBAAqB;GACvD,KAAK;GACL,OAAO;GACR;EACD;GAEE,aAAa,CAAC,kBAAkB,iCAAiC;GACjE,KAAK;GACL,OAAO;GACR;EACD;GAEE,aAAa,CAAC,yBAAyB,iCAAiC;GACxE,KAAK;GACL,OAAO;GACR;EACF;CACD,OAAO,CACL;EACE,aAAa,CAAC,QAAQ;EACtB,KAAK;EACL,OAAO;EACR,CACF;CACF;AAED,SAAgB,+BACd,UAAwD,EAAE,EAC1D,qBAC2E;CAC3E,IAAI,OAAe,QAAQ,KAAK;CAChC,IAAI;CAEJ,SAAS,iBAAiB;AACxB,MAAI,OAAO,YAAY,WACrB,cAAa,SAAS;MAEtB,cAAa,UAAU,SAAS,KAAK;;CAGzC,MAAM,eAAA,QAAA,IAAA,aAAwC;CAG9C,MAAM,oCAAoB,IAAI,KAA0B;CAExD,MAAM,oCAAoC;AACxC,SACE,WAAW,sBAAsB,mBACjC;;CAGJ,MAAM,yBAAyB;AA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AChB,MAAM,MAAM,cAAc,GAAG;AAC7B,SAAI,aAAa,OAAO,IAAI;KAC5B,MAAM,eAAe,cAAc,cAAc,IAAI,CAAC;KACtD,MAAM,CAAC,UAAU,aAAa,MAAM,IAAI;AAExC,SAAI,CAAC,OAAQ,QAAO;KAEpB,MAAM,iBAAiB,kBAAkB,IAAI,OAAO;AACpD,SAAI,CAAC,kBAAkB,eAAe,SAAS,EAAG,QAAO;AAEzD,SAAI,MAAO,SAAQ,KAAK,6BAA6B,GAAG;KAExD,MAAM,SAAS,4BAA4B;MACzC;MACA;MACA,UAAU;MACX,CAAC;AAEF,SAAI,OAAO;AACT,cAAQ,MAAM,OAAO,KAAK;AAC1B,cAAQ,IAAI,aAAa,OAAO,OAAO,OAAO;;AAGhD,YAAO;;IAEV;GAED,MAAM,EACJ,mBAAmB,aAAa;AAC9B,QAAI,WAAW,QAAQ,MAAM,gBAC3B,QAAO,WAAW,OAAO,KAAK,oBAAoB,YAAY;AAEhE,WAAO;MAEV;GACF;EACF;;AAGH,IAAa,qCAER,UAAU,EAAE,KAAK;AACpB,QAAO,+BAA+B,SAAS,2BAA2B,CAAC"}

@@ -34,3 +34,3 @@ import { configSchema, CodeSplittingOptions, Config } from './core/config.js';

declare const TanStackRouterEsbuild: (options?: Partial<{
target: "react" | "solid" | "vue";
target: "vue" | "react" | "solid";
routeFileIgnorePrefix: string;

@@ -56,17 +56,7 @@ routesDirectory: string;

importRoutesUsingAbsolutePaths: boolean;
enableRouteGeneration?: boolean | undefined;
codeSplittingOptions?: CodeSplittingOptions | undefined;
plugin?: {
vite?: {
environmentName?: string | undefined;
} | undefined;
hmr?: {
style?: "vite" | "webpack" | undefined;
} | undefined;
} | undefined;
virtualRouteConfig?: string | import('@tanstack/virtual-file-routes').VirtualRootRoute | undefined;
routeFilePrefix?: string | undefined;
routeFileIgnorePattern?: string | undefined;
pathParamsAllowedCharacters?: (";" | ":" | "@" | "&" | "=" | "+" | "$" | ",")[] | undefined;
routeTreeFileFooter?: string[] | ((...args: unknown[]) => string[]) | undefined;
pathParamsAllowedCharacters?: (":" | "$" | ";" | "@" | "&" | "=" | "+" | ",")[] | undefined;
routeTreeFileFooter?: string[] | (() => Array<string>) | undefined;
autoCodeSplitting?: boolean | undefined;

@@ -81,5 +71,15 @@ customScaffolding?: {

plugins?: import('@tanstack/router-generator').GeneratorPlugin[] | undefined;
enableRouteGeneration?: boolean | undefined;
codeSplittingOptions?: CodeSplittingOptions | undefined;
plugin?: {
hmr?: {
style?: "vite" | "webpack" | undefined;
} | undefined;
vite?: {
environmentName?: string | undefined;
} | undefined;
} | undefined;
} | (() => Config)> | undefined) => import('unplugin').EsbuildPlugin;
declare const tanstackRouter: (options?: Partial<{
target: "react" | "solid" | "vue";
target: "vue" | "react" | "solid";
routeFileIgnorePrefix: string;

@@ -105,17 +105,7 @@ routesDirectory: string;

importRoutesUsingAbsolutePaths: boolean;
enableRouteGeneration?: boolean | undefined;
codeSplittingOptions?: CodeSplittingOptions | undefined;
plugin?: {
vite?: {
environmentName?: string | undefined;
} | undefined;
hmr?: {
style?: "vite" | "webpack" | undefined;
} | undefined;
} | undefined;
virtualRouteConfig?: string | import('@tanstack/virtual-file-routes').VirtualRootRoute | undefined;
routeFilePrefix?: string | undefined;
routeFileIgnorePattern?: string | undefined;
pathParamsAllowedCharacters?: (";" | ":" | "@" | "&" | "=" | "+" | "$" | ",")[] | undefined;
routeTreeFileFooter?: string[] | ((...args: unknown[]) => string[]) | undefined;
pathParamsAllowedCharacters?: (":" | "$" | ";" | "@" | "&" | "=" | "+" | ",")[] | undefined;
routeTreeFileFooter?: string[] | (() => Array<string>) | undefined;
autoCodeSplitting?: boolean | undefined;

@@ -130,2 +120,12 @@ customScaffolding?: {

plugins?: import('@tanstack/router-generator').GeneratorPlugin[] | undefined;
enableRouteGeneration?: boolean | undefined;
codeSplittingOptions?: CodeSplittingOptions | undefined;
plugin?: {
hmr?: {
style?: "vite" | "webpack" | undefined;
} | undefined;
vite?: {
environmentName?: string | undefined;
} | undefined;
} | undefined;
} | (() => Config)> | undefined) => import('unplugin').EsbuildPlugin;

@@ -132,0 +132,0 @@ export default TanStackRouterEsbuild;

@@ -7,2 +7,4 @@ export { configSchema, getConfig } from './core/config.js';

export type { RouterPluginContext } from './core/router-plugin-context.js';
export { getObjectPropertyKeyName } from './core/utils.js';
export type { ReferenceRouteCompilerPlugin, ReferenceRouteCompilerPluginContext, } from './core/code-splitter/plugins.js';
export { tsrSplit, splitRouteIdentNodes, defaultCodeSplitGroupings, } from './core/constants.js';
import { configSchema, getConfig } from "./core/config.js";
import { defaultCodeSplitGroupings, splitRouteIdentNodes, tsrSplit } from "./core/constants.js";
import { getObjectPropertyKeyName } from "./core/utils.js";
import { createRouterPluginContext } from "./core/router-plugin-context.js";
import { unpluginRouterCodeSplitterFactory } from "./core/router-code-splitter-plugin.js";
import { unpluginRouterGeneratorFactory } from "./core/router-generator-plugin.js";
export { configSchema, createRouterPluginContext, defaultCodeSplitGroupings, getConfig, splitRouteIdentNodes, tsrSplit, unpluginRouterCodeSplitterFactory, unpluginRouterGeneratorFactory };
export { configSchema, createRouterPluginContext, defaultCodeSplitGroupings, getConfig, getObjectPropertyKeyName, splitRouteIdentNodes, tsrSplit, unpluginRouterCodeSplitterFactory, unpluginRouterGeneratorFactory };

@@ -34,3 +34,3 @@ import { configSchema, getConfig, CodeSplittingOptions, Config } from './core/config.js';

declare const tanstackRouter: (options?: Partial<{
target: "react" | "solid" | "vue";
target: "vue" | "react" | "solid";
routeFileIgnorePrefix: string;

@@ -56,17 +56,7 @@ routesDirectory: string;

importRoutesUsingAbsolutePaths: boolean;
enableRouteGeneration?: boolean | undefined;
codeSplittingOptions?: CodeSplittingOptions | undefined;
plugin?: {
vite?: {
environmentName?: string | undefined;
} | undefined;
hmr?: {
style?: "vite" | "webpack" | undefined;
} | undefined;
} | undefined;
virtualRouteConfig?: string | import('@tanstack/virtual-file-routes').VirtualRootRoute | undefined;
routeFilePrefix?: string | undefined;
routeFileIgnorePattern?: string | undefined;
pathParamsAllowedCharacters?: (";" | ":" | "@" | "&" | "=" | "+" | "$" | ",")[] | undefined;
routeTreeFileFooter?: string[] | ((...args: unknown[]) => string[]) | undefined;
pathParamsAllowedCharacters?: (":" | "$" | ";" | "@" | "&" | "=" | "+" | ",")[] | undefined;
routeTreeFileFooter?: string[] | (() => Array<string>) | undefined;
autoCodeSplitting?: boolean | undefined;

@@ -81,2 +71,12 @@ customScaffolding?: {

plugins?: import('@tanstack/router-generator').GeneratorPlugin[] | undefined;
enableRouteGeneration?: boolean | undefined;
codeSplittingOptions?: CodeSplittingOptions | undefined;
plugin?: {
hmr?: {
style?: "vite" | "webpack" | undefined;
} | undefined;
vite?: {
environmentName?: string | undefined;
} | undefined;
} | undefined;
} | (() => Config)> | undefined) => import('vite').Plugin<any> | import('vite').Plugin<any>[];

@@ -87,3 +87,3 @@ /**

declare const TanStackRouterVite: (options?: Partial<{
target: "react" | "solid" | "vue";
target: "vue" | "react" | "solid";
routeFileIgnorePrefix: string;

@@ -109,17 +109,7 @@ routesDirectory: string;

importRoutesUsingAbsolutePaths: boolean;
enableRouteGeneration?: boolean | undefined;
codeSplittingOptions?: CodeSplittingOptions | undefined;
plugin?: {
vite?: {
environmentName?: string | undefined;
} | undefined;
hmr?: {
style?: "vite" | "webpack" | undefined;
} | undefined;
} | undefined;
virtualRouteConfig?: string | import('@tanstack/virtual-file-routes').VirtualRootRoute | undefined;
routeFilePrefix?: string | undefined;
routeFileIgnorePattern?: string | undefined;
pathParamsAllowedCharacters?: (";" | ":" | "@" | "&" | "=" | "+" | "$" | ",")[] | undefined;
routeTreeFileFooter?: string[] | ((...args: unknown[]) => string[]) | undefined;
pathParamsAllowedCharacters?: (":" | "$" | ";" | "@" | "&" | "=" | "+" | ",")[] | undefined;
routeTreeFileFooter?: string[] | (() => Array<string>) | undefined;
autoCodeSplitting?: boolean | undefined;

@@ -134,2 +124,12 @@ customScaffolding?: {

plugins?: import('@tanstack/router-generator').GeneratorPlugin[] | undefined;
enableRouteGeneration?: boolean | undefined;
codeSplittingOptions?: CodeSplittingOptions | undefined;
plugin?: {
hmr?: {
style?: "vite" | "webpack" | undefined;
} | undefined;
vite?: {
environmentName?: string | undefined;
} | undefined;
} | undefined;
} | (() => Config)> | undefined) => import('vite').Plugin<any> | import('vite').Plugin<any>[];

@@ -136,0 +136,0 @@ export default tanstackRouter;

{
"name": "@tanstack/router-plugin",
"version": "1.168.6",
"version": "1.168.7",
"description": "Modern and scalable routing for React applications",

@@ -109,8 +109,8 @@ "author": "Tanner Linsley",

"@babel/types": "^7.28.5",
"chokidar": "^3.6.0",
"chokidar": "^5.0.0",
"unplugin": "^3.0.0",
"zod": "^3.24.2",
"@tanstack/router-core": "1.171.2",
"@tanstack/router-generator": "1.167.5",
"@tanstack/router-utils": "1.162.0",
"zod": "^4.4.3",
"@tanstack/router-core": "1.171.3",
"@tanstack/router-generator": "1.167.6",
"@tanstack/router-utils": "1.162.1",
"@tanstack/virtual-file-routes": "1.162.0"

@@ -129,3 +129,3 @@ },

"webpack": ">=5.92.0",
"@tanstack/react-router": "^1.170.4"
"@tanstack/react-router": "^1.170.5"
},

@@ -132,0 +132,0 @@ "peerDependenciesMeta": {

@@ -46,2 +46,5 @@ import type babel from '@babel/core'

getStableRouteOptionKeys?: () => Array<string>
onRouteOptions?: (
ctx: ReferenceRouteCompilerPluginContext,
) => void | ReferenceRouteCompilerPluginResult
onAddHmr?: (

@@ -48,0 +51,0 @@ ctx: ReferenceRouteCompilerPluginContext,

@@ -12,2 +12,3 @@ import { z } from 'zod'

import type { CodeSplitGroupings } from './constants'
import type { ReferenceRouteCompilerPlugin } from './code-splitter/plugins'

@@ -74,2 +75,8 @@ export const splitGroupingsSchema = z

addHmr?: boolean
/**
* Internal compiler plugins used by framework integrations.
* @internal
*/
compilerPlugins?: Array<ReferenceRouteCompilerPlugin>
}

@@ -91,3 +98,7 @@

const codeSplittingOptionsSchema = z.object({
splitBehavior: z.function().optional(),
splitBehavior: z
.custom<
CodeSplittingOptions['splitBehavior']
>((value) => typeof value === 'function')
.optional(),
defaultBehavior: splitGroupingsSchema.optional(),

@@ -94,0 +105,0 @@ deleteNodes: z.array(z.string()).optional(),

@@ -7,3 +7,3 @@ /**

import { fileURLToPath, pathToFileURL } from 'node:url'
import { logDiff } from '@tanstack/router-utils'
import { decodeIdentifier, logDiff } from '@tanstack/router-utils'
import { getConfig, splitGroupingsSchema } from './config'

@@ -24,3 +24,2 @@ import {

} from './constants'
import { decodeIdentifier } from './code-splitter/path-ids'
import { debug, normalizePath, routeFactoryCallCodeFilter } from './utils'

@@ -127,3 +126,3 @@ import { createRouterPluginContext } from './router-plugin-context'

if (!res.success) {
const message = res.error.errors.map((e) => e.message).join('. ')
const message = res.error.issues.map((e) => e.message).join('. ')
throw new Error(

@@ -144,3 +143,3 @@ `The groupings for the route "${id}" are invalid.\n${message}`,

if (!res.success) {
const message = res.error.errors.map((e) => e.message).join('. ')
const message = res.error.issues.map((e) => e.message).join('. ')
throw new Error(

@@ -184,7 +183,10 @@ `The groupings returned when using \`splitBehavior\` for the route "${id}" are invalid.\n${message}`,

sharedBindings: sharedBindings.size > 0 ? sharedBindings : undefined,
compilerPlugins: getReferenceRouteCompilerPlugins({
targetFramework: userConfig.target,
addHmr,
hmrStyle,
}),
compilerPlugins: [
...(getReferenceRouteCompilerPlugins({
targetFramework: userConfig.target,
addHmr,
hmrStyle,
}) ?? []),
...(userConfig.codeSplittingOptions?.compilerPlugins ?? []),
],
})

@@ -191,0 +193,0 @@

@@ -14,2 +14,7 @@ export { configSchema, getConfig } from './core/config'

export type { RouterPluginContext } from './core/router-plugin-context'
export { getObjectPropertyKeyName } from './core/utils'
export type {
ReferenceRouteCompilerPlugin,
ReferenceRouteCompilerPluginContext,
} from './core/code-splitter/plugins'
export {

@@ -16,0 +21,0 @@ tsrSplit,

//#region src/core/code-splitter/path-ids.ts
function createIdentifier(strings) {
if (strings.length === 0) throw new Error("Cannot create an identifier from an empty array");
let safeString = [...strings].sort().join("---").replace(/\//g, "--slash--");
safeString = safeString.replace(/\\/g, "--backslash--");
safeString = safeString.replace(/\?/g, "--question--");
safeString = safeString.replace(/%/g, "--percent--");
safeString = safeString.replace(/#/g, "--hash--");
safeString = safeString.replace(/\+/g, "--plus--");
safeString = safeString.replace(/=/g, "--equals--");
safeString = safeString.replace(/&/g, "--ampersand--");
safeString = safeString.replace(/\s/g, "_");
return safeString;
}
function decodeIdentifier(identifier) {
if (!identifier) return [];
let combinedString = identifier.replace(/--slash--/g, "/");
combinedString = combinedString.replace(/--backslash--/g, "\\");
combinedString = combinedString.replace(/--question--/g, "?");
combinedString = combinedString.replace(/--percent--/g, "%");
combinedString = combinedString.replace(/--hash--/g, "#");
combinedString = combinedString.replace(/--plus--/g, "+");
combinedString = combinedString.replace(/--equals--/g, "=");
combinedString = combinedString.replace(/--ampersand--/g, "&");
combinedString = combinedString.replace(/_/g, " ");
return combinedString.split("---");
}
//#endregion
exports.createIdentifier = createIdentifier;
exports.decodeIdentifier = decodeIdentifier;
//# sourceMappingURL=path-ids.cjs.map
{"version":3,"file":"path-ids.cjs","names":[],"sources":["../../../../src/core/code-splitter/path-ids.ts"],"sourcesContent":["export function createIdentifier(strings: Array<string>): string {\n if (strings.length === 0) {\n throw new Error('Cannot create an identifier from an empty array')\n }\n\n const sortedStrings = [...strings].sort()\n const combinedString = sortedStrings.join('---') // Delimiter\n\n // Replace unsafe characters\n let safeString = combinedString.replace(/\\//g, '--slash--')\n safeString = safeString.replace(/\\\\/g, '--backslash--')\n safeString = safeString.replace(/\\?/g, '--question--')\n safeString = safeString.replace(/%/g, '--percent--')\n safeString = safeString.replace(/#/g, '--hash--')\n safeString = safeString.replace(/\\+/g, '--plus--')\n safeString = safeString.replace(/=/g, '--equals--')\n safeString = safeString.replace(/&/g, '--ampersand--')\n safeString = safeString.replace(/\\s/g, '_') // Replace spaces with underscores\n\n return safeString\n}\n\nexport function decodeIdentifier(identifier: string): Array<string> {\n if (!identifier) {\n return []\n }\n\n let combinedString = identifier.replace(/--slash--/g, '/')\n combinedString = combinedString.replace(/--backslash--/g, '\\\\')\n combinedString = combinedString.replace(/--question--/g, '?')\n combinedString = combinedString.replace(/--percent--/g, '%')\n combinedString = combinedString.replace(/--hash--/g, '#')\n combinedString = combinedString.replace(/--plus--/g, '+')\n combinedString = combinedString.replace(/--equals--/g, '=')\n combinedString = combinedString.replace(/--ampersand--/g, '&')\n combinedString = combinedString.replace(/_/g, ' ') // Restore spaces\n\n return combinedString.split('---')\n}\n"],"mappings":";AAAA,SAAgB,iBAAiB,SAAgC;AAC/D,KAAI,QAAQ,WAAW,EACrB,OAAM,IAAI,MAAM,kDAAkD;CAOpE,IAAI,aAJkB,CAAC,GAAG,QAAQ,CAAC,MAAM,CACJ,KAAK,MAAM,CAGhB,QAAQ,OAAO,YAAY;AAC3D,cAAa,WAAW,QAAQ,OAAO,gBAAgB;AACvD,cAAa,WAAW,QAAQ,OAAO,eAAe;AACtD,cAAa,WAAW,QAAQ,MAAM,cAAc;AACpD,cAAa,WAAW,QAAQ,MAAM,WAAW;AACjD,cAAa,WAAW,QAAQ,OAAO,WAAW;AAClD,cAAa,WAAW,QAAQ,MAAM,aAAa;AACnD,cAAa,WAAW,QAAQ,MAAM,gBAAgB;AACtD,cAAa,WAAW,QAAQ,OAAO,IAAI;AAE3C,QAAO;;AAGT,SAAgB,iBAAiB,YAAmC;AAClE,KAAI,CAAC,WACH,QAAO,EAAE;CAGX,IAAI,iBAAiB,WAAW,QAAQ,cAAc,IAAI;AAC1D,kBAAiB,eAAe,QAAQ,kBAAkB,KAAK;AAC/D,kBAAiB,eAAe,QAAQ,iBAAiB,IAAI;AAC7D,kBAAiB,eAAe,QAAQ,gBAAgB,IAAI;AAC5D,kBAAiB,eAAe,QAAQ,aAAa,IAAI;AACzD,kBAAiB,eAAe,QAAQ,aAAa,IAAI;AACzD,kBAAiB,eAAe,QAAQ,eAAe,IAAI;AAC3D,kBAAiB,eAAe,QAAQ,kBAAkB,IAAI;AAC9D,kBAAiB,eAAe,QAAQ,MAAM,IAAI;AAElD,QAAO,eAAe,MAAM,MAAM"}
export declare function createIdentifier(strings: Array<string>): string;
export declare function decodeIdentifier(identifier: string): Array<string>;
export declare function createIdentifier(strings: Array<string>): string;
export declare function decodeIdentifier(identifier: string): Array<string>;
//#region src/core/code-splitter/path-ids.ts
function createIdentifier(strings) {
if (strings.length === 0) throw new Error("Cannot create an identifier from an empty array");
let safeString = [...strings].sort().join("---").replace(/\//g, "--slash--");
safeString = safeString.replace(/\\/g, "--backslash--");
safeString = safeString.replace(/\?/g, "--question--");
safeString = safeString.replace(/%/g, "--percent--");
safeString = safeString.replace(/#/g, "--hash--");
safeString = safeString.replace(/\+/g, "--plus--");
safeString = safeString.replace(/=/g, "--equals--");
safeString = safeString.replace(/&/g, "--ampersand--");
safeString = safeString.replace(/\s/g, "_");
return safeString;
}
function decodeIdentifier(identifier) {
if (!identifier) return [];
let combinedString = identifier.replace(/--slash--/g, "/");
combinedString = combinedString.replace(/--backslash--/g, "\\");
combinedString = combinedString.replace(/--question--/g, "?");
combinedString = combinedString.replace(/--percent--/g, "%");
combinedString = combinedString.replace(/--hash--/g, "#");
combinedString = combinedString.replace(/--plus--/g, "+");
combinedString = combinedString.replace(/--equals--/g, "=");
combinedString = combinedString.replace(/--ampersand--/g, "&");
combinedString = combinedString.replace(/_/g, " ");
return combinedString.split("---");
}
//#endregion
export { createIdentifier, decodeIdentifier };
//# sourceMappingURL=path-ids.js.map
{"version":3,"file":"path-ids.js","names":[],"sources":["../../../../src/core/code-splitter/path-ids.ts"],"sourcesContent":["export function createIdentifier(strings: Array<string>): string {\n if (strings.length === 0) {\n throw new Error('Cannot create an identifier from an empty array')\n }\n\n const sortedStrings = [...strings].sort()\n const combinedString = sortedStrings.join('---') // Delimiter\n\n // Replace unsafe characters\n let safeString = combinedString.replace(/\\//g, '--slash--')\n safeString = safeString.replace(/\\\\/g, '--backslash--')\n safeString = safeString.replace(/\\?/g, '--question--')\n safeString = safeString.replace(/%/g, '--percent--')\n safeString = safeString.replace(/#/g, '--hash--')\n safeString = safeString.replace(/\\+/g, '--plus--')\n safeString = safeString.replace(/=/g, '--equals--')\n safeString = safeString.replace(/&/g, '--ampersand--')\n safeString = safeString.replace(/\\s/g, '_') // Replace spaces with underscores\n\n return safeString\n}\n\nexport function decodeIdentifier(identifier: string): Array<string> {\n if (!identifier) {\n return []\n }\n\n let combinedString = identifier.replace(/--slash--/g, '/')\n combinedString = combinedString.replace(/--backslash--/g, '\\\\')\n combinedString = combinedString.replace(/--question--/g, '?')\n combinedString = combinedString.replace(/--percent--/g, '%')\n combinedString = combinedString.replace(/--hash--/g, '#')\n combinedString = combinedString.replace(/--plus--/g, '+')\n combinedString = combinedString.replace(/--equals--/g, '=')\n combinedString = combinedString.replace(/--ampersand--/g, '&')\n combinedString = combinedString.replace(/_/g, ' ') // Restore spaces\n\n return combinedString.split('---')\n}\n"],"mappings":";AAAA,SAAgB,iBAAiB,SAAgC;AAC/D,KAAI,QAAQ,WAAW,EACrB,OAAM,IAAI,MAAM,kDAAkD;CAOpE,IAAI,aAJkB,CAAC,GAAG,QAAQ,CAAC,MAAM,CACJ,KAAK,MAAM,CAGhB,QAAQ,OAAO,YAAY;AAC3D,cAAa,WAAW,QAAQ,OAAO,gBAAgB;AACvD,cAAa,WAAW,QAAQ,OAAO,eAAe;AACtD,cAAa,WAAW,QAAQ,MAAM,cAAc;AACpD,cAAa,WAAW,QAAQ,MAAM,WAAW;AACjD,cAAa,WAAW,QAAQ,OAAO,WAAW;AAClD,cAAa,WAAW,QAAQ,MAAM,aAAa;AACnD,cAAa,WAAW,QAAQ,MAAM,gBAAgB;AACtD,cAAa,WAAW,QAAQ,OAAO,IAAI;AAE3C,QAAO;;AAGT,SAAgB,iBAAiB,YAAmC;AAClE,KAAI,CAAC,WACH,QAAO,EAAE;CAGX,IAAI,iBAAiB,WAAW,QAAQ,cAAc,IAAI;AAC1D,kBAAiB,eAAe,QAAQ,kBAAkB,KAAK;AAC/D,kBAAiB,eAAe,QAAQ,iBAAiB,IAAI;AAC7D,kBAAiB,eAAe,QAAQ,gBAAgB,IAAI;AAC5D,kBAAiB,eAAe,QAAQ,aAAa,IAAI;AACzD,kBAAiB,eAAe,QAAQ,aAAa,IAAI;AACzD,kBAAiB,eAAe,QAAQ,eAAe,IAAI;AAC3D,kBAAiB,eAAe,QAAQ,kBAAkB,IAAI;AAC9D,kBAAiB,eAAe,QAAQ,MAAM,IAAI;AAElD,QAAO,eAAe,MAAM,MAAM"}
export function createIdentifier(strings: Array<string>): string {
if (strings.length === 0) {
throw new Error('Cannot create an identifier from an empty array')
}
const sortedStrings = [...strings].sort()
const combinedString = sortedStrings.join('---') // Delimiter
// Replace unsafe characters
let safeString = combinedString.replace(/\//g, '--slash--')
safeString = safeString.replace(/\\/g, '--backslash--')
safeString = safeString.replace(/\?/g, '--question--')
safeString = safeString.replace(/%/g, '--percent--')
safeString = safeString.replace(/#/g, '--hash--')
safeString = safeString.replace(/\+/g, '--plus--')
safeString = safeString.replace(/=/g, '--equals--')
safeString = safeString.replace(/&/g, '--ampersand--')
safeString = safeString.replace(/\s/g, '_') // Replace spaces with underscores
return safeString
}
export function decodeIdentifier(identifier: string): Array<string> {
if (!identifier) {
return []
}
let combinedString = identifier.replace(/--slash--/g, '/')
combinedString = combinedString.replace(/--backslash--/g, '\\')
combinedString = combinedString.replace(/--question--/g, '?')
combinedString = combinedString.replace(/--percent--/g, '%')
combinedString = combinedString.replace(/--hash--/g, '#')
combinedString = combinedString.replace(/--plus--/g, '+')
combinedString = combinedString.replace(/--equals--/g, '=')
combinedString = combinedString.replace(/--ampersand--/g, '&')
combinedString = combinedString.replace(/_/g, ' ') // Restore spaces
return combinedString.split('---')
}

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display