@tanstack/router-plugin 1.166.7 → 1.166.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/core/code-splitter/compilers.cjs +14 -0
- package/dist/cjs/core/code-splitter/compilers.cjs.map +1 -1
- package/dist/cjs/core/code-splitter/compilers.d.cts +2 -0
- package/dist/cjs/core/code-splitter/plugins/framework-plugins.cjs +17 -0
- package/dist/cjs/core/code-splitter/plugins/framework-plugins.cjs.map +1 -0
- package/dist/cjs/core/code-splitter/plugins/framework-plugins.d.cts +6 -0
- package/dist/cjs/core/code-splitter/plugins/react-refresh-route-components.cjs +69 -0
- package/dist/cjs/core/code-splitter/plugins/react-refresh-route-components.cjs.map +1 -0
- package/dist/cjs/core/code-splitter/plugins/react-refresh-route-components.d.cts +2 -0
- package/dist/cjs/core/code-splitter/plugins.d.cts +28 -0
- package/dist/cjs/core/router-code-splitter-plugin.cjs +11 -5
- package/dist/cjs/core/router-code-splitter-plugin.cjs.map +1 -1
- package/dist/cjs/core/router-hmr-plugin.cjs +23 -0
- package/dist/cjs/core/router-hmr-plugin.cjs.map +1 -1
- package/dist/cjs/core/utils.cjs +28 -0
- package/dist/cjs/core/utils.cjs.map +1 -1
- package/dist/cjs/core/utils.d.cts +3 -0
- package/dist/esm/core/code-splitter/compilers.d.ts +2 -0
- package/dist/esm/core/code-splitter/compilers.js +14 -0
- package/dist/esm/core/code-splitter/compilers.js.map +1 -1
- package/dist/esm/core/code-splitter/plugins/framework-plugins.d.ts +6 -0
- package/dist/esm/core/code-splitter/plugins/framework-plugins.js +17 -0
- package/dist/esm/core/code-splitter/plugins/framework-plugins.js.map +1 -0
- package/dist/esm/core/code-splitter/plugins/react-refresh-route-components.d.ts +2 -0
- package/dist/esm/core/code-splitter/plugins/react-refresh-route-components.js +52 -0
- package/dist/esm/core/code-splitter/plugins/react-refresh-route-components.js.map +1 -0
- package/dist/esm/core/code-splitter/plugins.d.ts +28 -0
- package/dist/esm/core/router-code-splitter-plugin.js +8 -2
- package/dist/esm/core/router-code-splitter-plugin.js.map +1 -1
- package/dist/esm/core/router-hmr-plugin.js +24 -1
- package/dist/esm/core/router-hmr-plugin.js.map +1 -1
- package/dist/esm/core/utils.d.ts +3 -0
- package/dist/esm/core/utils.js +11 -0
- package/dist/esm/core/utils.js.map +1 -1
- package/package.json +2 -2
- package/src/core/code-splitter/compilers.ts +22 -0
- package/src/core/code-splitter/plugins/framework-plugins.ts +19 -0
- package/src/core/code-splitter/plugins/react-refresh-route-components.ts +63 -0
- package/src/core/code-splitter/plugins.ts +34 -0
- package/src/core/router-code-splitter-plugin.ts +9 -3
- package/src/core/router-hmr-plugin.ts +26 -0
- package/src/core/utils.ts +21 -0
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
3
|
+
const t = require("@babel/types");
|
|
4
|
+
const utils = require("../../utils.cjs");
|
|
5
|
+
function _interopNamespaceDefault(e) {
|
|
6
|
+
const n = Object.create(null, { [Symbol.toStringTag]: { value: "Module" } });
|
|
7
|
+
if (e) {
|
|
8
|
+
for (const k in e) {
|
|
9
|
+
if (k !== "default") {
|
|
10
|
+
const d = Object.getOwnPropertyDescriptor(e, k);
|
|
11
|
+
Object.defineProperty(n, k, d.get ? d : {
|
|
12
|
+
enumerable: true,
|
|
13
|
+
get: () => e[k]
|
|
14
|
+
});
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
n.default = e;
|
|
19
|
+
return Object.freeze(n);
|
|
20
|
+
}
|
|
21
|
+
const t__namespace = /* @__PURE__ */ _interopNamespaceDefault(t);
|
|
22
|
+
const REACT_REFRESH_ROUTE_COMPONENT_IDENTS = /* @__PURE__ */ new Set([
|
|
23
|
+
"component",
|
|
24
|
+
"pendingComponent",
|
|
25
|
+
"errorComponent",
|
|
26
|
+
"notFoundComponent"
|
|
27
|
+
]);
|
|
28
|
+
function createReactRefreshRouteComponentsPlugin() {
|
|
29
|
+
return {
|
|
30
|
+
name: "react-refresh-route-components",
|
|
31
|
+
onUnsplittableRoute(ctx) {
|
|
32
|
+
if (!ctx.opts.addHmr) {
|
|
33
|
+
return;
|
|
34
|
+
}
|
|
35
|
+
const hoistedDeclarations = [];
|
|
36
|
+
ctx.routeOptions.properties.forEach((prop) => {
|
|
37
|
+
if (!t__namespace.isObjectProperty(prop) || !t__namespace.isIdentifier(prop.key)) {
|
|
38
|
+
return;
|
|
39
|
+
}
|
|
40
|
+
if (!REACT_REFRESH_ROUTE_COMPONENT_IDENTS.has(prop.key.name)) {
|
|
41
|
+
return;
|
|
42
|
+
}
|
|
43
|
+
if (!t__namespace.isArrowFunctionExpression(prop.value) && !t__namespace.isFunctionExpression(prop.value)) {
|
|
44
|
+
return;
|
|
45
|
+
}
|
|
46
|
+
const hoistedIdentifier = utils.getUniqueProgramIdentifier(
|
|
47
|
+
ctx.programPath,
|
|
48
|
+
`TSR${prop.key.name[0].toUpperCase()}${prop.key.name.slice(1)}`
|
|
49
|
+
);
|
|
50
|
+
hoistedDeclarations.push(
|
|
51
|
+
t__namespace.variableDeclaration("const", [
|
|
52
|
+
t__namespace.variableDeclarator(
|
|
53
|
+
hoistedIdentifier,
|
|
54
|
+
t__namespace.cloneNode(prop.value, true)
|
|
55
|
+
)
|
|
56
|
+
])
|
|
57
|
+
);
|
|
58
|
+
prop.value = t__namespace.cloneNode(hoistedIdentifier);
|
|
59
|
+
});
|
|
60
|
+
if (hoistedDeclarations.length === 0) {
|
|
61
|
+
return;
|
|
62
|
+
}
|
|
63
|
+
ctx.insertionPath.insertBefore(hoistedDeclarations);
|
|
64
|
+
return { modified: true };
|
|
65
|
+
}
|
|
66
|
+
};
|
|
67
|
+
}
|
|
68
|
+
exports.createReactRefreshRouteComponentsPlugin = createReactRefreshRouteComponentsPlugin;
|
|
69
|
+
//# sourceMappingURL=react-refresh-route-components.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"react-refresh-route-components.cjs","sources":["../../../../../src/core/code-splitter/plugins/react-refresh-route-components.ts"],"sourcesContent":["import * as t from '@babel/types'\nimport { getUniqueProgramIdentifier } from '../../utils'\nimport type { ReferenceRouteCompilerPlugin } from '../plugins'\n\nconst REACT_REFRESH_ROUTE_COMPONENT_IDENTS = new Set([\n 'component',\n 'pendingComponent',\n 'errorComponent',\n 'notFoundComponent',\n])\n\nexport function createReactRefreshRouteComponentsPlugin(): ReferenceRouteCompilerPlugin {\n return {\n name: 'react-refresh-route-components',\n onUnsplittableRoute(ctx) {\n if (!ctx.opts.addHmr) {\n return\n }\n\n const hoistedDeclarations: Array<t.VariableDeclaration> = []\n\n ctx.routeOptions.properties.forEach((prop) => {\n if (!t.isObjectProperty(prop) || !t.isIdentifier(prop.key)) {\n return\n }\n\n if (!REACT_REFRESH_ROUTE_COMPONENT_IDENTS.has(prop.key.name)) {\n return\n }\n\n if (\n !t.isArrowFunctionExpression(prop.value) &&\n !t.isFunctionExpression(prop.value)\n ) {\n return\n }\n\n const hoistedIdentifier = getUniqueProgramIdentifier(\n ctx.programPath,\n `TSR${prop.key.name[0]!.toUpperCase()}${prop.key.name.slice(1)}`,\n )\n\n hoistedDeclarations.push(\n t.variableDeclaration('const', [\n t.variableDeclarator(\n hoistedIdentifier,\n t.cloneNode(prop.value, true),\n ),\n ]),\n )\n\n prop.value = t.cloneNode(hoistedIdentifier)\n })\n\n if (hoistedDeclarations.length === 0) {\n return\n }\n\n ctx.insertionPath.insertBefore(hoistedDeclarations)\n return { modified: true }\n },\n }\n}\n"],"names":["t","getUniqueProgramIdentifier"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAIA,MAAM,2DAA2C,IAAI;AAAA,EACnD;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,CAAC;AAEM,SAAS,0CAAwE;AACtF,SAAO;AAAA,IACL,MAAM;AAAA,IACN,oBAAoB,KAAK;AACvB,UAAI,CAAC,IAAI,KAAK,QAAQ;AACpB;AAAA,MACF;AAEA,YAAM,sBAAoD,CAAA;AAE1D,UAAI,aAAa,WAAW,QAAQ,CAAC,SAAS;AAC5C,YAAI,CAACA,aAAE,iBAAiB,IAAI,KAAK,CAACA,aAAE,aAAa,KAAK,GAAG,GAAG;AAC1D;AAAA,QACF;AAEA,YAAI,CAAC,qCAAqC,IAAI,KAAK,IAAI,IAAI,GAAG;AAC5D;AAAA,QACF;AAEA,YACE,CAACA,aAAE,0BAA0B,KAAK,KAAK,KACvC,CAACA,aAAE,qBAAqB,KAAK,KAAK,GAClC;AACA;AAAA,QACF;AAEA,cAAM,oBAAoBC,MAAAA;AAAAA,UACxB,IAAI;AAAA,UACJ,MAAM,KAAK,IAAI,KAAK,CAAC,EAAG,aAAa,GAAG,KAAK,IAAI,KAAK,MAAM,CAAC,CAAC;AAAA,QAAA;AAGhE,4BAAoB;AAAA,UAClBD,aAAE,oBAAoB,SAAS;AAAA,YAC7BA,aAAE;AAAA,cACA;AAAA,cACAA,aAAE,UAAU,KAAK,OAAO,IAAI;AAAA,YAAA;AAAA,UAC9B,CACD;AAAA,QAAA;AAGH,aAAK,QAAQA,aAAE,UAAU,iBAAiB;AAAA,MAC5C,CAAC;AAED,UAAI,oBAAoB,WAAW,GAAG;AACpC;AAAA,MACF;AAEA,UAAI,cAAc,aAAa,mBAAmB;AAClD,aAAO,EAAE,UAAU,KAAA;AAAA,IACrB;AAAA,EAAA;AAEJ;;"}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import { default as babel } from '@babel/core';
|
|
2
|
+
import { Config, DeletableNodes } from '../config.cjs';
|
|
3
|
+
import { CodeSplitGroupings } from '../constants.cjs';
|
|
4
|
+
import type * as t from '@babel/types';
|
|
5
|
+
export type CompileCodeSplitReferenceRouteOptions = {
|
|
6
|
+
codeSplitGroupings: CodeSplitGroupings;
|
|
7
|
+
deleteNodes?: Set<DeletableNodes>;
|
|
8
|
+
targetFramework: Config['target'];
|
|
9
|
+
filename: string;
|
|
10
|
+
id: string;
|
|
11
|
+
addHmr?: boolean;
|
|
12
|
+
sharedBindings?: Set<string>;
|
|
13
|
+
};
|
|
14
|
+
export type ReferenceRouteCompilerPluginContext = {
|
|
15
|
+
programPath: babel.NodePath<t.Program>;
|
|
16
|
+
callExpressionPath: babel.NodePath<t.CallExpression>;
|
|
17
|
+
insertionPath: babel.NodePath;
|
|
18
|
+
routeOptions: t.ObjectExpression;
|
|
19
|
+
createRouteFn: string;
|
|
20
|
+
opts: CompileCodeSplitReferenceRouteOptions;
|
|
21
|
+
};
|
|
22
|
+
export type ReferenceRouteCompilerPluginResult = {
|
|
23
|
+
modified?: boolean;
|
|
24
|
+
};
|
|
25
|
+
export type ReferenceRouteCompilerPlugin = {
|
|
26
|
+
name: string;
|
|
27
|
+
onUnsplittableRoute?: (ctx: ReferenceRouteCompilerPluginContext) => void | ReferenceRouteCompilerPluginResult;
|
|
28
|
+
};
|
|
@@ -4,6 +4,7 @@ const node_url = require("node:url");
|
|
|
4
4
|
const routerUtils = require("@tanstack/router-utils");
|
|
5
5
|
const config = require("./config.cjs");
|
|
6
6
|
const compilers = require("./code-splitter/compilers.cjs");
|
|
7
|
+
const frameworkPlugins = require("./code-splitter/plugins/framework-plugins.cjs");
|
|
7
8
|
const constants = require("./constants.cjs");
|
|
8
9
|
const pathIds = require("./code-splitter/path-ids.cjs");
|
|
9
10
|
const utils = require("./utils.cjs");
|
|
@@ -95,6 +96,7 @@ ${message}`
|
|
|
95
96
|
} else {
|
|
96
97
|
sharedBindingsMap.delete(id);
|
|
97
98
|
}
|
|
99
|
+
const addHmr = (userConfig.codeSplittingOptions?.addHmr ?? true) && !isProduction;
|
|
98
100
|
const compiledReferenceRoute = compilers.compileCodeSplitReferenceRoute({
|
|
99
101
|
code,
|
|
100
102
|
codeSplitGroupings: splitGroupings,
|
|
@@ -102,8 +104,12 @@ ${message}`
|
|
|
102
104
|
filename: id,
|
|
103
105
|
id,
|
|
104
106
|
deleteNodes: userConfig.codeSplittingOptions?.deleteNodes ? new Set(userConfig.codeSplittingOptions.deleteNodes) : void 0,
|
|
105
|
-
addHmr
|
|
106
|
-
sharedBindings: sharedBindings.size > 0 ? sharedBindings : void 0
|
|
107
|
+
addHmr,
|
|
108
|
+
sharedBindings: sharedBindings.size > 0 ? sharedBindings : void 0,
|
|
109
|
+
compilerPlugins: frameworkPlugins.getReferenceRouteCompilerPlugins({
|
|
110
|
+
targetFramework: userConfig.target,
|
|
111
|
+
addHmr
|
|
112
|
+
})
|
|
107
113
|
});
|
|
108
114
|
if (compiledReferenceRoute === null) {
|
|
109
115
|
if (utils.debug) {
|
|
@@ -188,9 +194,9 @@ ${message}`
|
|
|
188
194
|
(p) => p.name === CODE_SPLITTER_PLUGIN_NAME
|
|
189
195
|
);
|
|
190
196
|
if (routerPluginIndex === -1) return;
|
|
191
|
-
const
|
|
192
|
-
if (!
|
|
193
|
-
for (const transformPlugin of
|
|
197
|
+
const frameworkPlugins2 = TRANSFORMATION_PLUGINS_BY_FRAMEWORK[userConfig.target];
|
|
198
|
+
if (!frameworkPlugins2) return;
|
|
199
|
+
for (const transformPlugin of frameworkPlugins2) {
|
|
194
200
|
const transformPluginIndex = config2.plugins.findIndex(
|
|
195
201
|
(p) => transformPlugin.pluginNames.includes(p.name)
|
|
196
202
|
);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"router-code-splitter-plugin.cjs","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 {\n defaultCodeSplitGroupings,\n splitRouteIdentNodes,\n tsrShared,\n tsrSplit,\n} from './constants'\nimport { decodeIdentifier } from './code-splitter/path-ids'\nimport { debug, normalizePath } from './utils'\nimport type { CodeSplitGroupings, SplitRouteIdentNodes } from './constants'\nimport type { GetRoutesByFileMapResultValue } from '@tanstack/router-generator'\nimport type { Config } from './config'\nimport type {\n UnpluginFactory,\n TransformResult as UnpluginTransformResult,\n} from 'unplugin'\n\nconst PLUGIN_NAME = 'unplugin:router-code-splitter'\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 const unpluginRouterCodeSplitterFactory: UnpluginFactory<\n Partial<Config | (() => Config)> | undefined\n> = (options = {}, { framework: _framework }) => {\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\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 })\n\n if (fromCode.groupings) {\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.routePath,\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 codeSplitGroupings: splitGroupings,\n })\n if (sharedBindings.size > 0) {\n sharedBindingsMap.set(id, sharedBindings)\n } else {\n sharedBindingsMap.delete(id)\n }\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 (userConfig.codeSplittingOptions?.addHmr ?? true) && !isProduction,\n sharedBindings: sharedBindings.size > 0 ? sharedBindings : undefined,\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 const includedCode = [\n 'createFileRoute(',\n 'createRootRoute(',\n 'createRootRouteWithContext(',\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: includedCode,\n },\n },\n handler(code, id) {\n const normalizedId = normalizePath(id)\n const generatorFileInfo =\n globalThis.TSR_ROUTES_BY_ID_MAP?.get(normalizedId)\n if (\n generatorFileInfo &&\n includedCode.some((included) => code.includes(included))\n ) {\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(compiler) {\n ROOT = process.cwd()\n initUserConfig()\n\n if (compiler.options.mode === 'production') {\n compiler.hooks.done.tap(PLUGIN_NAME, () => {\n console.info('✅ ' + PLUGIN_NAME + ': code-splitting done!')\n })\n }\n },\n\n webpack(compiler) {\n ROOT = process.cwd()\n initUserConfig()\n\n if (compiler.options.mode === 'production') {\n compiler.hooks.done.tap(PLUGIN_NAME, () => {\n console.info('✅ ' + PLUGIN_NAME + ': code-splitting done!')\n })\n }\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"],"names":["getConfig","defaultCodeSplitGroupings","debug","detectCodeSplitGroupingsFromRoute","splitGroupingsSchema","computeSharedBindings","compileCodeSplitReferenceRoute","logDiff","tsrSplit","decodeIdentifier","splitRouteIdentNodes","compileCodeSplitVirtualRoute","tsrShared","normalizePath","config","pathToFileURL","fileURLToPath","compileCodeSplitSharedRoute"],"mappings":";;;;;;;;;AA+BA,MAAM,cAAc;AACpB,MAAM,4BACJ;AAYF,MAAM,sCAGF;AAAA,EACF,OAAO;AAAA,IACL;AAAA;AAAA,MAEE,aAAa,CAAC,oBAAoB,oBAAoB;AAAA,MACtD,KAAK;AAAA,MACL,OAAO;AAAA,IAAA;AAAA,IAET;AAAA;AAAA,MAEE,aAAa,CAAC,kBAAkB,gCAAgC;AAAA,MAChE,KAAK;AAAA,MACL,OAAO;A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AAAA,YACzC;AAAA,YACA;AAAA,YACA,UAAU;AAAA,UAAA,CACX;AAED,cAAIf,aAAO;AACTK,gCAAQ,MAAM,OAAO,IAAI;AACzB,oBAAQ,IAAI,aAAa,OAAO,OAAO,MAAM;AAAA,UAC/C;AAEA,iBAAO;AAAA,QACT;AAAA,MAAA;AAAA,MAGF,MAAM;AAAA,QACJ,mBAAmB,aAAa;AAC9B,cAAI,WAAW,QAAQ,MAAM,iBAAiB;AAC5C,mBAAO,WAAW,OAAO,KAAK,oBAAoB,YAAY;AAAA,UAChE;AACA,iBAAO;AAAA,QACT;AAAA,MAAA;AAAA,IACF;AAAA,EACF;AAEJ;;"}
|
|
1
|
+
{"version":3,"file":"router-code-splitter-plugin.cjs","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 } from './utils'\nimport type { CodeSplitGroupings, SplitRouteIdentNodes } from './constants'\nimport type { GetRoutesByFileMapResultValue } from '@tanstack/router-generator'\nimport type { Config } from './config'\nimport type {\n UnpluginFactory,\n TransformResult as UnpluginTransformResult,\n} from 'unplugin'\n\nconst PLUGIN_NAME = 'unplugin:router-code-splitter'\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 const unpluginRouterCodeSplitterFactory: UnpluginFactory<\n Partial<Config | (() => Config)> | undefined\n> = (options = {}, { framework: _framework }) => {\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 })\n\n if (fromCode.groupings) {\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.routePath,\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 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\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 sharedBindings: sharedBindings.size > 0 ? sharedBindings : undefined,\n compilerPlugins: getReferenceRouteCompilerPlugins({\n targetFramework: userConfig.target,\n addHmr,\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 const includedCode = [\n 'createFileRoute(',\n 'createRootRoute(',\n 'createRootRouteWithContext(',\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: includedCode,\n },\n },\n handler(code, id) {\n const normalizedId = normalizePath(id)\n const generatorFileInfo =\n globalThis.TSR_ROUTES_BY_ID_MAP?.get(normalizedId)\n if (\n generatorFileInfo &&\n includedCode.some((included) => code.includes(included))\n ) {\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(compiler) {\n ROOT = process.cwd()\n initUserConfig()\n\n if (compiler.options.mode === 'production') {\n compiler.hooks.done.tap(PLUGIN_NAME, () => {\n console.info('✅ ' + PLUGIN_NAME + ': code-splitting done!')\n })\n }\n },\n\n webpack(compiler) {\n ROOT = process.cwd()\n initUserConfig()\n\n if (compiler.options.mode === 'production') {\n compiler.hooks.done.tap(PLUGIN_NAME, () => {\n console.info('✅ ' + PLUGIN_NAME + ': code-splitting done!')\n })\n }\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"],"names":["getConfig","defaultCodeSplitGroupings","debug","detectCodeSplitGroupingsFromRoute","splitGroupingsSchema","computeSharedBindings","compileCodeSplitReferenceRoute","getReferenceRouteCompilerPlugins","logDiff","tsrSplit","decodeIdentifier","splitRouteIdentNodes","compileCodeSplitVirtualRoute","tsrShared","normalizePath","config","frameworkPlugins","pathToFileURL","fileURLToPath","compileCodeSplitSharedRoute"],"mappings":";;;;;;;;;;AAgCA,MAAM,cAAc;AACpB,MAAM,4BACJ;AAYF,MAAM,sCAGF;AAAA,EACF,OAAO;AAAA,IACL;AAAA;AAAA,MAEE,aAAa,CAAC,oBAAoB,oBAAoB;AAAA,MACtD,KAAK;AAAA,MACL,OAAO;AAAA,IAAA;AAAA,IAET;AAAA;AAAA,MAEE,aAAa,CAAC,kBAAkB,gCAAgC;AAAA,MAChE,KAAK;AAAA,MACL,OAAO;AAAA,IAAA;AAAA,IAET;AAAA;AAAA,MAEE,aAAa,CAAC,yBAAyB,gCAAgC;AAAA,MACvE,KAAK;AAAA,MACL,OAAO;AAAA,IAAA;AAAA,EACT;AAAA,EAEF,OAAO;AAAA,IACL;AAAA,MACE,aAAa,CAAC,OAAO;AAAA,MACrB,KAAK;AAAA,MACL,OAAO;AAAA,IAAA;AAAA,EACT;AAEJ;AAEO,MAAM,oCAET,CA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C/C;AAEA,iBAAO;AAAA,QACT;AAAA,MAAA;AAAA,MAGF,MAAM;AAAA,QACJ,mBAAmB,aAAa;AAC9B,cAAI,WAAW,QAAQ,MAAM,iBAAiB;AAC5C,mBAAO,WAAW,OAAO,KAAK,oBAAoB,YAAY;AAAA,UAChE;AACA,iBAAO;AAAA,QACT;AAAA,MAAA;AAAA,IACF;AAAA,EACF;AAEJ;;"}
|
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
3
3
|
const routerUtils = require("@tanstack/router-utils");
|
|
4
|
+
const compilers = require("./code-splitter/compilers.cjs");
|
|
5
|
+
const frameworkPlugins = require("./code-splitter/plugins/framework-plugins.cjs");
|
|
4
6
|
const routeHmrStatement = require("./route-hmr-statement.cjs");
|
|
5
7
|
const utils = require("./utils.cjs");
|
|
6
8
|
const config = require("./config.cjs");
|
|
@@ -29,6 +31,27 @@ const unpluginRouterHmrFactory = (options = {}) => {
|
|
|
29
31
|
return null;
|
|
30
32
|
}
|
|
31
33
|
if (utils.debug) console.info("Adding HMR handling to route ", normalizedId);
|
|
34
|
+
if (userConfig.target === "react") {
|
|
35
|
+
const compiled = compilers.compileCodeSplitReferenceRoute({
|
|
36
|
+
code,
|
|
37
|
+
filename: normalizedId,
|
|
38
|
+
id: normalizedId,
|
|
39
|
+
addHmr: true,
|
|
40
|
+
codeSplitGroupings: [],
|
|
41
|
+
targetFramework: "react",
|
|
42
|
+
compilerPlugins: frameworkPlugins.getReferenceRouteCompilerPlugins({
|
|
43
|
+
targetFramework: "react",
|
|
44
|
+
addHmr: true
|
|
45
|
+
})
|
|
46
|
+
});
|
|
47
|
+
if (compiled) {
|
|
48
|
+
if (utils.debug) {
|
|
49
|
+
routerUtils.logDiff(code, compiled.code);
|
|
50
|
+
console.log("Output:\n", compiled.code + "\n\n");
|
|
51
|
+
}
|
|
52
|
+
return compiled;
|
|
53
|
+
}
|
|
54
|
+
}
|
|
32
55
|
const ast = routerUtils.parseAst({ code });
|
|
33
56
|
ast.program.body.push(routeHmrStatement.routeHmrStatement);
|
|
34
57
|
const result = routerUtils.generateFromAst(ast, {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"router-hmr-plugin.cjs","sources":["../../../src/core/router-hmr-plugin.ts"],"sourcesContent":["import { generateFromAst, logDiff, parseAst } from '@tanstack/router-utils'\nimport { routeHmrStatement } from './route-hmr-statement'\nimport { debug, normalizePath } from './utils'\nimport { getConfig } from './config'\nimport type { UnpluginFactory } from 'unplugin'\nimport type { Config } from './config'\n\n/**\n * This plugin adds HMR support for file routes.\n * It is only added to the composed plugin in dev when autoCodeSplitting is disabled, since the code splitting plugin\n * handles HMR for code-split routes itself.\n */\n\nconst includeCode = [\n 'createFileRoute(',\n 'createRootRoute(',\n 'createRootRouteWithContext(',\n]\nexport const unpluginRouterHmrFactory: UnpluginFactory<\n Partial<Config> | undefined\n> = (options = {}) => {\n let ROOT: string = process.cwd()\n let userConfig = options as Config\n\n return {\n name: 'tanstack-router:hmr',\n enforce: 'pre',\n transform: {\n filter: {\n // this is necessary for webpack / rspack to avoid matching .html files\n id: /\\.(m|c)?(j|t)sx?$/,\n code: {\n include: includeCode,\n },\n },\n handler(code, id) {\n const normalizedId = normalizePath(id)\n if (!globalThis.TSR_ROUTES_BY_ID_MAP?.has(normalizedId)) {\n return null\n }\n\n if (debug) console.info('Adding HMR handling to route ', normalizedId)\n\n const ast = parseAst({ code })\n ast.program.body.push(routeHmrStatement)\n const result = generateFromAst(ast, {\n sourceMaps: true,\n filename: normalizedId,\n sourceFileName: normalizedId,\n })\n if (debug) {\n logDiff(code, result.code)\n console.log('Output:\\n', result.code + '\\n\\n')\n }\n return result\n },\n },\n vite: {\n configResolved(config) {\n ROOT = config.root\n userConfig = getConfig(options, ROOT)\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}\n"],"names":["normalizePath","debug","parseAst","routeHmrStatement","generateFromAst","
|
|
1
|
+
{"version":3,"file":"router-hmr-plugin.cjs","sources":["../../../src/core/router-hmr-plugin.ts"],"sourcesContent":["import { generateFromAst, logDiff, parseAst } from '@tanstack/router-utils'\nimport { compileCodeSplitReferenceRoute } from './code-splitter/compilers'\nimport { getReferenceRouteCompilerPlugins } from './code-splitter/plugins/framework-plugins'\nimport { routeHmrStatement } from './route-hmr-statement'\nimport { debug, normalizePath } from './utils'\nimport { getConfig } from './config'\nimport type { UnpluginFactory } from 'unplugin'\nimport type { Config } from './config'\n\n/**\n * This plugin adds HMR support for file routes.\n * It is only added to the composed plugin in dev when autoCodeSplitting is disabled, since the code splitting plugin\n * handles HMR for code-split routes itself.\n */\n\nconst includeCode = [\n 'createFileRoute(',\n 'createRootRoute(',\n 'createRootRouteWithContext(',\n]\nexport const unpluginRouterHmrFactory: UnpluginFactory<\n Partial<Config> | undefined\n> = (options = {}) => {\n let ROOT: string = process.cwd()\n let userConfig = options as Config\n\n return {\n name: 'tanstack-router:hmr',\n enforce: 'pre',\n transform: {\n filter: {\n // this is necessary for webpack / rspack to avoid matching .html files\n id: /\\.(m|c)?(j|t)sx?$/,\n code: {\n include: includeCode,\n },\n },\n handler(code, id) {\n const normalizedId = normalizePath(id)\n if (!globalThis.TSR_ROUTES_BY_ID_MAP?.has(normalizedId)) {\n return null\n }\n\n if (debug) console.info('Adding HMR handling to route ', normalizedId)\n\n if (userConfig.target === 'react') {\n const compiled = compileCodeSplitReferenceRoute({\n code,\n filename: normalizedId,\n id: normalizedId,\n addHmr: true,\n codeSplitGroupings: [],\n targetFramework: 'react',\n compilerPlugins: getReferenceRouteCompilerPlugins({\n targetFramework: 'react',\n addHmr: true,\n }),\n })\n\n if (compiled) {\n if (debug) {\n logDiff(code, compiled.code)\n console.log('Output:\\n', compiled.code + '\\n\\n')\n }\n\n return compiled\n }\n }\n\n const ast = parseAst({ code })\n ast.program.body.push(routeHmrStatement)\n const result = generateFromAst(ast, {\n sourceMaps: true,\n filename: normalizedId,\n sourceFileName: normalizedId,\n })\n if (debug) {\n logDiff(code, result.code)\n console.log('Output:\\n', result.code + '\\n\\n')\n }\n return result\n },\n },\n vite: {\n configResolved(config) {\n ROOT = config.root\n userConfig = getConfig(options, ROOT)\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}\n"],"names":["normalizePath","debug","compileCodeSplitReferenceRoute","getReferenceRouteCompilerPlugins","logDiff","parseAst","routeHmrStatement","generateFromAst","config","getConfig"],"mappings":";;;;;;;;AAeA,MAAM,cAAc;AAAA,EAClB;AAAA,EACA;AAAA,EACA;AACF;AACO,MAAM,2BAET,CAAC,UAAU,OAAO;AACpB,MAAI,OAAe,QAAQ,IAAA;AAC3B,MAAI,aAAa;AAEjB,SAAO;AAAA,IACL,MAAM;AAAA,IACN,SAAS;AAAA,IACT,WAAW;AAAA,MACT,QAAQ;AAAA;AAAA,QAEN,IAAI;AAAA,QACJ,MAAM;AAAA,UACJ,SAAS;AAAA,QAAA;AAAA,MACX;AAAA,MAEF,QAAQ,MAAM,IAAI;AAChB,cAAM,eAAeA,MAAAA,cAAc,EAAE;AACrC,YAAI,CAAC,WAAW,sBAAsB,IAAI,YAAY,GAAG;AACvD,iBAAO;AAAA,QACT;AAEA,YAAIC,MAAAA,MAAO,SAAQ,KAAK,iCAAiC,YAAY;AAErE,YAAI,WAAW,WAAW,SAAS;AACjC,gBAAM,WAAWC,UAAAA,+BAA+B;AAAA,YAC9C;AAAA,YACA,UAAU;AAAA,YACV,IAAI;AAAA,YACJ,QAAQ;AAAA,YACR,oBAAoB,CAAA;AAAA,YACpB,iBAAiB;AAAA,YACjB,iBAAiBC,iBAAAA,iCAAiC;AAAA,cAChD,iBAAiB;AAAA,cACjB,QAAQ;AAAA,YAAA,CACT;AAAA,UAAA,CACF;AAED,cAAI,UAAU;AACZ,gBAAIF,aAAO;AACTG,kCAAQ,MAAM,SAAS,IAAI;AAC3B,sBAAQ,IAAI,aAAa,SAAS,OAAO,MAAM;AAAA,YACjD;AAEA,mBAAO;AAAA,UACT;AAAA,QACF;AAEA,cAAM,MAAMC,YAAAA,SAAS,EAAE,MAAM;AAC7B,YAAI,QAAQ,KAAK,KAAKC,kBAAAA,iBAAiB;AACvC,cAAM,SAASC,YAAAA,gBAAgB,KAAK;AAAA,UAClC,YAAY;AAAA,UACZ,UAAU;AAAA,UACV,gBAAgB;AAAA,QAAA,CACjB;AACD,YAAIN,aAAO;AACTG,8BAAQ,MAAM,OAAO,IAAI;AACzB,kBAAQ,IAAI,aAAa,OAAO,OAAO,MAAM;AAAA,QAC/C;AACA,eAAO;AAAA,MACT;AAAA,IAAA;AAAA,IAEF,MAAM;AAAA,MACJ,eAAeI,UAAQ;AACrB,eAAOA,SAAO;AACd,qBAAaC,OAAAA,UAAU,SAAS,IAAI;AAAA,MACtC;AAAA,MACA,mBAAmB,aAAa;AAC9B,YAAI,WAAW,QAAQ,MAAM,iBAAiB;AAC5C,iBAAO,WAAW,OAAO,KAAK,oBAAoB,YAAY;AAAA,QAChE;AACA,eAAO;AAAA,MACT;AAAA,IAAA;AAAA,EACF;AAEJ;;"}
|
package/dist/cjs/core/utils.cjs
CHANGED
|
@@ -1,9 +1,37 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
3
|
+
const t = require("@babel/types");
|
|
4
|
+
function _interopNamespaceDefault(e) {
|
|
5
|
+
const n = Object.create(null, { [Symbol.toStringTag]: { value: "Module" } });
|
|
6
|
+
if (e) {
|
|
7
|
+
for (const k in e) {
|
|
8
|
+
if (k !== "default") {
|
|
9
|
+
const d = Object.getOwnPropertyDescriptor(e, k);
|
|
10
|
+
Object.defineProperty(n, k, d.get ? d : {
|
|
11
|
+
enumerable: true,
|
|
12
|
+
get: () => e[k]
|
|
13
|
+
});
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
n.default = e;
|
|
18
|
+
return Object.freeze(n);
|
|
19
|
+
}
|
|
20
|
+
const t__namespace = /* @__PURE__ */ _interopNamespaceDefault(t);
|
|
3
21
|
const debug = process.env.TSR_VITE_DEBUG && ["true", "router-plugin"].includes(process.env.TSR_VITE_DEBUG);
|
|
4
22
|
function normalizePath(path) {
|
|
5
23
|
return path.replace(/\\/g, "/");
|
|
6
24
|
}
|
|
25
|
+
function getUniqueProgramIdentifier(programPath, baseName) {
|
|
26
|
+
let name = baseName;
|
|
27
|
+
let suffix = 2;
|
|
28
|
+
while (programPath.scope.hasBinding(name) || programPath.scope.hasGlobal(name)) {
|
|
29
|
+
name = `${baseName}${suffix}`;
|
|
30
|
+
suffix++;
|
|
31
|
+
}
|
|
32
|
+
return t__namespace.identifier(name);
|
|
33
|
+
}
|
|
7
34
|
exports.debug = debug;
|
|
35
|
+
exports.getUniqueProgramIdentifier = getUniqueProgramIdentifier;
|
|
8
36
|
exports.normalizePath = normalizePath;
|
|
9
37
|
//# sourceMappingURL=utils.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"utils.cjs","sources":["../../../src/core/utils.ts"],"sourcesContent":["
|
|
1
|
+
{"version":3,"file":"utils.cjs","sources":["../../../src/core/utils.ts"],"sourcesContent":["import * as t from '@babel/types'\nimport type babel from '@babel/core'\n\nexport const debug =\n process.env.TSR_VITE_DEBUG &&\n ['true', 'router-plugin'].includes(process.env.TSR_VITE_DEBUG)\n\n/**\n * Normalizes a file path by converting Windows backslashes to forward slashes.\n * This ensures consistent path handling across different bundlers and operating systems.\n *\n * The route generator stores paths with forward slashes, but rspack/webpack on Windows\n * pass native paths with backslashes to transform handlers.\n */\nexport function normalizePath(path: string): string {\n return path.replace(/\\\\/g, '/')\n}\n\nexport function getUniqueProgramIdentifier(\n programPath: babel.NodePath<t.Program>,\n baseName: string,\n): t.Identifier {\n let name = baseName\n let suffix = 2\n\n while (\n programPath.scope.hasBinding(name) ||\n programPath.scope.hasGlobal(name)\n ) {\n name = `${baseName}${suffix}`\n suffix++\n }\n\n return t.identifier(name)\n}\n"],"names":["t"],"mappings":";;;;;;;;;;;;;;;;;;;;AAGO,MAAM,QACX,QAAQ,IAAI,kBACZ,CAAC,QAAQ,eAAe,EAAE,SAAS,QAAQ,IAAI,cAAc;AASxD,SAAS,cAAc,MAAsB;AAClD,SAAO,KAAK,QAAQ,OAAO,GAAG;AAChC;AAEO,SAAS,2BACd,aACA,UACc;AACd,MAAI,OAAO;AACX,MAAI,SAAS;AAEb,SACE,YAAY,MAAM,WAAW,IAAI,KACjC,YAAY,MAAM,UAAU,IAAI,GAChC;AACA,WAAO,GAAG,QAAQ,GAAG,MAAM;AAC3B;AAAA,EACF;AAEA,SAAOA,aAAE,WAAW,IAAI;AAC1B;;;;"}
|
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { default as babel } from '@babel/core';
|
|
2
|
+
import * as t from '@babel/types';
|
|
1
3
|
export declare const debug: boolean | "" | undefined;
|
|
2
4
|
/**
|
|
3
5
|
* Normalizes a file path by converting Windows backslashes to forward slashes.
|
|
@@ -7,3 +9,4 @@ export declare const debug: boolean | "" | undefined;
|
|
|
7
9
|
* pass native paths with backslashes to transform handlers.
|
|
8
10
|
*/
|
|
9
11
|
export declare function normalizePath(path: string): string;
|
|
12
|
+
export declare function getUniqueProgramIdentifier(programPath: babel.NodePath<t.Program>, baseName: string): t.Identifier;
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { ReferenceRouteCompilerPlugin } from './plugins.js';
|
|
1
2
|
import { GeneratorResult, ParseAstOptions } from '@tanstack/router-utils';
|
|
2
3
|
import { CodeSplitGroupings, SplitRouteIdentNodes } from '../constants.js';
|
|
3
4
|
import { Config, DeletableNodes } from '../config.js';
|
|
@@ -80,6 +81,7 @@ export declare function compileCodeSplitReferenceRoute(opts: ParseAstOptions & {
|
|
|
80
81
|
id: string;
|
|
81
82
|
addHmr?: boolean;
|
|
82
83
|
sharedBindings?: Set<string>;
|
|
84
|
+
compilerPlugins?: Array<ReferenceRouteCompilerPlugin>;
|
|
83
85
|
}): GeneratorResult | null;
|
|
84
86
|
export declare function compileCodeSplitVirtualRoute(opts: ParseAstOptions & {
|
|
85
87
|
splitTargets: Array<SplitRouteIdentNodes>;
|
|
@@ -447,6 +447,20 @@ function compileCodeSplitReferenceRoute(opts) {
|
|
|
447
447
|
);
|
|
448
448
|
}
|
|
449
449
|
if (!splittableCreateRouteFns.includes(createRouteFn)) {
|
|
450
|
+
const insertionPath = path.getStatementParent() ?? path;
|
|
451
|
+
opts.compilerPlugins?.forEach((plugin) => {
|
|
452
|
+
const pluginResult = plugin.onUnsplittableRoute?.({
|
|
453
|
+
programPath,
|
|
454
|
+
callExpressionPath: path,
|
|
455
|
+
insertionPath,
|
|
456
|
+
routeOptions,
|
|
457
|
+
createRouteFn,
|
|
458
|
+
opts
|
|
459
|
+
});
|
|
460
|
+
if (pluginResult?.modified) {
|
|
461
|
+
modified = true;
|
|
462
|
+
}
|
|
463
|
+
});
|
|
450
464
|
if (opts.addHmr && !hmrAdded) {
|
|
451
465
|
programPath.pushContainer("body", routeHmrStatement);
|
|
452
466
|
modified = true;
|