@tanstack/router-generator 1.131.5 → 1.132.0-alpha.0
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/config.cjs +1 -2
- package/dist/cjs/config.cjs.map +1 -1
- package/dist/cjs/filesystem/physical/getRouteNodes.cjs.map +1 -1
- package/dist/cjs/filesystem/virtual/config.cjs.map +1 -1
- package/dist/cjs/filesystem/virtual/getRouteNodes.cjs +2 -2
- package/dist/cjs/filesystem/virtual/getRouteNodes.cjs.map +1 -1
- package/dist/cjs/filesystem/virtual/loadConfigFile.cjs.map +1 -1
- package/dist/cjs/generator.cjs +22 -45
- package/dist/cjs/generator.cjs.map +1 -1
- package/dist/cjs/logger.cjs.map +1 -1
- package/dist/cjs/plugin/default-generator-plugin.cjs +3 -10
- package/dist/cjs/plugin/default-generator-plugin.cjs.map +1 -1
- package/dist/cjs/template.cjs.map +1 -1
- package/dist/cjs/transform/default-transform-plugin.cjs +1 -2
- package/dist/cjs/transform/default-transform-plugin.cjs.map +1 -1
- package/dist/cjs/transform/transform.cjs +7 -9
- package/dist/cjs/transform/transform.cjs.map +1 -1
- package/dist/cjs/transform/utils.cjs.map +1 -1
- package/dist/cjs/utils.cjs +16 -35
- package/dist/cjs/utils.cjs.map +1 -1
- package/dist/esm/config.js +1 -2
- package/dist/esm/config.js.map +1 -1
- package/dist/esm/filesystem/physical/getRouteNodes.js.map +1 -1
- package/dist/esm/filesystem/virtual/config.js.map +1 -1
- package/dist/esm/filesystem/virtual/getRouteNodes.js +2 -2
- package/dist/esm/filesystem/virtual/getRouteNodes.js.map +1 -1
- package/dist/esm/filesystem/virtual/loadConfigFile.js.map +1 -1
- package/dist/esm/generator.js +22 -45
- package/dist/esm/generator.js.map +1 -1
- package/dist/esm/logger.js.map +1 -1
- package/dist/esm/plugin/default-generator-plugin.js +3 -10
- package/dist/esm/plugin/default-generator-plugin.js.map +1 -1
- package/dist/esm/template.js.map +1 -1
- package/dist/esm/transform/default-transform-plugin.js +1 -2
- package/dist/esm/transform/default-transform-plugin.js.map +1 -1
- package/dist/esm/transform/transform.js +7 -9
- package/dist/esm/transform/transform.js.map +1 -1
- package/dist/esm/transform/utils.js.map +1 -1
- package/dist/esm/utils.js +16 -35
- package/dist/esm/utils.js.map +1 -1
- package/package.json +5 -5
package/dist/esm/logger.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"logger.js","sources":["../../src/logger.ts"],"sourcesContent":["export interface Logger {\n log: (...args: Array<any>) => void\n debug: (...args: Array<any>) => void\n info: (...args: Array<any>) => void\n warn: (...args: Array<any>) => void\n error: (...args: Array<any>) => void\n}\n\nexport function logging(config: { disabled: boolean }): Logger {\n function stripEmojis(str: string) {\n return str.replace(\n /[\\p{Emoji_Presentation}\\p{Extended_Pictographic}]/gu,\n '',\n )\n }\n\n function formatLogArgs(args: Array<any>): Array<any> {\n if (process.env.CI) {\n return args.map((arg) =>\n typeof arg === 'string' ? stripEmojis(arg) : arg,\n )\n }\n return args\n }\n\n return {\n log: (...args: Array<any>) => {\n if (!config.disabled) console.log(...formatLogArgs(args))\n },\n debug: (...args: Array<any>) => {\n if (!config.disabled) console.debug(...formatLogArgs(args))\n },\n info: (...args: Array<any>) => {\n if (!config.disabled) console.info(...formatLogArgs(args))\n },\n warn: (...args: Array<any>) => {\n if (!config.disabled) console.warn(...formatLogArgs(args))\n },\n error: (...args: Array<any>) => {\n if (!config.disabled) console.error(...formatLogArgs(args))\n },\n }\n}\n"],"names":[],"mappings":"AAQO,SAAS,QAAQ,QAAuC;AAC7D,WAAS,YAAY,KAAa;AAChC,WAAO,IAAI;AAAA,MACT;AAAA,MACA;AAAA,
|
|
1
|
+
{"version":3,"file":"logger.js","sources":["../../src/logger.ts"],"sourcesContent":["export interface Logger {\n log: (...args: Array<any>) => void\n debug: (...args: Array<any>) => void\n info: (...args: Array<any>) => void\n warn: (...args: Array<any>) => void\n error: (...args: Array<any>) => void\n}\n\nexport function logging(config: { disabled: boolean }): Logger {\n function stripEmojis(str: string) {\n return str.replace(\n /[\\p{Emoji_Presentation}\\p{Extended_Pictographic}]/gu,\n '',\n )\n }\n\n function formatLogArgs(args: Array<any>): Array<any> {\n if (process.env.CI) {\n return args.map((arg) =>\n typeof arg === 'string' ? stripEmojis(arg) : arg,\n )\n }\n return args\n }\n\n return {\n log: (...args: Array<any>) => {\n if (!config.disabled) console.log(...formatLogArgs(args))\n },\n debug: (...args: Array<any>) => {\n if (!config.disabled) console.debug(...formatLogArgs(args))\n },\n info: (...args: Array<any>) => {\n if (!config.disabled) console.info(...formatLogArgs(args))\n },\n warn: (...args: Array<any>) => {\n if (!config.disabled) console.warn(...formatLogArgs(args))\n },\n error: (...args: Array<any>) => {\n if (!config.disabled) console.error(...formatLogArgs(args))\n },\n }\n}\n"],"names":[],"mappings":"AAQO,SAAS,QAAQ,QAAuC;AAC7D,WAAS,YAAY,KAAa;AAChC,WAAO,IAAI;AAAA,MACT;AAAA,MACA;AAAA,IAAA;AAAA,EAEJ;AAEA,WAAS,cAAc,MAA8B;AACnD,QAAI,QAAQ,IAAI,IAAI;AAClB,aAAO,KAAK;AAAA,QAAI,CAAC,QACf,OAAO,QAAQ,WAAW,YAAY,GAAG,IAAI;AAAA,MAAA;AAAA,IAEjD;AACA,WAAO;AAAA,EACT;AAEA,SAAO;AAAA,IACL,KAAK,IAAI,SAAqB;AAC5B,UAAI,CAAC,OAAO,SAAU,SAAQ,IAAI,GAAG,cAAc,IAAI,CAAC;AAAA,IAC1D;AAAA,IACA,OAAO,IAAI,SAAqB;AAC9B,UAAI,CAAC,OAAO,SAAU,SAAQ,MAAM,GAAG,cAAc,IAAI,CAAC;AAAA,IAC5D;AAAA,IACA,MAAM,IAAI,SAAqB;AAC7B,UAAI,CAAC,OAAO,SAAU,SAAQ,KAAK,GAAG,cAAc,IAAI,CAAC;AAAA,IAC3D;AAAA,IACA,MAAM,IAAI,SAAqB;AAC7B,UAAI,CAAC,OAAO,SAAU,SAAQ,KAAK,GAAG,cAAc,IAAI,CAAC;AAAA,IAC3D;AAAA,IACA,OAAO,IAAI,SAAqB;AAC9B,UAAI,CAAC,OAAO,SAAU,SAAQ,MAAM,GAAG,cAAc,IAAI,CAAC;AAAA,IAC5D;AAAA,EAAA;AAEJ;"}
|
|
@@ -6,7 +6,6 @@ function defaultGeneratorPlugin() {
|
|
|
6
6
|
name: "default",
|
|
7
7
|
transformPlugin: defaultTransformPlugin,
|
|
8
8
|
imports: (opts) => {
|
|
9
|
-
var _a;
|
|
10
9
|
const imports = [];
|
|
11
10
|
if (opts.acc.routeNodes.some((n) => n.isVirtual)) {
|
|
12
11
|
imports.push({
|
|
@@ -26,10 +25,7 @@ function defaultGeneratorPlugin() {
|
|
|
26
25
|
typeImport.specifiers.push({ imported: "CreateFileRoute" });
|
|
27
26
|
}
|
|
28
27
|
if (opts.sortedRouteNodes.some(
|
|
29
|
-
(node) =>
|
|
30
|
-
var _a2;
|
|
31
|
-
return ((_a2 = opts.acc.routePiecesByPath[node.routePath]) == null ? void 0 : _a2.lazy) && isRouteNodeValidForAugmentation(node);
|
|
32
|
-
}
|
|
28
|
+
(node) => opts.acc.routePiecesByPath[node.routePath]?.lazy && isRouteNodeValidForAugmentation(node)
|
|
33
29
|
)) {
|
|
34
30
|
typeImport.specifiers.push({ imported: "CreateLazyFileRoute" });
|
|
35
31
|
}
|
|
@@ -40,7 +36,7 @@ function defaultGeneratorPlugin() {
|
|
|
40
36
|
}
|
|
41
37
|
const hasMatchingRouteFiles = opts.acc.routeNodes.length > 0;
|
|
42
38
|
if (hasMatchingRouteFiles) {
|
|
43
|
-
if (!
|
|
39
|
+
if (!opts.rootRouteNode.exports?.includes(EXPORT_NAME)) {
|
|
44
40
|
imports.push({
|
|
45
41
|
specifiers: [{ imported: "createRootRoute" }],
|
|
46
42
|
source: opts.generator.targetTemplate.fullPkg
|
|
@@ -64,10 +60,7 @@ function defaultGeneratorPlugin() {
|
|
|
64
60
|
}
|
|
65
61
|
checkRouteFullPathUniqueness(
|
|
66
62
|
routeTree.sortedRouteNodes.filter(
|
|
67
|
-
(d) =>
|
|
68
|
-
var _a;
|
|
69
|
-
return d.children === void 0 && "lazy" !== d._fsRouteType && ((_a = d.exports) == null ? void 0 : _a.includes(EXPORT_NAME));
|
|
70
|
-
}
|
|
63
|
+
(d) => d.children === void 0 && "lazy" !== d._fsRouteType && d.exports?.includes(EXPORT_NAME)
|
|
71
64
|
),
|
|
72
65
|
generator.config
|
|
73
66
|
);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"default-generator-plugin.js","sources":["../../../src/plugin/default-generator-plugin.ts"],"sourcesContent":["import { defaultTransformPlugin } from '../transform/default-transform-plugin'\nimport {\n checkRouteFullPathUniqueness,\n isRouteNodeValidForAugmentation,\n} from '../utils'\nimport type { ImportDeclaration } from '../types'\nimport type { GeneratorPluginWithTransform } from './types'\n\nconst EXPORT_NAME = 'Route'\nexport function defaultGeneratorPlugin(): GeneratorPluginWithTransform {\n return {\n name: 'default',\n transformPlugin: defaultTransformPlugin,\n imports: (opts) => {\n const imports: Array<ImportDeclaration> = []\n if (opts.acc.routeNodes.some((n) => n.isVirtual)) {\n imports.push({\n specifiers: [{ imported: 'createFileRoute' }],\n source: opts.generator.targetTemplate.fullPkg,\n })\n }\n if (opts.generator.config.verboseFileRoutes === false) {\n const typeImport: ImportDeclaration = {\n specifiers: [],\n source: opts.generator.targetTemplate.fullPkg,\n importKind: 'type',\n }\n if (\n opts.sortedRouteNodes.some(\n (d) =>\n isRouteNodeValidForAugmentation(d) && d._fsRouteType !== 'lazy',\n )\n ) {\n typeImport.specifiers.push({ imported: 'CreateFileRoute' })\n }\n if (\n opts.sortedRouteNodes.some(\n (node) =>\n opts.acc.routePiecesByPath[node.routePath!]?.lazy &&\n isRouteNodeValidForAugmentation(node),\n )\n ) {\n typeImport.specifiers.push({ imported: 'CreateLazyFileRoute' })\n }\n\n if (typeImport.specifiers.length > 0) {\n typeImport.specifiers.push({ imported: 'FileRoutesByPath' })\n imports.push(typeImport)\n }\n }\n const hasMatchingRouteFiles = opts.acc.routeNodes.length > 0\n if (hasMatchingRouteFiles) {\n // needs a virtual root route\n if (!opts.rootRouteNode.exports?.includes(EXPORT_NAME)) {\n imports.push({\n specifiers: [{ imported: 'createRootRoute' }],\n source: opts.generator.targetTemplate.fullPkg,\n })\n }\n }\n return imports\n },\n moduleAugmentation: ({ generator }) => ({\n module: generator.targetTemplate.fullPkg,\n interfaceName: 'FileRoutesByPath',\n }),\n onRouteTreesChanged: ({ routeTrees, generator }) => {\n const routeTree = routeTrees.find(\n (tree) => tree.exportName === EXPORT_NAME,\n )\n if (!routeTree) {\n throw new Error(\n 'No route tree found with export name \"Route\". Please ensure your routes are correctly defined.',\n )\n }\n checkRouteFullPathUniqueness(\n routeTree.sortedRouteNodes.filter(\n (d) =>\n d.children === undefined &&\n 'lazy' !== d._fsRouteType &&\n d.exports?.includes(EXPORT_NAME),\n ),\n generator.config,\n )\n },\n routeModuleAugmentation: ({ routeNode }) => {\n if (routeNode._fsRouteType === 'lazy') {\n return `const createLazyFileRoute: CreateLazyFileRoute<FileRoutesByPath['${routeNode.routePath}']['preLoaderRoute']>`\n } else {\n return `const createFileRoute: CreateFileRoute<'${routeNode.routePath}',\n FileRoutesByPath['${routeNode.routePath}']['parentRoute'],\n FileRoutesByPath['${routeNode.routePath}']['id'],\n FileRoutesByPath['${routeNode.routePath}']['path'],\n FileRoutesByPath['${routeNode.routePath}']['fullPath']\n >\n `\n }\n },\n createRootRouteCode: () => `createRootRoute()`,\n createVirtualRouteCode: ({ node }) =>\n `createFileRoute('${node.routePath}')()`,\n config: ({ sortedRouteNodes }) => {\n const hasMatchingRouteFiles = sortedRouteNodes.length > 0\n return {\n virtualRootRoute: hasMatchingRouteFiles,\n }\n },\n }\n}\n"],"names":[
|
|
1
|
+
{"version":3,"file":"default-generator-plugin.js","sources":["../../../src/plugin/default-generator-plugin.ts"],"sourcesContent":["import { defaultTransformPlugin } from '../transform/default-transform-plugin'\nimport {\n checkRouteFullPathUniqueness,\n isRouteNodeValidForAugmentation,\n} from '../utils'\nimport type { ImportDeclaration } from '../types'\nimport type { GeneratorPluginWithTransform } from './types'\n\nconst EXPORT_NAME = 'Route'\nexport function defaultGeneratorPlugin(): GeneratorPluginWithTransform {\n return {\n name: 'default',\n transformPlugin: defaultTransformPlugin,\n imports: (opts) => {\n const imports: Array<ImportDeclaration> = []\n if (opts.acc.routeNodes.some((n) => n.isVirtual)) {\n imports.push({\n specifiers: [{ imported: 'createFileRoute' }],\n source: opts.generator.targetTemplate.fullPkg,\n })\n }\n if (opts.generator.config.verboseFileRoutes === false) {\n const typeImport: ImportDeclaration = {\n specifiers: [],\n source: opts.generator.targetTemplate.fullPkg,\n importKind: 'type',\n }\n if (\n opts.sortedRouteNodes.some(\n (d) =>\n isRouteNodeValidForAugmentation(d) && d._fsRouteType !== 'lazy',\n )\n ) {\n typeImport.specifiers.push({ imported: 'CreateFileRoute' })\n }\n if (\n opts.sortedRouteNodes.some(\n (node) =>\n opts.acc.routePiecesByPath[node.routePath!]?.lazy &&\n isRouteNodeValidForAugmentation(node),\n )\n ) {\n typeImport.specifiers.push({ imported: 'CreateLazyFileRoute' })\n }\n\n if (typeImport.specifiers.length > 0) {\n typeImport.specifiers.push({ imported: 'FileRoutesByPath' })\n imports.push(typeImport)\n }\n }\n const hasMatchingRouteFiles = opts.acc.routeNodes.length > 0\n if (hasMatchingRouteFiles) {\n // needs a virtual root route\n if (!opts.rootRouteNode.exports?.includes(EXPORT_NAME)) {\n imports.push({\n specifiers: [{ imported: 'createRootRoute' }],\n source: opts.generator.targetTemplate.fullPkg,\n })\n }\n }\n return imports\n },\n moduleAugmentation: ({ generator }) => ({\n module: generator.targetTemplate.fullPkg,\n interfaceName: 'FileRoutesByPath',\n }),\n onRouteTreesChanged: ({ routeTrees, generator }) => {\n const routeTree = routeTrees.find(\n (tree) => tree.exportName === EXPORT_NAME,\n )\n if (!routeTree) {\n throw new Error(\n 'No route tree found with export name \"Route\". Please ensure your routes are correctly defined.',\n )\n }\n checkRouteFullPathUniqueness(\n routeTree.sortedRouteNodes.filter(\n (d) =>\n d.children === undefined &&\n 'lazy' !== d._fsRouteType &&\n d.exports?.includes(EXPORT_NAME),\n ),\n generator.config,\n )\n },\n routeModuleAugmentation: ({ routeNode }) => {\n if (routeNode._fsRouteType === 'lazy') {\n return `const createLazyFileRoute: CreateLazyFileRoute<FileRoutesByPath['${routeNode.routePath}']['preLoaderRoute']>`\n } else {\n return `const createFileRoute: CreateFileRoute<'${routeNode.routePath}',\n FileRoutesByPath['${routeNode.routePath}']['parentRoute'],\n FileRoutesByPath['${routeNode.routePath}']['id'],\n FileRoutesByPath['${routeNode.routePath}']['path'],\n FileRoutesByPath['${routeNode.routePath}']['fullPath']\n >\n `\n }\n },\n createRootRouteCode: () => `createRootRoute()`,\n createVirtualRouteCode: ({ node }) =>\n `createFileRoute('${node.routePath}')()`,\n config: ({ sortedRouteNodes }) => {\n const hasMatchingRouteFiles = sortedRouteNodes.length > 0\n return {\n virtualRootRoute: hasMatchingRouteFiles,\n }\n },\n }\n}\n"],"names":[],"mappings":";;AAQA,MAAM,cAAc;AACb,SAAS,yBAAuD;AACrE,SAAO;AAAA,IACL,MAAM;AAAA,IACN,iBAAiB;AAAA,IACjB,SAAS,CAAC,SAAS;AACjB,YAAM,UAAoC,CAAA;AAC1C,UAAI,KAAK,IAAI,WAAW,KAAK,CAAC,MAAM,EAAE,SAAS,GAAG;AAChD,gBAAQ,KAAK;AAAA,UACX,YAAY,CAAC,EAAE,UAAU,mBAAmB;AAAA,UAC5C,QAAQ,KAAK,UAAU,eAAe;AAAA,QAAA,CACvC;AAAA,MACH;AACA,UAAI,KAAK,UAAU,OAAO,sBAAsB,OAAO;AACrD,cAAM,aAAgC;AAAA,UACpC,YAAY,CAAA;AAAA,UACZ,QAAQ,KAAK,UAAU,eAAe;AAAA,UACtC,YAAY;AAAA,QAAA;AAEd,YACE,KAAK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AC,EAAE,gBAAgB;AAC1C,UAAI,UAAU,iBAAiB,QAAQ;AACrC,eAAO,oEAAoE,UAAU,SAAS;AAAA,MAChG,OAAO;AACL,eAAO,2CAA2C,UAAU,SAAS;AAAA,gCAC7C,UAAU,SAAS;AAAA,gCACnB,UAAU,SAAS;AAAA,gCACnB,UAAU,SAAS;AAAA,gCACnB,UAAU,SAAS;AAAA;AAAA;AAAA,MAG7C;AAAA,IACF;AAAA,IACA,qBAAqB,MAAM;AAAA,IAC3B,wBAAwB,CAAC,EAAE,WACzB,oBAAoB,KAAK,SAAS;AAAA,IACpC,QAAQ,CAAC,EAAE,uBAAuB;AAChC,YAAM,wBAAwB,iBAAiB,SAAS;AACxD,aAAO;AAAA,QACL,kBAAkB;AAAA,MAAA;AAAA,IAEtB;AAAA,EAAA;AAEJ;"}
|
package/dist/esm/template.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"template.js","sources":["../../src/template.ts"],"sourcesContent":["import { format } from './utils'\nimport type { Config } from './config'\n\ntype TemplateTag = 'tsrImports' | 'tsrPath' | 'tsrExportStart' | 'tsrExportEnd'\n\nexport function fillTemplate(\n config: Config,\n template: string,\n values: Record<TemplateTag, string>,\n) {\n const replaced = template.replace(\n /%%(\\w+)%%/g,\n (_, key) => values[key as TemplateTag] || '',\n )\n return format(replaced, config)\n}\n\nexport type TargetTemplate = {\n fullPkg: string\n subPkg: string\n rootRoute: {\n template: () => string\n imports: {\n tsrImports: () => string\n tsrExportStart: () => string\n tsrExportEnd: () => string\n }\n }\n route: {\n template: () => string\n imports: {\n tsrImports: () => string\n tsrExportStart: (routePath: string) => string\n tsrExportEnd: () => string\n }\n }\n lazyRoute: {\n template: () => string\n imports: {\n tsrImports: () => string\n tsrExportStart: (routePath: string) => string\n tsrExportEnd: () => string\n }\n }\n}\n\nexport function getTargetTemplate(config: Config): TargetTemplate {\n const target = config.target\n switch (target) {\n case 'react':\n return {\n fullPkg: '@tanstack/react-router',\n subPkg: 'react-router',\n rootRoute: {\n template: () =>\n [\n 'import * as React from \"react\"\\n',\n '%%tsrImports%%',\n '\\n\\n',\n '%%tsrExportStart%%{\\n component: RootComponent\\n }%%tsrExportEnd%%\\n\\n',\n 'function RootComponent() { return (<React.Fragment><div>Hello \"%%tsrPath%%\"!</div><Outlet /></React.Fragment>) };\\n',\n ].join(''),\n imports: {\n tsrImports: () =>\n \"import { Outlet, createRootRoute } from '@tanstack/react-router';\",\n tsrExportStart: () => 'export const Route = createRootRoute(',\n tsrExportEnd: () => ');',\n },\n },\n route: {\n template: () =>\n [\n '%%tsrImports%%',\n '\\n\\n',\n '%%tsrExportStart%%{\\n component: RouteComponent\\n }%%tsrExportEnd%%\\n\\n',\n 'function RouteComponent() { return <div>Hello \"%%tsrPath%%\"!</div> };\\n',\n ].join(''),\n imports: {\n tsrImports: () =>\n config.verboseFileRoutes === false\n ? ''\n : \"import { createFileRoute } from '@tanstack/react-router';\",\n tsrExportStart: (routePath) =>\n config.verboseFileRoutes === false\n ? 'export const Route = createFileRoute('\n : `export const Route = createFileRoute('${routePath}')(`,\n tsrExportEnd: () => ');',\n },\n },\n lazyRoute: {\n template: () =>\n [\n '%%tsrImports%%',\n '\\n\\n',\n '%%tsrExportStart%%{\\n component: RouteComponent\\n }%%tsrExportEnd%%\\n\\n',\n 'function RouteComponent() { return <div>Hello \"%%tsrPath%%\"!</div> };\\n',\n ].join(''),\n imports: {\n tsrImports: () =>\n config.verboseFileRoutes === false\n ? ''\n : \"import { createLazyFileRoute } from '@tanstack/react-router';\",\n tsrExportStart: (routePath) =>\n config.verboseFileRoutes === false\n ? 'export const Route = createLazyFileRoute('\n : `export const Route = createLazyFileRoute('${routePath}')(`,\n tsrExportEnd: () => ');',\n },\n },\n }\n case 'solid':\n return {\n fullPkg: '@tanstack/solid-router',\n subPkg: 'solid-router',\n rootRoute: {\n template: () =>\n [\n 'import * as Solid from \"solid-js\"\\n',\n '%%tsrImports%%',\n '\\n\\n',\n '%%tsrExportStart%%{\\n component: RootComponent\\n }%%tsrExportEnd%%\\n\\n',\n 'function RootComponent() { return (<><div>Hello \"%%tsrPath%%\"!</div><Outlet /></>) };\\n',\n ].join(''),\n imports: {\n tsrImports: () =>\n \"import { Outlet, createRootRoute } from '@tanstack/solid-router';\",\n tsrExportStart: () => 'export const Route = createRootRoute(',\n tsrExportEnd: () => ');',\n },\n },\n route: {\n template: () =>\n [\n '%%tsrImports%%',\n '\\n\\n',\n '%%tsrExportStart%%{\\n component: RouteComponent\\n }%%tsrExportEnd%%\\n\\n',\n 'function RouteComponent() { return <div>Hello \"%%tsrPath%%\"!</div> };\\n',\n ].join(''),\n imports: {\n tsrImports: () =>\n config.verboseFileRoutes === false\n ? ''\n : \"import { createFileRoute } from '@tanstack/solid-router';\",\n tsrExportStart: (routePath) =>\n config.verboseFileRoutes === false\n ? 'export const Route = createFileRoute('\n : `export const Route = createFileRoute('${routePath}')(`,\n tsrExportEnd: () => ');',\n },\n },\n lazyRoute: {\n template: () =>\n [\n '%%tsrImports%%',\n '\\n\\n',\n '%%tsrExportStart%%{\\n component: RouteComponent\\n }%%tsrExportEnd%%\\n\\n',\n 'function RouteComponent() { return <div>Hello \"%%tsrPath%%\"!</div> };\\n',\n ].join(''),\n imports: {\n tsrImports: () =>\n config.verboseFileRoutes === false\n ? ''\n : \"import { createLazyFileRoute } from '@tanstack/solid-router';\",\n\n tsrExportStart: (routePath) =>\n config.verboseFileRoutes === false\n ? 'export const Route = createLazyFileRoute('\n : `export const Route = createLazyFileRoute('${routePath}')(`,\n\n tsrExportEnd: () => ');',\n },\n },\n }\n default:\n throw new Error(`router-generator: Unknown target type: ${target}`)\n }\n}\n"],"names":[],"mappings":";
|
|
1
|
+
{"version":3,"file":"template.js","sources":["../../src/template.ts"],"sourcesContent":["import { format } from './utils'\nimport type { Config } from './config'\n\ntype TemplateTag = 'tsrImports' | 'tsrPath' | 'tsrExportStart' | 'tsrExportEnd'\n\nexport function fillTemplate(\n config: Config,\n template: string,\n values: Record<TemplateTag, string>,\n) {\n const replaced = template.replace(\n /%%(\\w+)%%/g,\n (_, key) => values[key as TemplateTag] || '',\n )\n return format(replaced, config)\n}\n\nexport type TargetTemplate = {\n fullPkg: string\n subPkg: string\n rootRoute: {\n template: () => string\n imports: {\n tsrImports: () => string\n tsrExportStart: () => string\n tsrExportEnd: () => string\n }\n }\n route: {\n template: () => string\n imports: {\n tsrImports: () => string\n tsrExportStart: (routePath: string) => string\n tsrExportEnd: () => string\n }\n }\n lazyRoute: {\n template: () => string\n imports: {\n tsrImports: () => string\n tsrExportStart: (routePath: string) => string\n tsrExportEnd: () => string\n }\n }\n}\n\nexport function getTargetTemplate(config: Config): TargetTemplate {\n const target = config.target\n switch (target) {\n case 'react':\n return {\n fullPkg: '@tanstack/react-router',\n subPkg: 'react-router',\n rootRoute: {\n template: () =>\n [\n 'import * as React from \"react\"\\n',\n '%%tsrImports%%',\n '\\n\\n',\n '%%tsrExportStart%%{\\n component: RootComponent\\n }%%tsrExportEnd%%\\n\\n',\n 'function RootComponent() { return (<React.Fragment><div>Hello \"%%tsrPath%%\"!</div><Outlet /></React.Fragment>) };\\n',\n ].join(''),\n imports: {\n tsrImports: () =>\n \"import { Outlet, createRootRoute } from '@tanstack/react-router';\",\n tsrExportStart: () => 'export const Route = createRootRoute(',\n tsrExportEnd: () => ');',\n },\n },\n route: {\n template: () =>\n [\n '%%tsrImports%%',\n '\\n\\n',\n '%%tsrExportStart%%{\\n component: RouteComponent\\n }%%tsrExportEnd%%\\n\\n',\n 'function RouteComponent() { return <div>Hello \"%%tsrPath%%\"!</div> };\\n',\n ].join(''),\n imports: {\n tsrImports: () =>\n config.verboseFileRoutes === false\n ? ''\n : \"import { createFileRoute } from '@tanstack/react-router';\",\n tsrExportStart: (routePath) =>\n config.verboseFileRoutes === false\n ? 'export const Route = createFileRoute('\n : `export const Route = createFileRoute('${routePath}')(`,\n tsrExportEnd: () => ');',\n },\n },\n lazyRoute: {\n template: () =>\n [\n '%%tsrImports%%',\n '\\n\\n',\n '%%tsrExportStart%%{\\n component: RouteComponent\\n }%%tsrExportEnd%%\\n\\n',\n 'function RouteComponent() { return <div>Hello \"%%tsrPath%%\"!</div> };\\n',\n ].join(''),\n imports: {\n tsrImports: () =>\n config.verboseFileRoutes === false\n ? ''\n : \"import { createLazyFileRoute } from '@tanstack/react-router';\",\n tsrExportStart: (routePath) =>\n config.verboseFileRoutes === false\n ? 'export const Route = createLazyFileRoute('\n : `export const Route = createLazyFileRoute('${routePath}')(`,\n tsrExportEnd: () => ');',\n },\n },\n }\n case 'solid':\n return {\n fullPkg: '@tanstack/solid-router',\n subPkg: 'solid-router',\n rootRoute: {\n template: () =>\n [\n 'import * as Solid from \"solid-js\"\\n',\n '%%tsrImports%%',\n '\\n\\n',\n '%%tsrExportStart%%{\\n component: RootComponent\\n }%%tsrExportEnd%%\\n\\n',\n 'function RootComponent() { return (<><div>Hello \"%%tsrPath%%\"!</div><Outlet /></>) };\\n',\n ].join(''),\n imports: {\n tsrImports: () =>\n \"import { Outlet, createRootRoute } from '@tanstack/solid-router';\",\n tsrExportStart: () => 'export const Route = createRootRoute(',\n tsrExportEnd: () => ');',\n },\n },\n route: {\n template: () =>\n [\n '%%tsrImports%%',\n '\\n\\n',\n '%%tsrExportStart%%{\\n component: RouteComponent\\n }%%tsrExportEnd%%\\n\\n',\n 'function RouteComponent() { return <div>Hello \"%%tsrPath%%\"!</div> };\\n',\n ].join(''),\n imports: {\n tsrImports: () =>\n config.verboseFileRoutes === false\n ? ''\n : \"import { createFileRoute } from '@tanstack/solid-router';\",\n tsrExportStart: (routePath) =>\n config.verboseFileRoutes === false\n ? 'export const Route = createFileRoute('\n : `export const Route = createFileRoute('${routePath}')(`,\n tsrExportEnd: () => ');',\n },\n },\n lazyRoute: {\n template: () =>\n [\n '%%tsrImports%%',\n '\\n\\n',\n '%%tsrExportStart%%{\\n component: RouteComponent\\n }%%tsrExportEnd%%\\n\\n',\n 'function RouteComponent() { return <div>Hello \"%%tsrPath%%\"!</div> };\\n',\n ].join(''),\n imports: {\n tsrImports: () =>\n config.verboseFileRoutes === false\n ? ''\n : \"import { createLazyFileRoute } from '@tanstack/solid-router';\",\n\n tsrExportStart: (routePath) =>\n config.verboseFileRoutes === false\n ? 'export const Route = createLazyFileRoute('\n : `export const Route = createLazyFileRoute('${routePath}')(`,\n\n tsrExportEnd: () => ');',\n },\n },\n }\n default:\n throw new Error(`router-generator: Unknown target type: ${target}`)\n }\n}\n"],"names":[],"mappings":";AAKO,SAAS,aACd,QACA,UACA,QACA;AACA,QAAM,WAAW,SAAS;AAAA,IACxB;AAAA,IACA,CAAC,GAAG,QAAQ,OAAO,GAAkB,KAAK;AAAA,EAAA;AAE5C,SAAO,OAAO,UAAU,MAAM;AAChC;AA+BO,SAAS,kBAAkB,QAAgC;AAChE,QAAM,SAAS,OAAO;AACtB,UAAQ,QAAA;AAAA,IACN,KAAK;AACH,aAAO;AAAA,QACL,SAAS;AAAA,QACT,QAAQ;AAAA,QACR,WAAW;AAAA,UACT,UAAU,MACR;AAAA,YACE;AAAA,YACA;AAAA,YACA;AAAA,YACA;AAAA,YACA;AAAA,UAAA,EACA,KAAK,EAAE;AAAA,UACX,SAAS;AAAA,YACP,YAAY,MACV;AAAA,YACF,gBAAgB,MAAM;AAAA,YACtB,cAAc,MAAM;AAAA,UAAA;AAAA,QACtB;AAAA,QAEF,OAAO;AAAA,UACL,UAAU,MACR;AAAA,YACE;AAAA,YACA;AAAA,YACA;AAAA,YACA;AAAA,UAAA,EACA,KAAK,EAAE;AAAA,UACX,SAAS;AAAA,YACP,YAAY,MACV,OAAO,sBAAsB,QACzB,KACA;AAAA,YACN,gBAAgB,CAAC,cACf,OAAO,sBAAsB,QACzB,0CACA,yCAAyC,SAAS;AAAA,YACxD,cAAc,MAAM;AAAA,UAAA;AAAA,QACtB;AAAA,QAEF,WAAW;AAAA,UACT,UAAU,MACR;AAAA,YACE;AAAA,YACA;AAAA,YACA;AAAA,YACA;AAAA,UAAA,EACA,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|
50
50
|
return imports;
|
|
51
51
|
},
|
|
52
52
|
onExportFound: ({ decl, ctx }) => {
|
|
53
|
-
var _a;
|
|
54
53
|
let appliedChanges = false;
|
|
55
|
-
if (
|
|
54
|
+
if (decl.init?.type === "CallExpression") {
|
|
56
55
|
const callExpression = decl.init;
|
|
57
56
|
let identifier;
|
|
58
57
|
if (callExpression.callee.type === "Identifier") {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"default-transform-plugin.js","sources":["../../../src/transform/default-transform-plugin.ts"],"sourcesContent":["import { types } from 'recast'\nimport { ensureStringArgument } from './utils'\nimport type { TransformImportsConfig, TransformPlugin } from './types'\n\nconst b = types.builders\n\nconst EXPORT_NAME = 'Route'\nexport const defaultTransformPlugin: TransformPlugin = {\n name: 'default-transform',\n exportName: EXPORT_NAME,\n imports: (ctx) => {\n const imports: TransformImportsConfig = {}\n const targetModule = `@tanstack/${ctx.target}-router`\n if (ctx.verboseFileRoutes === false) {\n imports.banned = [\n {\n source: targetModule,\n specifiers: [\n { imported: 'createLazyFileRoute' },\n { imported: 'createFileRoute' },\n ],\n },\n ]\n } else {\n if (ctx.lazy) {\n imports.required = [\n {\n source: targetModule,\n specifiers: [{ imported: 'createLazyFileRoute' }],\n },\n ]\n imports.banned = [\n {\n source: targetModule,\n specifiers: [{ imported: 'createFileRoute' }],\n },\n ]\n } else {\n imports.required = [\n {\n source: targetModule,\n specifiers: [{ imported: 'createFileRoute' }],\n },\n ]\n imports.banned = [\n {\n source: targetModule,\n specifiers: [{ imported: 'createLazyFileRoute' }],\n },\n ]\n }\n }\n return imports\n },\n onExportFound: ({ decl, ctx }) => {\n let appliedChanges = false\n if (decl.init?.type === 'CallExpression') {\n const callExpression = decl.init\n let identifier: types.namedTypes.Identifier | undefined\n // `const Route = createFileRoute({ ... })`\n if (callExpression.callee.type === 'Identifier') {\n identifier = callExpression.callee\n if (ctx.verboseFileRoutes) {\n // we need to add the string literal via another CallExpression\n callExpression.callee = b.callExpression(identifier, [\n b.stringLiteral(ctx.routeId),\n ])\n appliedChanges = true\n }\n }\n // `const Route = createFileRoute('/path')({ ... })`\n else if (\n callExpression.callee.type === 'CallExpression' &&\n callExpression.callee.callee.type === 'Identifier'\n ) {\n identifier = callExpression.callee.callee\n if (!ctx.verboseFileRoutes) {\n // we need to remove the route id\n callExpression.callee = identifier\n appliedChanges = true\n } else {\n // check if the route id is correct\n appliedChanges = ensureStringArgument(\n callExpression.callee,\n ctx.routeId,\n ctx.preferredQuote,\n )\n }\n }\n if (identifier === undefined) {\n throw new Error(\n `expected identifier to be present in ${ctx.routeId} for export ${EXPORT_NAME}`,\n )\n }\n if (identifier.name === 'createFileRoute' && ctx.lazy) {\n identifier.name = 'createLazyFileRoute'\n appliedChanges = true\n } else if (identifier.name === 'createLazyFileRoute' && !ctx.lazy) {\n identifier.name = 'createFileRoute'\n appliedChanges = true\n }\n }\n\n return appliedChanges\n },\n}\n"],"names":[],"mappings":";;AAIA,MAAM,IAAI,MAAM;AAEhB,MAAM,cAAc;AACb,MAAM,yBAA0C;AAAA,EACrD,MAAM;AAAA,EACN,YAAY;AAAA,EACZ,SAAS,CAAC,QAAQ;AAChB,UAAM,UAAkC,
|
|
1
|
+
{"version":3,"file":"default-transform-plugin.js","sources":["../../../src/transform/default-transform-plugin.ts"],"sourcesContent":["import { types } from 'recast'\nimport { ensureStringArgument } from './utils'\nimport type { TransformImportsConfig, TransformPlugin } from './types'\n\nconst b = types.builders\n\nconst EXPORT_NAME = 'Route'\nexport const defaultTransformPlugin: TransformPlugin = {\n name: 'default-transform',\n exportName: EXPORT_NAME,\n imports: (ctx) => {\n const imports: TransformImportsConfig = {}\n const targetModule = `@tanstack/${ctx.target}-router`\n if (ctx.verboseFileRoutes === false) {\n imports.banned = [\n {\n source: targetModule,\n specifiers: [\n { imported: 'createLazyFileRoute' },\n { imported: 'createFileRoute' },\n ],\n },\n ]\n } else {\n if (ctx.lazy) {\n imports.required = [\n {\n source: targetModule,\n specifiers: [{ imported: 'createLazyFileRoute' }],\n },\n ]\n imports.banned = [\n {\n source: targetModule,\n specifiers: [{ imported: 'createFileRoute' }],\n },\n ]\n } else {\n imports.required = [\n {\n source: targetModule,\n specifiers: [{ imported: 'createFileRoute' }],\n },\n ]\n imports.banned = [\n {\n source: targetModule,\n specifiers: [{ imported: 'createLazyFileRoute' }],\n },\n ]\n }\n }\n return imports\n },\n onExportFound: ({ decl, ctx }) => {\n let appliedChanges = false\n if (decl.init?.type === 'CallExpression') {\n const callExpression = decl.init\n let identifier: types.namedTypes.Identifier | undefined\n // `const Route = createFileRoute({ ... })`\n if (callExpression.callee.type === 'Identifier') {\n identifier = callExpression.callee\n if (ctx.verboseFileRoutes) {\n // we need to add the string literal via another CallExpression\n callExpression.callee = b.callExpression(identifier, [\n b.stringLiteral(ctx.routeId),\n ])\n appliedChanges = true\n }\n }\n // `const Route = createFileRoute('/path')({ ... })`\n else if (\n callExpression.callee.type === 'CallExpression' &&\n callExpression.callee.callee.type === 'Identifier'\n ) {\n identifier = callExpression.callee.callee\n if (!ctx.verboseFileRoutes) {\n // we need to remove the route id\n callExpression.callee = identifier\n appliedChanges = true\n } else {\n // check if the route id is correct\n appliedChanges = ensureStringArgument(\n callExpression.callee,\n ctx.routeId,\n ctx.preferredQuote,\n )\n }\n }\n if (identifier === undefined) {\n throw new Error(\n `expected identifier to be present in ${ctx.routeId} for export ${EXPORT_NAME}`,\n )\n }\n if (identifier.name === 'createFileRoute' && ctx.lazy) {\n identifier.name = 'createLazyFileRoute'\n appliedChanges = true\n } else if (identifier.name === 'createLazyFileRoute' && !ctx.lazy) {\n identifier.name = 'createFileRoute'\n appliedChanges = true\n }\n }\n\n return appliedChanges\n },\n}\n"],"names":[],"mappings":";;AAIA,MAAM,IAAI,MAAM;AAEhB,MAAM,cAAc;AACb,MAAM,yBAA0C;AAAA,EACrD,MAAM;AAAA,EACN,YAAY;AAAA,EACZ,SAAS,CAAC,QAAQ;AAChB,UAAM,UAAkC,CAAA;AACxC,UA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AAe,OAAO;AACnC,YAAI,CAAC,IAAI,mBAAmB;AAE1B,yBAAe,SAAS;AACxB,2BAAiB;AAAA,QACnB,OAAO;AAEL,2BAAiB;AAAA,YACf,eAAe;AAAA,YACf,IAAI;AAAA,YACJ,IAAI;AAAA,UAAA;AAAA,QAER;AAAA,MACF;AACA,UAAI,eAAe,QAAW;AAC5B,cAAM,IAAI;AAAA,UACR,wCAAwC,IAAI,OAAO,eAAe,WAAW;AAAA,QAAA;AAAA,MAEjF;AACA,UAAI,WAAW,SAAS,qBAAqB,IAAI,MAAM;AACrD,mBAAW,OAAO;AAClB,yBAAiB;AAAA,MACnB,WAAW,WAAW,SAAS,yBAAyB,CAAC,IAAI,MAAM;AACjE,mBAAW,OAAO;AAClB,yBAAiB;AAAA,MACnB;AAAA,IACF;AAEA,WAAO;AAAA,EACT;AACF;"}
|
|
@@ -8,7 +8,6 @@ async function transform({
|
|
|
8
8
|
source,
|
|
9
9
|
plugins
|
|
10
10
|
}) {
|
|
11
|
-
var _a, _b, _c, _d;
|
|
12
11
|
let appliedChanges = false;
|
|
13
12
|
let ast;
|
|
14
13
|
const foundExports = [];
|
|
@@ -39,7 +38,7 @@ async function transform({
|
|
|
39
38
|
const exportName = plugin.exportName;
|
|
40
39
|
if (registeredExports.has(exportName)) {
|
|
41
40
|
throw new Error(
|
|
42
|
-
`Export ${exportName} is already registered by plugin ${
|
|
41
|
+
`Export ${exportName} is already registered by plugin ${registeredExports.get(exportName)?.name}`
|
|
43
42
|
);
|
|
44
43
|
}
|
|
45
44
|
registeredExports.set(exportName, plugin);
|
|
@@ -58,7 +57,7 @@ async function transform({
|
|
|
58
57
|
const program = ast.program;
|
|
59
58
|
for (const n of program.body) {
|
|
60
59
|
if (registeredExports.size > 0 && n.type === "ExportNamedDeclaration") {
|
|
61
|
-
if (
|
|
60
|
+
if (n.declaration?.type === "VariableDeclaration") {
|
|
62
61
|
const decl = n.declaration.declarations[0];
|
|
63
62
|
if (decl && decl.type === "VariableDeclarator" && decl.id.type === "Identifier") {
|
|
64
63
|
const plugin = registeredExports.get(decl.id.name);
|
|
@@ -71,7 +70,7 @@ async function transform({
|
|
|
71
70
|
if (typeof spec.exported.name === "string") {
|
|
72
71
|
const plugin = registeredExports.get(spec.exported.name);
|
|
73
72
|
if (plugin) {
|
|
74
|
-
const variableName =
|
|
73
|
+
const variableName = spec.local?.name || spec.exported.name;
|
|
75
74
|
for (const decl of program.body) {
|
|
76
75
|
if (decl.type === "VariableDeclaration" && decl.declarations[0]) {
|
|
77
76
|
const variable = decl.declarations[0];
|
|
@@ -218,7 +217,7 @@ async function transform({
|
|
|
218
217
|
if (importDeclarationsToRemove.length > 0) {
|
|
219
218
|
appliedChanges = true;
|
|
220
219
|
for (const importDeclaration of importDeclarationsToRemove) {
|
|
221
|
-
if (
|
|
220
|
+
if (importDeclaration.specifiers?.length === 0) {
|
|
222
221
|
const index = program.body.indexOf(importDeclaration);
|
|
223
222
|
if (index !== -1) {
|
|
224
223
|
program.body.splice(index, 1);
|
|
@@ -353,11 +352,10 @@ function detectPreferredQuoteStyle(ast) {
|
|
|
353
352
|
let double = 0;
|
|
354
353
|
visit(ast, {
|
|
355
354
|
visitStringLiteral(path) {
|
|
356
|
-
var _a;
|
|
357
355
|
if (path.parent.node.type !== "JSXAttribute") {
|
|
358
|
-
const raw =
|
|
359
|
-
if (raw
|
|
360
|
-
else if (raw
|
|
356
|
+
const raw = path.node.extra?.raw;
|
|
357
|
+
if (raw?.startsWith("'")) single++;
|
|
358
|
+
else if (raw?.startsWith('"')) double++;
|
|
361
359
|
}
|
|
362
360
|
return false;
|
|
363
361
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"transform.js","sources":["../../../src/transform/transform.ts"],"sourcesContent":["import { parseAst } from '@tanstack/router-utils'\nimport { parse, print, types, visit } from 'recast'\nimport { SourceMapConsumer } from 'source-map'\nimport { mergeImportDeclarations } from '../utils'\nimport type { ImportDeclaration } from '../types'\nimport type { RawSourceMap } from 'source-map'\nimport type {\n TransformOptions,\n TransformPlugin,\n TransformResult,\n} from './types'\n\nconst b = types.builders\n\nexport async function transform({\n ctx,\n source,\n plugins,\n}: TransformOptions): Promise<TransformResult> {\n let appliedChanges = false as boolean\n let ast: types.namedTypes.File\n const foundExports: Array<string> = []\n try {\n ast = parse(source, {\n sourceFileName: 'output.ts',\n parser: {\n parse(code: string) {\n return parseAst({\n code,\n // we need to instruct babel to produce tokens,\n // otherwise recast will try to generate the tokens via its own parser and will fail\n tokens: true,\n })\n },\n },\n })\n } catch (e) {\n console.error('Error parsing code', ctx.routeId, source, e)\n return {\n result: 'error',\n error: e,\n }\n }\n\n const preferredQuote = detectPreferredQuoteStyle(ast)\n\n const registeredExports = new Map</* export name */ string, TransformPlugin>()\n\n for (const plugin of plugins ?? []) {\n const exportName = plugin.exportName\n if (registeredExports.has(exportName)) {\n throw new Error(\n `Export ${exportName} is already registered by plugin ${registeredExports.get(exportName)?.name}`,\n )\n }\n registeredExports.set(exportName, plugin)\n }\n\n function onExportFound(\n decl: types.namedTypes.VariableDeclarator,\n exportName: string,\n plugin: TransformPlugin,\n ) {\n const pluginAppliedChanges = plugin.onExportFound({\n decl,\n ctx: { ...ctx, preferredQuote },\n })\n if (pluginAppliedChanges) {\n appliedChanges = true\n }\n\n // export is handled, remove it from the registered exports\n registeredExports.delete(exportName)\n // store the export so we can later return it once the file is transformed\n foundExports.push(exportName)\n }\n\n const program: types.namedTypes.Program = ast.program\n // first pass: find registered exports\n for (const n of program.body) {\n if (registeredExports.size > 0 && n.type === 'ExportNamedDeclaration') {\n // direct export of a variable declaration, e.g. `export const Route = createFileRoute('/path')`\n if (n.declaration?.type === 'VariableDeclaration') {\n const decl = n.declaration.declarations[0]\n if (\n decl &&\n decl.type === 'VariableDeclarator' &&\n decl.id.type === 'Identifier'\n ) {\n const plugin = registeredExports.get(decl.id.name)\n if (plugin) {\n onExportFound(decl, decl.id.name, plugin)\n }\n }\n }\n // this is an export without a declaration, e.g. `export { Route }`\n else if (n.declaration === null && n.specifiers) {\n for (const spec of n.specifiers) {\n if (typeof spec.exported.name === 'string') {\n const plugin = registeredExports.get(spec.exported.name)\n if (plugin) {\n const variableName = spec.local?.name || spec.exported.name\n // find the matching variable declaration by iterating over the top-level declarations\n for (const decl of program.body) {\n if (\n decl.type === 'VariableDeclaration' &&\n decl.declarations[0]\n ) {\n const variable = decl.declarations[0]\n if (\n variable.type === 'VariableDeclarator' &&\n variable.id.type === 'Identifier' &&\n variable.id.name === variableName\n ) {\n onExportFound(variable, spec.exported.name, plugin)\n break\n }\n }\n }\n }\n }\n }\n }\n }\n }\n\n const imports: {\n required: Array<ImportDeclaration>\n banned: Array<ImportDeclaration>\n } = {\n required: [],\n banned: [],\n }\n\n for (const plugin of plugins ?? []) {\n const exportName = plugin.exportName\n if (foundExports.includes(exportName)) {\n const pluginImports = plugin.imports(ctx)\n if (pluginImports.required) {\n imports.required.push(...pluginImports.required)\n }\n if (pluginImports.banned) {\n imports.banned.push(...pluginImports.banned)\n }\n }\n }\n\n imports.required = mergeImportDeclarations(imports.required)\n imports.banned = mergeImportDeclarations(imports.banned)\n\n const importStatementCandidates: Array<types.namedTypes.ImportDeclaration> =\n []\n const importDeclarationsToRemove: Array<types.namedTypes.ImportDeclaration> =\n []\n\n // second pass: apply import rules, but only if a matching export for the plugin was found\n for (const n of program.body) {\n const findImport =\n (opts: { source: string; importKind?: 'type' | 'value' | 'typeof' }) =>\n (i: ImportDeclaration) => {\n if (i.source === opts.source) {\n const importKind = i.importKind || 'value'\n const expectedImportKind = opts.importKind || 'value'\n return expectedImportKind === importKind\n }\n return false\n }\n if (n.type === 'ImportDeclaration' && typeof n.source.value === 'string') {\n const filterImport = findImport({\n source: n.source.value,\n importKind: n.importKind,\n })\n let requiredImports = imports.required.filter(filterImport)[0]\n\n const bannedImports = imports.banned.filter(filterImport)[0]\n if (!requiredImports && !bannedImports) {\n continue\n }\n const importSpecifiersToRemove: types.namedTypes.ImportDeclaration['specifiers'] =\n []\n if (n.specifiers) {\n for (const spec of n.specifiers) {\n if (!requiredImports && !bannedImports) {\n break\n }\n if (\n spec.type === 'ImportSpecifier' &&\n typeof spec.imported.name === 'string'\n ) {\n if (requiredImports) {\n const requiredImportIndex = requiredImports.specifiers.findIndex(\n (imp) => imp.imported === spec.imported.name,\n )\n if (requiredImportIndex !== -1) {\n // import is already present, remove it from requiredImports\n requiredImports.specifiers.splice(requiredImportIndex, 1)\n if (requiredImports.specifiers.length === 0) {\n imports.required = imports.required.splice(\n imports.required.indexOf(requiredImports),\n 1,\n )\n requiredImports = undefined\n }\n } else {\n // add the import statement to the candidates\n importStatementCandidates.push(n)\n }\n }\n if (bannedImports) {\n const bannedImportIndex = bannedImports.specifiers.findIndex(\n (imp) => imp.imported === spec.imported.name,\n )\n if (bannedImportIndex !== -1) {\n importSpecifiersToRemove.push(spec)\n }\n }\n }\n }\n if (importSpecifiersToRemove.length > 0) {\n appliedChanges = true\n n.specifiers = n.specifiers.filter(\n (spec) => !importSpecifiersToRemove.includes(spec),\n )\n\n // mark the import statement as to be deleted if it is now empty\n if (n.specifiers.length === 0) {\n importDeclarationsToRemove.push(n)\n }\n }\n }\n }\n }\n imports.required.forEach((requiredImport) => {\n if (requiredImport.specifiers.length > 0) {\n appliedChanges = true\n if (importStatementCandidates.length > 0) {\n // find the first import statement that matches both the module and the import kind\n const importStatement = importStatementCandidates.find(\n (importStatement) => {\n if (importStatement.source.value === requiredImport.source) {\n const importKind = importStatement.importKind || 'value'\n const requiredImportKind = requiredImport.importKind || 'value'\n return importKind === requiredImportKind\n }\n return false\n },\n )\n if (importStatement) {\n if (importStatement.specifiers === undefined) {\n importStatement.specifiers = []\n }\n const importSpecifiersToAdd = requiredImport.specifiers.map((spec) =>\n b.importSpecifier(\n b.identifier(spec.imported),\n b.identifier(spec.imported),\n ),\n )\n importStatement.specifiers = [\n ...importStatement.specifiers,\n ...importSpecifiersToAdd,\n ]\n return\n }\n }\n const importStatement = b.importDeclaration(\n requiredImport.specifiers.map((spec) =>\n b.importSpecifier(\n b.identifier(spec.imported),\n spec.local ? b.identifier(spec.local) : null,\n ),\n ),\n b.stringLiteral(requiredImport.source),\n )\n program.body.unshift(importStatement)\n }\n })\n if (importDeclarationsToRemove.length > 0) {\n appliedChanges = true\n for (const importDeclaration of importDeclarationsToRemove) {\n // check if the import declaration is still empty\n if (importDeclaration.specifiers?.length === 0) {\n const index = program.body.indexOf(importDeclaration)\n if (index !== -1) {\n program.body.splice(index, 1)\n }\n }\n }\n }\n\n if (!appliedChanges) {\n return {\n exports: foundExports,\n result: 'not-modified',\n }\n }\n\n const printResult = print(ast, {\n reuseWhitespace: true,\n sourceMapName: 'output.map',\n })\n let transformedCode = printResult.code\n if (printResult.map) {\n const fixedOutput = await fixTransformedOutputText({\n originalCode: source,\n transformedCode,\n sourceMap: printResult.map as RawSourceMap,\n preferredQuote,\n })\n transformedCode = fixedOutput\n }\n return {\n result: 'modified',\n exports: foundExports,\n output: transformedCode,\n }\n}\n\nasync function fixTransformedOutputText({\n originalCode,\n transformedCode,\n sourceMap,\n preferredQuote,\n}: {\n originalCode: string\n transformedCode: string\n sourceMap: RawSourceMap\n preferredQuote: '\"' | \"'\"\n}) {\n const originalLines = originalCode.split('\\n')\n const transformedLines = transformedCode.split('\\n')\n\n const defaultUsesSemicolons = detectSemicolonUsage(originalCode)\n\n const consumer = await new SourceMapConsumer(sourceMap)\n\n const fixedLines = transformedLines.map((line, i) => {\n const transformedLineNum = i + 1\n\n let origLineText: string | undefined = undefined\n\n for (let col = 0; col < line.length; col++) {\n const mapped = consumer.originalPositionFor({\n line: transformedLineNum,\n column: col,\n })\n if (mapped.line != null && mapped.line > 0) {\n origLineText = originalLines[mapped.line - 1]\n break\n }\n }\n\n if (origLineText !== undefined) {\n if (origLineText === line) {\n return origLineText\n }\n return fixLine(line, {\n originalLine: origLineText,\n useOriginalSemicolon: true,\n useOriginalQuotes: true,\n fallbackQuote: preferredQuote,\n })\n } else {\n return fixLine(line, {\n originalLine: null,\n useOriginalSemicolon: false,\n useOriginalQuotes: false,\n fallbackQuote: preferredQuote,\n fallbackSemicolon: defaultUsesSemicolons,\n })\n }\n })\n\n return fixedLines.join('\\n')\n}\n\nfunction fixLine(\n line: string,\n {\n originalLine,\n useOriginalSemicolon,\n useOriginalQuotes,\n fallbackQuote,\n fallbackSemicolon = true,\n }: {\n originalLine: string | null\n useOriginalSemicolon: boolean\n useOriginalQuotes: boolean\n fallbackQuote: string\n fallbackSemicolon?: boolean\n },\n) {\n let result = line\n\n if (useOriginalQuotes && originalLine) {\n result = fixQuotes(result, originalLine, fallbackQuote)\n } else if (!useOriginalQuotes && fallbackQuote) {\n result = fixQuotesToPreferred(result, fallbackQuote)\n }\n\n if (useOriginalSemicolon && originalLine) {\n const hadSemicolon = originalLine.trimEnd().endsWith(';')\n const hasSemicolon = result.trimEnd().endsWith(';')\n if (hadSemicolon && !hasSemicolon) result += ';'\n if (!hadSemicolon && hasSemicolon) result = result.replace(/;\\s*$/, '')\n } else if (!useOriginalSemicolon) {\n const hasSemicolon = result.trimEnd().endsWith(';')\n if (!fallbackSemicolon && hasSemicolon) result = result.replace(/;\\s*$/, '')\n if (fallbackSemicolon && !hasSemicolon && result.trim()) result += ';'\n }\n\n return result\n}\n\nfunction fixQuotes(line: string, originalLine: string, fallbackQuote: string) {\n let originalQuote = detectQuoteFromLine(originalLine)\n if (!originalQuote) {\n originalQuote = fallbackQuote\n }\n return fixQuotesToPreferred(line, originalQuote)\n}\n\nfunction fixQuotesToPreferred(line: string, quote: string) {\n // Replace existing quotes with preferred quote\n return line.replace(\n /(['\"`])([^'\"`\\\\]*(?:\\\\.[^'\"`\\\\]*)*)\\1/g,\n (_, q, content) => {\n const escaped = content.replaceAll(quote, `\\\\${quote}`)\n return `${quote}${escaped}${quote}`\n },\n )\n}\n\nfunction detectQuoteFromLine(line: string) {\n const match = line.match(/(['\"`])(?:\\\\.|[^\\\\])*?\\1/)\n return match ? match[1] : null\n}\n\nfunction detectSemicolonUsage(code: string) {\n const lines = code.split('\\n').map((l) => l.trim())\n const total = lines.length\n const withSemis = lines.filter((l) => l.endsWith(';')).length\n return withSemis > total / 2\n}\n\nexport function detectPreferredQuoteStyle(ast: types.ASTNode): \"'\" | '\"' {\n let single = 0\n let double = 0\n\n visit(ast, {\n visitStringLiteral(path) {\n if (path.parent.node.type !== 'JSXAttribute') {\n const raw = path.node.extra?.raw\n if (raw?.startsWith(\"'\")) single++\n else if (raw?.startsWith('\"')) double++\n }\n return false\n },\n })\n\n if (single >= double) {\n return \"'\"\n }\n return '\"'\n}\n"],"names":["importStatement"],"mappings":";;;;AAYA,MAAM,IAAI,MAAM;AAEhB,eAAsB,UAAU;AAAA,EAC9B;AAAA,EACA;AAAA,EACA;AACF,GAA+C;;AAC7C,MAAI,iBAAiB;AACjB,MAAA;AACJ,QAAM,eAA8B,CAAC;AACjC,MAAA;AACF,UAAM,MAAM,QAAQ;AAAA,MAClB,gBAAgB;AAAA,MAChB,QAAQ;AAAA,QACN,MAAM,MAAc;AAClB,iBAAO,SAAS;AAAA,YACd;AAAA;AAAA;AAAA,YAGA,QAAQ;AAAA,UAAA,CACT;AAAA,QAAA;AAAA,MACH;AAAA,IACF,CACD;AAAA,WACM,GAAG;AACV,YAAQ,MAAM,sBAAsB,IAAI,SAAS,QAAQ,CAAC;AACnD,WAAA;AAAA,MACL,QAAQ;AAAA,MACR,OAAO;AAAA,IACT;AAAA,EAAA;AAGI,QAAA,iBAAiB,0BAA0B,GAAG;AAE9C,QAAA,wCAAwB,IAA+C;AAElE,aAAA,UAAU,WAAW,IAAI;AAClC,UAAM,aAAa,OAAO;AACtB,QAAA,kBAAkB,IAAI,UAAU,GAAG;AACrC,YAAM,IAAI;AAAA,QACR,UAAU,UAAU,qCAAoC,uBAAkB,IAAI,UAAU,MAAhC,mBAAmC,IAAI;AAAA,MACjG;AAAA,IAAA;AAEgB,sBAAA,IAAI,YAAY,MAAM;AAAA,EAAA;AAGjC,WAAA,cACP,MACA,YACA,Q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,CAAC,IAAI;AAC5B;AAEA,SAAS,qBAAqB,MAAc;AACpC,QAAA,QAAQ,KAAK,MAAM,IAAI,EAAE,IAAI,CAAC,MAAM,EAAE,MAAM;AAClD,QAAM,QAAQ,MAAM;AACd,QAAA,YAAY,MAAM,OAAO,CAAC,MAAM,EAAE,SAAS,GAAG,CAAC,EAAE;AACvD,SAAO,YAAY,QAAQ;AAC7B;AAEO,SAAS,0BAA0B,KAA+B;AACvE,MAAI,SAAS;AACb,MAAI,SAAS;AAEb,QAAM,KAAK;AAAA,IACT,mBAAmB,MAAM;;AACvB,UAAI,KAAK,OAAO,KAAK,SAAS,gBAAgB;AACtC,cAAA,OAAM,UAAK,KAAK,UAAV,mBAAiB;AACzB,YAAA,2BAAK,WAAW,KAAM;AAAA,iBACjB,2BAAK,WAAW,KAAM;AAAA,MAAA;AAE1B,aAAA;AAAA,IAAA;AAAA,EACT,CACD;AAED,MAAI,UAAU,QAAQ;AACb,WAAA;AAAA,EAAA;AAEF,SAAA;AACT;"}
|
|
1
|
+
{"version":3,"file":"transform.js","sources":["../../../src/transform/transform.ts"],"sourcesContent":["import { parseAst } from '@tanstack/router-utils'\nimport { parse, print, types, visit } from 'recast'\nimport { SourceMapConsumer } from 'source-map'\nimport { mergeImportDeclarations } from '../utils'\nimport type { ImportDeclaration } from '../types'\nimport type { RawSourceMap } from 'source-map'\nimport type {\n TransformOptions,\n TransformPlugin,\n TransformResult,\n} from './types'\n\nconst b = types.builders\n\nexport async function transform({\n ctx,\n source,\n plugins,\n}: TransformOptions): Promise<TransformResult> {\n let appliedChanges = false as boolean\n let ast: types.namedTypes.File\n const foundExports: Array<string> = []\n try {\n ast = parse(source, {\n sourceFileName: 'output.ts',\n parser: {\n parse(code: string) {\n return parseAst({\n code,\n // we need to instruct babel to produce tokens,\n // otherwise recast will try to generate the tokens via its own parser and will fail\n tokens: true,\n })\n },\n },\n })\n } catch (e) {\n console.error('Error parsing code', ctx.routeId, source, e)\n return {\n result: 'error',\n error: e,\n }\n }\n\n const preferredQuote = detectPreferredQuoteStyle(ast)\n\n const registeredExports = new Map</* export name */ string, TransformPlugin>()\n\n for (const plugin of plugins ?? []) {\n const exportName = plugin.exportName\n if (registeredExports.has(exportName)) {\n throw new Error(\n `Export ${exportName} is already registered by plugin ${registeredExports.get(exportName)?.name}`,\n )\n }\n registeredExports.set(exportName, plugin)\n }\n\n function onExportFound(\n decl: types.namedTypes.VariableDeclarator,\n exportName: string,\n plugin: TransformPlugin,\n ) {\n const pluginAppliedChanges = plugin.onExportFound({\n decl,\n ctx: { ...ctx, preferredQuote },\n })\n if (pluginAppliedChanges) {\n appliedChanges = true\n }\n\n // export is handled, remove it from the registered exports\n registeredExports.delete(exportName)\n // store the export so we can later return it once the file is transformed\n foundExports.push(exportName)\n }\n\n const program: types.namedTypes.Program = ast.program\n // first pass: find registered exports\n for (const n of program.body) {\n if (registeredExports.size > 0 && n.type === 'ExportNamedDeclaration') {\n // direct export of a variable declaration, e.g. `export const Route = createFileRoute('/path')`\n if (n.declaration?.type === 'VariableDeclaration') {\n const decl = n.declaration.declarations[0]\n if (\n decl &&\n decl.type === 'VariableDeclarator' &&\n decl.id.type === 'Identifier'\n ) {\n const plugin = registeredExports.get(decl.id.name)\n if (plugin) {\n onExportFound(decl, decl.id.name, plugin)\n }\n }\n }\n // this is an export without a declaration, e.g. `export { Route }`\n else if (n.declaration === null && n.specifiers) {\n for (const spec of n.specifiers) {\n if (typeof spec.exported.name === 'string') {\n const plugin = registeredExports.get(spec.exported.name)\n if (plugin) {\n const variableName = spec.local?.name || spec.exported.name\n // find the matching variable declaration by iterating over the top-level declarations\n for (const decl of program.body) {\n if (\n decl.type === 'VariableDeclaration' &&\n decl.declarations[0]\n ) {\n const variable = decl.declarations[0]\n if (\n variable.type === 'VariableDeclarator' &&\n variable.id.type === 'Identifier' &&\n variable.id.name === variableName\n ) {\n onExportFound(variable, spec.exported.name, plugin)\n break\n }\n }\n }\n }\n }\n }\n }\n }\n }\n\n const imports: {\n required: Array<ImportDeclaration>\n banned: Array<ImportDeclaration>\n } = {\n required: [],\n banned: [],\n }\n\n for (const plugin of plugins ?? []) {\n const exportName = plugin.exportName\n if (foundExports.includes(exportName)) {\n const pluginImports = plugin.imports(ctx)\n if (pluginImports.required) {\n imports.required.push(...pluginImports.required)\n }\n if (pluginImports.banned) {\n imports.banned.push(...pluginImports.banned)\n }\n }\n }\n\n imports.required = mergeImportDeclarations(imports.required)\n imports.banned = mergeImportDeclarations(imports.banned)\n\n const importStatementCandidates: Array<types.namedTypes.ImportDeclaration> =\n []\n const importDeclarationsToRemove: Array<types.namedTypes.ImportDeclaration> =\n []\n\n // second pass: apply import rules, but only if a matching export for the plugin was found\n for (const n of program.body) {\n const findImport =\n (opts: { source: string; importKind?: 'type' | 'value' | 'typeof' }) =>\n (i: ImportDeclaration) => {\n if (i.source === opts.source) {\n const importKind = i.importKind || 'value'\n const expectedImportKind = opts.importKind || 'value'\n return expectedImportKind === importKind\n }\n return false\n }\n if (n.type === 'ImportDeclaration' && typeof n.source.value === 'string') {\n const filterImport = findImport({\n source: n.source.value,\n importKind: n.importKind,\n })\n let requiredImports = imports.required.filter(filterImport)[0]\n\n const bannedImports = imports.banned.filter(filterImport)[0]\n if (!requiredImports && !bannedImports) {\n continue\n }\n const importSpecifiersToRemove: types.namedTypes.ImportDeclaration['specifiers'] =\n []\n if (n.specifiers) {\n for (const spec of n.specifiers) {\n if (!requiredImports && !bannedImports) {\n break\n }\n if (\n spec.type === 'ImportSpecifier' &&\n typeof spec.imported.name === 'string'\n ) {\n if (requiredImports) {\n const requiredImportIndex = requiredImports.specifiers.findIndex(\n (imp) => imp.imported === spec.imported.name,\n )\n if (requiredImportIndex !== -1) {\n // import is already present, remove it from requiredImports\n requiredImports.specifiers.splice(requiredImportIndex, 1)\n if (requiredImports.specifiers.length === 0) {\n imports.required = imports.required.splice(\n imports.required.indexOf(requiredImports),\n 1,\n )\n requiredImports = undefined\n }\n } else {\n // add the import statement to the candidates\n importStatementCandidates.push(n)\n }\n }\n if (bannedImports) {\n const bannedImportIndex = bannedImports.specifiers.findIndex(\n (imp) => imp.imported === spec.imported.name,\n )\n if (bannedImportIndex !== -1) {\n importSpecifiersToRemove.push(spec)\n }\n }\n }\n }\n if (importSpecifiersToRemove.length > 0) {\n appliedChanges = true\n n.specifiers = n.specifiers.filter(\n (spec) => !importSpecifiersToRemove.includes(spec),\n )\n\n // mark the import statement as to be deleted if it is now empty\n if (n.specifiers.length === 0) {\n importDeclarationsToRemove.push(n)\n }\n }\n }\n }\n }\n imports.required.forEach((requiredImport) => {\n if (requiredImport.specifiers.length > 0) {\n appliedChanges = true\n if (importStatementCandidates.length > 0) {\n // find the first import statement that matches both the module and the import kind\n const importStatement = importStatementCandidates.find(\n (importStatement) => {\n if (importStatement.source.value === requiredImport.source) {\n const importKind = importStatement.importKind || 'value'\n const requiredImportKind = requiredImport.importKind || 'value'\n return importKind === requiredImportKind\n }\n return false\n },\n )\n if (importStatement) {\n if (importStatement.specifiers === undefined) {\n importStatement.specifiers = []\n }\n const importSpecifiersToAdd = requiredImport.specifiers.map((spec) =>\n b.importSpecifier(\n b.identifier(spec.imported),\n b.identifier(spec.imported),\n ),\n )\n importStatement.specifiers = [\n ...importStatement.specifiers,\n ...importSpecifiersToAdd,\n ]\n return\n }\n }\n const importStatement = b.importDeclaration(\n requiredImport.specifiers.map((spec) =>\n b.importSpecifier(\n b.identifier(spec.imported),\n spec.local ? b.identifier(spec.local) : null,\n ),\n ),\n b.stringLiteral(requiredImport.source),\n )\n program.body.unshift(importStatement)\n }\n })\n if (importDeclarationsToRemove.length > 0) {\n appliedChanges = true\n for (const importDeclaration of importDeclarationsToRemove) {\n // check if the import declaration is still empty\n if (importDeclaration.specifiers?.length === 0) {\n const index = program.body.indexOf(importDeclaration)\n if (index !== -1) {\n program.body.splice(index, 1)\n }\n }\n }\n }\n\n if (!appliedChanges) {\n return {\n exports: foundExports,\n result: 'not-modified',\n }\n }\n\n const printResult = print(ast, {\n reuseWhitespace: true,\n sourceMapName: 'output.map',\n })\n let transformedCode = printResult.code\n if (printResult.map) {\n const fixedOutput = await fixTransformedOutputText({\n originalCode: source,\n transformedCode,\n sourceMap: printResult.map as RawSourceMap,\n preferredQuote,\n })\n transformedCode = fixedOutput\n }\n return {\n result: 'modified',\n exports: foundExports,\n output: transformedCode,\n }\n}\n\nasync function fixTransformedOutputText({\n originalCode,\n transformedCode,\n sourceMap,\n preferredQuote,\n}: {\n originalCode: string\n transformedCode: string\n sourceMap: RawSourceMap\n preferredQuote: '\"' | \"'\"\n}) {\n const originalLines = originalCode.split('\\n')\n const transformedLines = transformedCode.split('\\n')\n\n const defaultUsesSemicolons = detectSemicolonUsage(originalCode)\n\n const consumer = await new SourceMapConsumer(sourceMap)\n\n const fixedLines = transformedLines.map((line, i) => {\n const transformedLineNum = i + 1\n\n let origLineText: string | undefined = undefined\n\n for (let col = 0; col < line.length; col++) {\n const mapped = consumer.originalPositionFor({\n line: transformedLineNum,\n column: col,\n })\n if (mapped.line != null && mapped.line > 0) {\n origLineText = originalLines[mapped.line - 1]\n break\n }\n }\n\n if (origLineText !== undefined) {\n if (origLineText === line) {\n return origLineText\n }\n return fixLine(line, {\n originalLine: origLineText,\n useOriginalSemicolon: true,\n useOriginalQuotes: true,\n fallbackQuote: preferredQuote,\n })\n } else {\n return fixLine(line, {\n originalLine: null,\n useOriginalSemicolon: false,\n useOriginalQuotes: false,\n fallbackQuote: preferredQuote,\n fallbackSemicolon: defaultUsesSemicolons,\n })\n }\n })\n\n return fixedLines.join('\\n')\n}\n\nfunction fixLine(\n line: string,\n {\n originalLine,\n useOriginalSemicolon,\n useOriginalQuotes,\n fallbackQuote,\n fallbackSemicolon = true,\n }: {\n originalLine: string | null\n useOriginalSemicolon: boolean\n useOriginalQuotes: boolean\n fallbackQuote: string\n fallbackSemicolon?: boolean\n },\n) {\n let result = line\n\n if (useOriginalQuotes && originalLine) {\n result = fixQuotes(result, originalLine, fallbackQuote)\n } else if (!useOriginalQuotes && fallbackQuote) {\n result = fixQuotesToPreferred(result, fallbackQuote)\n }\n\n if (useOriginalSemicolon && originalLine) {\n const hadSemicolon = originalLine.trimEnd().endsWith(';')\n const hasSemicolon = result.trimEnd().endsWith(';')\n if (hadSemicolon && !hasSemicolon) result += ';'\n if (!hadSemicolon && hasSemicolon) result = result.replace(/;\\s*$/, '')\n } else if (!useOriginalSemicolon) {\n const hasSemicolon = result.trimEnd().endsWith(';')\n if (!fallbackSemicolon && hasSemicolon) result = result.replace(/;\\s*$/, '')\n if (fallbackSemicolon && !hasSemicolon && result.trim()) result += ';'\n }\n\n return result\n}\n\nfunction fixQuotes(line: string, originalLine: string, fallbackQuote: string) {\n let originalQuote = detectQuoteFromLine(originalLine)\n if (!originalQuote) {\n originalQuote = fallbackQuote\n }\n return fixQuotesToPreferred(line, originalQuote)\n}\n\nfunction fixQuotesToPreferred(line: string, quote: string) {\n // Replace existing quotes with preferred quote\n return line.replace(\n /(['\"`])([^'\"`\\\\]*(?:\\\\.[^'\"`\\\\]*)*)\\1/g,\n (_, q, content) => {\n const escaped = content.replaceAll(quote, `\\\\${quote}`)\n return `${quote}${escaped}${quote}`\n },\n )\n}\n\nfunction detectQuoteFromLine(line: string) {\n const match = line.match(/(['\"`])(?:\\\\.|[^\\\\])*?\\1/)\n return match ? match[1] : null\n}\n\nfunction detectSemicolonUsage(code: string) {\n const lines = code.split('\\n').map((l) => l.trim())\n const total = lines.length\n const withSemis = lines.filter((l) => l.endsWith(';')).length\n return withSemis > total / 2\n}\n\nexport function detectPreferredQuoteStyle(ast: types.ASTNode): \"'\" | '\"' {\n let single = 0\n let double = 0\n\n visit(ast, {\n visitStringLiteral(path) {\n if (path.parent.node.type !== 'JSXAttribute') {\n const raw = path.node.extra?.raw\n if (raw?.startsWith(\"'\")) single++\n else if (raw?.startsWith('\"')) double++\n }\n return false\n },\n })\n\n if (single >= double) {\n return \"'\"\n }\n return '\"'\n}\n"],"names":["importStatement"],"mappings":";;;;AAYA,MAAM,IA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M,KAAK,KAAK,OAAO;AAC7B,YAAI,KAAK,WAAW,GAAG,EAAG;AAAA,iBACjB,KAAK,WAAW,GAAG,EAAG;AAAA,MACjC;AACA,aAAO;AAAA,IACT;AAAA,EAAA,CACD;AAED,MAAI,UAAU,QAAQ;AACpB,WAAO;AAAA,EACT;AACA,SAAO;AACT;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"utils.js","sources":["../../../src/transform/utils.ts"],"sourcesContent":["import { types } from 'recast'\n\nconst b = types.builders\n\nexport function ensureStringArgument(\n callExpression: types.namedTypes.CallExpression,\n value: string,\n preferredQuote?: \"'\" | '\"',\n) {\n const argument = callExpression.arguments[0]\n if (!argument) {\n let stringLiteral: types.namedTypes.StringLiteral\n if (!preferredQuote) {\n stringLiteral = b.stringLiteral.from({ value })\n } else {\n stringLiteral = b.stringLiteral.from({\n value,\n extra: {\n rawValue: value,\n raw: `${preferredQuote}${value}${preferredQuote}`,\n },\n })\n }\n callExpression.arguments.push(stringLiteral)\n return true\n } else if (argument.type === 'StringLiteral') {\n if (argument.value !== value) {\n argument.value = value\n return true\n }\n } else if (argument.type === 'TemplateLiteral') {\n if (\n argument.quasis.length === 1 &&\n argument.quasis[0] &&\n argument.quasis[0].value.raw !== value\n ) {\n argument.quasis[0].value.raw = value\n return true\n }\n }\n return false\n}\n"],"names":[],"mappings":";AAEA,MAAM,IAAI,MAAM;
|
|
1
|
+
{"version":3,"file":"utils.js","sources":["../../../src/transform/utils.ts"],"sourcesContent":["import { types } from 'recast'\n\nconst b = types.builders\n\nexport function ensureStringArgument(\n callExpression: types.namedTypes.CallExpression,\n value: string,\n preferredQuote?: \"'\" | '\"',\n) {\n const argument = callExpression.arguments[0]\n if (!argument) {\n let stringLiteral: types.namedTypes.StringLiteral\n if (!preferredQuote) {\n stringLiteral = b.stringLiteral.from({ value })\n } else {\n stringLiteral = b.stringLiteral.from({\n value,\n extra: {\n rawValue: value,\n raw: `${preferredQuote}${value}${preferredQuote}`,\n },\n })\n }\n callExpression.arguments.push(stringLiteral)\n return true\n } else if (argument.type === 'StringLiteral') {\n if (argument.value !== value) {\n argument.value = value\n return true\n }\n } else if (argument.type === 'TemplateLiteral') {\n if (\n argument.quasis.length === 1 &&\n argument.quasis[0] &&\n argument.quasis[0].value.raw !== value\n ) {\n argument.quasis[0].value.raw = value\n return true\n }\n }\n return false\n}\n"],"names":[],"mappings":";AAEA,MAAM,IAAI,MAAM;AAET,SAAS,qBACd,gBACA,OACA,gBACA;AACA,QAAM,WAAW,eAAe,UAAU,CAAC;AAC3C,MAAI,CAAC,UAAU;AACb,QAAI;AACJ,QAAI,CAAC,gBAAgB;AACnB,sBAAgB,EAAE,cAAc,KAAK,EAAE,OAAO;AAAA,IAChD,OAAO;AACL,sBAAgB,EAAE,cAAc,KAAK;AAAA,QACnC;AAAA,QACA,OAAO;AAAA,UACL,UAAU;AAAA,UACV,KAAK,GAAG,cAAc,GAAG,KAAK,GAAG,cAAc;AAAA,QAAA;AAAA,MACjD,CACD;AAAA,IACH;AACA,mBAAe,UAAU,KAAK,aAAa;AAC3C,WAAO;AAAA,EACT,WAAW,SAAS,SAAS,iBAAiB;AAC5C,QAAI,SAAS,UAAU,OAAO;AAC5B,eAAS,QAAQ;AACjB,aAAO;AAAA,IACT;AAAA,EACF,WAAW,SAAS,SAAS,mBAAmB;AAC9C,QACE,SAAS,OAAO,WAAW,KAC3B,SAAS,OAAO,CAAC,KACjB,SAAS,OAAO,CAAC,EAAE,MAAM,QAAQ,OACjC;AACA,eAAS,OAAO,CAAC,EAAE,MAAM,MAAM;AAC/B,aAAO;AAAA,IACT;AAAA,EACF;AACA,SAAO;AACT;"}
|
package/dist/esm/utils.js
CHANGED
|
@@ -75,7 +75,6 @@ function replaceBackslash(s) {
|
|
|
75
75
|
return s.replaceAll(/\\/gi, "/");
|
|
76
76
|
}
|
|
77
77
|
function routePathToVariable(routePath) {
|
|
78
|
-
var _a;
|
|
79
78
|
const toVariableSafeChar = (char) => {
|
|
80
79
|
if (/[a-zA-Z0-9_]/.test(char)) {
|
|
81
80
|
return char;
|
|
@@ -100,10 +99,10 @@ function routePathToVariable(routePath) {
|
|
|
100
99
|
return `Char${char.charCodeAt(0)}`;
|
|
101
100
|
}
|
|
102
101
|
};
|
|
103
|
-
return
|
|
102
|
+
return removeUnderscores(routePath)?.replace(/\/\$\//g, "/splat/").replace(/\$$/g, "splat").replace(/\$\{\$\}/g, "splat").replace(/\$/g, "").split(/[/-]/g).map((d, i) => i > 0 ? capitalize(d) : d).join("").split("").map(toVariableSafeChar).join("").replace(/^(\d)/g, "R$1") ?? "";
|
|
104
103
|
}
|
|
105
104
|
function removeUnderscores(s) {
|
|
106
|
-
return s
|
|
105
|
+
return s?.replaceAll(/(^_|_$)/gi, "").replaceAll(/(\/_|_\/)/gi, "/");
|
|
107
106
|
}
|
|
108
107
|
function capitalize(s) {
|
|
109
108
|
if (typeof s !== "string") return "";
|
|
@@ -113,11 +112,10 @@ function removeExt(d, keepExtension = false) {
|
|
|
113
112
|
return keepExtension ? d : d.substring(0, d.lastIndexOf(".")) || d;
|
|
114
113
|
}
|
|
115
114
|
async function writeIfDifferent(filepath, content, incomingContent, callbacks) {
|
|
116
|
-
var _a, _b;
|
|
117
115
|
if (content !== incomingContent) {
|
|
118
|
-
|
|
116
|
+
callbacks?.beforeWrite?.();
|
|
119
117
|
await fsp.writeFile(filepath, incomingContent);
|
|
120
|
-
|
|
118
|
+
callbacks?.afterWrite?.();
|
|
121
119
|
return true;
|
|
122
120
|
}
|
|
123
121
|
return false;
|
|
@@ -152,8 +150,7 @@ function removeLayoutSegments(routePath = "/") {
|
|
|
152
150
|
return newSegments.join("/");
|
|
153
151
|
}
|
|
154
152
|
function determineNodePath(node) {
|
|
155
|
-
|
|
156
|
-
return node.path = node.parent ? ((_a = node.routePath) == null ? void 0 : _a.replace(node.parent.routePath ?? "", "")) || "/" : node.routePath;
|
|
153
|
+
return node.path = node.parent ? node.routePath?.replace(node.parent.routePath ?? "", "") || "/" : node.routePath;
|
|
157
154
|
}
|
|
158
155
|
function removeLastSegmentFromPath(routePath = "/") {
|
|
159
156
|
const segments = routePath.split("/");
|
|
@@ -180,8 +177,7 @@ function hasParentRoute(routes, node, routePathToCheck) {
|
|
|
180
177
|
return hasParentRoute(routes, node, parentRoutePath);
|
|
181
178
|
}
|
|
182
179
|
const getResolvedRouteNodeVariableName = (routeNode, variableNameSuffix) => {
|
|
183
|
-
|
|
184
|
-
return ((_a = routeNode.children) == null ? void 0 : _a.length) ? `${routeNode.variableName}${variableNameSuffix}WithChildren` : `${routeNode.variableName}${variableNameSuffix}`;
|
|
180
|
+
return routeNode.children?.length ? `${routeNode.variableName}${variableNameSuffix}WithChildren` : `${routeNode.variableName}${variableNameSuffix}`;
|
|
185
181
|
};
|
|
186
182
|
function isRouteNodeValidForAugmentation(routeNode) {
|
|
187
183
|
if (!routeNode || routeNode.isVirtual) {
|
|
@@ -190,8 +186,7 @@ function isRouteNodeValidForAugmentation(routeNode) {
|
|
|
190
186
|
return true;
|
|
191
187
|
}
|
|
192
188
|
const inferPath = (routeNode) => {
|
|
193
|
-
|
|
194
|
-
return routeNode.cleanedPath === "/" ? routeNode.cleanedPath : ((_a = routeNode.cleanedPath) == null ? void 0 : _a.replace(/\/$/, "")) ?? "";
|
|
189
|
+
return routeNode.cleanedPath === "/" ? routeNode.cleanedPath : routeNode.cleanedPath?.replace(/\/$/, "") ?? "";
|
|
195
190
|
};
|
|
196
191
|
const inferFullPath = (routeNode) => {
|
|
197
192
|
const fullPath = removeGroups(
|
|
@@ -227,8 +222,7 @@ const inferTo = (routeNode) => {
|
|
|
227
222
|
};
|
|
228
223
|
const dedupeBranchesAndIndexRoutes = (routes) => {
|
|
229
224
|
return routes.filter((route) => {
|
|
230
|
-
|
|
231
|
-
if ((_a = route.children) == null ? void 0 : _a.find((child) => child.cleanedPath === "/")) return false;
|
|
225
|
+
if (route.children?.find((child) => child.cleanedPath === "/")) return false;
|
|
232
226
|
return true;
|
|
233
227
|
});
|
|
234
228
|
};
|
|
@@ -260,19 +254,15 @@ Conflicting files:
|
|
|
260
254
|
}
|
|
261
255
|
}
|
|
262
256
|
function buildRouteTreeConfig(nodes, exportName, disableTypes, depth = 1) {
|
|
263
|
-
const children = nodes.filter((n) => {
|
|
264
|
-
var _a;
|
|
265
|
-
return (_a = n.exports) == null ? void 0 : _a.includes(exportName);
|
|
266
|
-
}).map((node) => {
|
|
267
|
-
var _a, _b;
|
|
257
|
+
const children = nodes.filter((n) => n.exports?.includes(exportName)).map((node) => {
|
|
268
258
|
if (node._fsRouteType === "__root") {
|
|
269
259
|
return;
|
|
270
260
|
}
|
|
271
|
-
if (node._fsRouteType === "pathless_layout" && !
|
|
261
|
+
if (node._fsRouteType === "pathless_layout" && !node.children?.length) {
|
|
272
262
|
return;
|
|
273
263
|
}
|
|
274
264
|
const route = `${node.variableName}`;
|
|
275
|
-
if (
|
|
265
|
+
if (node.children?.length) {
|
|
276
266
|
const childConfigs = buildRouteTreeConfig(
|
|
277
267
|
node.children,
|
|
278
268
|
exportName,
|
|
@@ -280,18 +270,12 @@ function buildRouteTreeConfig(nodes, exportName, disableTypes, depth = 1) {
|
|
|
280
270
|
depth + 1
|
|
281
271
|
);
|
|
282
272
|
const childrenDeclaration = disableTypes ? "" : `interface ${route}${exportName}Children {
|
|
283
|
-
${node.children.filter((n) =>
|
|
284
|
-
var _a2;
|
|
285
|
-
return (_a2 = n.exports) == null ? void 0 : _a2.includes(exportName);
|
|
286
|
-
}).map(
|
|
273
|
+
${node.children.filter((n) => n.exports?.includes(exportName)).map(
|
|
287
274
|
(child) => `${child.variableName}${exportName}: typeof ${getResolvedRouteNodeVariableName(child, exportName)}`
|
|
288
275
|
).join(",")}
|
|
289
276
|
}`;
|
|
290
277
|
const children2 = `const ${route}${exportName}Children${disableTypes ? "" : `: ${route}${exportName}Children`} = {
|
|
291
|
-
${node.children.filter((n) =>
|
|
292
|
-
var _a2;
|
|
293
|
-
return (_a2 = n.exports) == null ? void 0 : _a2.includes(exportName);
|
|
294
|
-
}).map(
|
|
278
|
+
${node.children.filter((n) => n.exports?.includes(exportName)).map(
|
|
295
279
|
(child) => `${child.variableName}${exportName}: ${getResolvedRouteNodeVariableName(child, exportName)}`
|
|
296
280
|
).join(",")}
|
|
297
281
|
}`;
|
|
@@ -335,16 +319,14 @@ function mergeImportDeclarations(imports) {
|
|
|
335
319
|
return Object.values(merged);
|
|
336
320
|
}
|
|
337
321
|
function hasChildWithExport(node, exportName) {
|
|
338
|
-
|
|
339
|
-
return ((_a = node.children) == null ? void 0 : _a.some((child) => hasChildWithExport(child))) ?? false;
|
|
322
|
+
return node.children?.some((child) => hasChildWithExport(child)) ?? false;
|
|
340
323
|
}
|
|
341
324
|
const findParent = (node, exportName) => {
|
|
342
|
-
var _a;
|
|
343
325
|
if (!node) {
|
|
344
326
|
return `root${exportName}Import`;
|
|
345
327
|
}
|
|
346
328
|
if (node.parent) {
|
|
347
|
-
if (
|
|
329
|
+
if (node.parent.exports?.includes(exportName)) {
|
|
348
330
|
if (node.isVirtualParentRequired) {
|
|
349
331
|
return `${node.parent.variableName}${exportName}`;
|
|
350
332
|
} else {
|
|
@@ -358,10 +340,9 @@ function buildFileRoutesByPathInterface(opts) {
|
|
|
358
340
|
return `declare module '${opts.module}' {
|
|
359
341
|
interface ${opts.interfaceName} {
|
|
360
342
|
${opts.routeNodes.map((routeNode) => {
|
|
361
|
-
var _a;
|
|
362
343
|
const filePathId = routeNode.routePath;
|
|
363
344
|
let preloaderRoute = "";
|
|
364
|
-
if (
|
|
345
|
+
if (routeNode.exports?.includes(opts.exportName)) {
|
|
365
346
|
preloaderRoute = `typeof ${routeNode.variableName}${opts.exportName}Import`;
|
|
366
347
|
} else {
|
|
367
348
|
preloaderRoute = "unknown";
|