gt 2.23.2 → 2.24.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/CHANGELOG.md +23 -0
- package/dist/cli/base.js +23 -15
- package/dist/cli/base.js.map +1 -1
- package/dist/cli/flags.js +3 -2
- package/dist/cli/flags.js.map +1 -1
- package/dist/formats/files/postprocess/localizeMintlifyRedirects.d.ts +16 -0
- package/dist/formats/files/postprocess/localizeMintlifyRedirects.js +122 -0
- package/dist/formats/files/postprocess/localizeMintlifyRedirects.js.map +1 -0
- package/dist/fs/config/setupConfig.d.ts +14 -1
- package/dist/fs/config/setupConfig.js +33 -9
- package/dist/fs/config/setupConfig.js.map +1 -1
- package/dist/fs/createLoadTranslationsFile.js +1 -1
- package/dist/fs/createLoadTranslationsFile.js.map +1 -1
- package/dist/generated/version.d.ts +1 -1
- package/dist/generated/version.js +1 -1
- package/dist/generated/version.js.map +1 -1
- package/dist/react/config/createESBuildConfig.d.ts +1 -1
- package/dist/react/config/createESBuildConfig.js.map +1 -1
- package/dist/react/parse/createDictionaryUpdates.d.ts +1 -1
- package/dist/react/parse/createDictionaryUpdates.js +1 -1
- package/dist/react/parse/createDictionaryUpdates.js.map +1 -1
- package/dist/setup/buildTools/index.d.ts +2 -0
- package/dist/setup/buildTools/index.js +2 -1
- package/dist/setup/buildTools/index.js.map +1 -1
- package/dist/setup/buildTools/tanstackStart/edits.d.ts +21 -0
- package/dist/setup/buildTools/tanstackStart/edits.js +44 -0
- package/dist/setup/buildTools/tanstackStart/edits.js.map +1 -0
- package/dist/setup/buildTools/tanstackStart/index.d.ts +2 -0
- package/dist/setup/buildTools/tanstackStart/index.js +127 -0
- package/dist/setup/buildTools/tanstackStart/index.js.map +1 -0
- package/dist/setup/buildTools/tanstackStart/middleware.d.ts +9 -0
- package/dist/setup/buildTools/tanstackStart/middleware.js +59 -0
- package/dist/setup/buildTools/tanstackStart/middleware.js.map +1 -0
- package/dist/setup/buildTools/tanstackStart/root.d.ts +30 -0
- package/dist/setup/buildTools/tanstackStart/root.js +178 -0
- package/dist/setup/buildTools/tanstackStart/root.js.map +1 -0
- package/dist/setup/buildTools/tanstackStart/router.d.ts +15 -0
- package/dist/setup/buildTools/tanstackStart/router.js +64 -0
- package/dist/setup/buildTools/tanstackStart/router.js.map +1 -0
- package/dist/setup/buildTools/tanstackStart/source.d.ts +19 -0
- package/dist/setup/buildTools/tanstackStart/source.js +66 -0
- package/dist/setup/buildTools/tanstackStart/source.js.map +1 -0
- package/dist/setup/buildTools/vite.d.ts +1 -0
- package/dist/setup/buildTools/vite.js +3 -3
- package/dist/setup/buildTools/vite.js.map +1 -1
- package/dist/setup/detectFramework.d.ts +1 -1
- package/dist/setup/detectFramework.js +5 -1
- package/dist/setup/detectFramework.js.map +1 -1
- package/dist/setup/developmentCredentials.d.ts +1 -0
- package/dist/setup/developmentCredentials.js +12 -4
- package/dist/setup/developmentCredentials.js.map +1 -1
- package/dist/setup/frameworkUtils.js +4 -1
- package/dist/setup/frameworkUtils.js.map +1 -1
- package/dist/setup/onboarding.js +3 -3
- package/dist/setup/onboarding.js.map +1 -1
- package/dist/setup/setupViteSPA.d.ts +10 -1
- package/dist/setup/setupViteSPA.js +16 -3
- package/dist/setup/setupViteSPA.js.map +1 -1
- package/dist/setup/wizard.js +13 -2
- package/dist/setup/wizard.js.map +1 -1
- package/dist/state/orphanedFileNames.d.ts +4 -0
- package/dist/state/orphanedFileNames.js +16 -0
- package/dist/state/orphanedFileNames.js.map +1 -0
- package/dist/types/index.d.ts +2 -1
- package/dist/types/index.js +2 -1
- package/dist/types/index.js.map +1 -1
- package/dist/utils/constants.d.ts +1 -0
- package/dist/utils/constants.js +2 -1
- package/dist/utils/constants.js.map +1 -1
- package/dist/utils/credentials.js +2 -1
- package/dist/utils/credentials.js.map +1 -1
- package/dist/utils/localizeStaticUrls.d.ts +6 -0
- package/dist/utils/localizeStaticUrls.js +1 -1
- package/dist/utils/localizeStaticUrls.js.map +1 -1
- package/dist/utils/packageManager.js +21 -11
- package/dist/utils/packageManager.js.map +1 -1
- package/dist/workflows/steps/UploadSourcesStep.js +3 -0
- package/dist/workflows/steps/UploadSourcesStep.js.map +1 -1
- package/package.json +4 -3
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
import { DEFAULT_VITE_TRANSLATIONS_DIR } from "../../../utils/constants.js";
|
|
2
|
+
import { getViteLoaderExport, parseModule, writeViteLoader } from "../../setupViteSPA.js";
|
|
3
|
+
import { VITE_LOADER_FILE, viteSetup } from "../vite.js";
|
|
4
|
+
import { applyEdits, getCodeStyle, getImportEdit } from "./edits.js";
|
|
5
|
+
import { DOCS_URL, inspectTanStackStart, readSourceFile } from "./source.js";
|
|
6
|
+
import { START_CONTENT, getMiddlewareAction, registersMiddleware } from "./middleware.js";
|
|
7
|
+
import { configureRootRoute, findRootComponent, getRootFix, rendersElement } from "./root.js";
|
|
8
|
+
import { findInitializeCall, getRouterLines, getStorageAction, passesLoader } from "./router.js";
|
|
9
|
+
import path from "node:path";
|
|
10
|
+
import fs from "node:fs";
|
|
11
|
+
//#region src/setup/buildTools/tanstackStart/index.ts
|
|
12
|
+
async function writeLoader(ctx) {
|
|
13
|
+
const loader = await writeViteLoader({
|
|
14
|
+
...ctx,
|
|
15
|
+
create: true
|
|
16
|
+
});
|
|
17
|
+
return {
|
|
18
|
+
loader,
|
|
19
|
+
steps: loader === "created" || loader === "updated" ? [`${loader} ${VITE_LOADER_FILE}`] : []
|
|
20
|
+
};
|
|
21
|
+
}
|
|
22
|
+
const tanstackStartSetup = {
|
|
23
|
+
framework: "tanstack-start",
|
|
24
|
+
defaultTranslationsDir: DEFAULT_VITE_TRANSLATIONS_DIR,
|
|
25
|
+
initializer: "initializeGT",
|
|
26
|
+
ownsLoader: true,
|
|
27
|
+
skipsGTInstall: () => false,
|
|
28
|
+
devCredentialsOption: "--live-translations",
|
|
29
|
+
docsUrl: DOCS_URL,
|
|
30
|
+
async preflight(appDirectory) {
|
|
31
|
+
await inspectTanStackStart(appDirectory);
|
|
32
|
+
},
|
|
33
|
+
async syncLoader(ctx) {
|
|
34
|
+
const result = await viteSetup.syncLoader(ctx);
|
|
35
|
+
if (ctx.keepAppSource) return result;
|
|
36
|
+
const router = await readSourceFile(ctx.appDirectory, "src/router");
|
|
37
|
+
const initializeCall = router && findInitializeCall(router);
|
|
38
|
+
if (!initializeCall || passesLoader(router, initializeCall.arguments[0], ctx) !== false) return result;
|
|
39
|
+
const { loader, steps } = await writeLoader(ctx);
|
|
40
|
+
const loaderExport = await getViteLoaderExport(ctx.appDirectory, loader);
|
|
41
|
+
return {
|
|
42
|
+
steps: [...result.steps, ...steps],
|
|
43
|
+
manualActions: loaderExport ? [...result.manualActions, getStorageAction(router, ctx, loaderExport, false)] : result.manualActions
|
|
44
|
+
};
|
|
45
|
+
},
|
|
46
|
+
async apply(ctx) {
|
|
47
|
+
const { appDirectory, translationsDir } = ctx;
|
|
48
|
+
const { router, root, start } = await inspectTanStackStart(appDirectory);
|
|
49
|
+
const steps = [];
|
|
50
|
+
const manualActions = [];
|
|
51
|
+
const writeSource = async (file, content) => {
|
|
52
|
+
await fs.promises.writeFile(path.join(appDirectory, file), content);
|
|
53
|
+
};
|
|
54
|
+
let loaderExport;
|
|
55
|
+
if (translationsDir) {
|
|
56
|
+
const { loader, steps: loaderSteps } = await writeLoader({
|
|
57
|
+
...ctx,
|
|
58
|
+
translationsDir
|
|
59
|
+
});
|
|
60
|
+
steps.push(...loaderSteps);
|
|
61
|
+
loaderExport = await getViteLoaderExport(appDirectory, loader);
|
|
62
|
+
if (loader === "custom") manualActions.push(loaderExport ? {
|
|
63
|
+
whatHappened: `Your custom ${VITE_LOADER_FILE} was preserved`,
|
|
64
|
+
fix: `Verify ${VITE_LOADER_FILE} loads translations from ${translationsDir}`
|
|
65
|
+
} : {
|
|
66
|
+
whatHappened: `Your custom ${VITE_LOADER_FILE} has no runtime loadTranslations export`,
|
|
67
|
+
fix: `Export a default or named loadTranslations function from ${VITE_LOADER_FILE} that loads translations from ${translationsDir}, then rerun gt init`
|
|
68
|
+
});
|
|
69
|
+
}
|
|
70
|
+
const parses = (file, content) => content !== void 0 && parseModule(content, file.path) !== void 0 ? content : void 0;
|
|
71
|
+
const initializeCall = findInitializeCall(router);
|
|
72
|
+
let routerReady = initializeCall !== void 0;
|
|
73
|
+
let configuredRouter;
|
|
74
|
+
const wantsLoader = Boolean(translationsDir);
|
|
75
|
+
const loaderPassed = passesLoader(router, initializeCall?.arguments[0], ctx);
|
|
76
|
+
if (loaderPassed !== void 0 && loaderPassed !== wantsLoader && (!translationsDir || loaderExport)) manualActions.push(getStorageAction(router, ctx, loaderExport, loaderPassed));
|
|
77
|
+
if (!routerReady && (!translationsDir || loaderExport)) {
|
|
78
|
+
if (router.statements && !/\binitializeGT\b/.test(router.content)) {
|
|
79
|
+
const style = getCodeStyle(router.content, router.statements);
|
|
80
|
+
configuredRouter = parses(router, applyEdits(router.content, [getImportEdit(router.statements, getRouterLines(router, ctx, loaderExport, style), style.eol)]));
|
|
81
|
+
}
|
|
82
|
+
routerReady = configuredRouter !== void 0;
|
|
83
|
+
if (!routerReady) {
|
|
84
|
+
const lines = getRouterLines(router, ctx, loaderExport, {
|
|
85
|
+
quote: "'",
|
|
86
|
+
semi: ";"
|
|
87
|
+
});
|
|
88
|
+
manualActions.push({
|
|
89
|
+
whatHappened: `${router.path} was not configured automatically`,
|
|
90
|
+
fix: `Initialize GT after the imports in ${router.path}: ${lines.filter(Boolean).join(" ")}, then rerun gt init (see ${DOCS_URL})`
|
|
91
|
+
});
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
const startReady = !start || registersMiddleware(start);
|
|
95
|
+
if (!startReady) manualActions.push(getMiddlewareAction(start.path));
|
|
96
|
+
const rootComponent = root.statements && findRootComponent(root.statements);
|
|
97
|
+
const rootConfigured = rendersElement([rootComponent?.component, rootComponent?.document], "GTProvider");
|
|
98
|
+
const providerElsewhere = !rootConfigured && rendersElement(root.statements ?? [], "GTProvider");
|
|
99
|
+
const configuredRoot = rootConfigured || providerElsewhere ? void 0 : parses(root, configureRootRoute(root));
|
|
100
|
+
if (!rootConfigured && !configuredRoot) manualActions.push({
|
|
101
|
+
whatHappened: providerElsewhere ? `${root.path} renders GTProvider outside the root route's document` : `${root.path} does not match the create-start root route`,
|
|
102
|
+
fix: getRootFix(root.path)
|
|
103
|
+
});
|
|
104
|
+
if (routerReady) {
|
|
105
|
+
if (!start) {
|
|
106
|
+
await writeSource("src/start.ts", START_CONTENT);
|
|
107
|
+
steps.push("created src/start.ts");
|
|
108
|
+
}
|
|
109
|
+
if (configuredRouter) {
|
|
110
|
+
await writeSource(router.path, configuredRouter);
|
|
111
|
+
steps.push(`configured ${router.path}`);
|
|
112
|
+
}
|
|
113
|
+
if (configuredRoot && startReady) {
|
|
114
|
+
await writeSource(root.path, configuredRoot);
|
|
115
|
+
steps.push(`configured ${root.path}`);
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
return {
|
|
119
|
+
steps,
|
|
120
|
+
manualActions
|
|
121
|
+
};
|
|
122
|
+
}
|
|
123
|
+
};
|
|
124
|
+
//#endregion
|
|
125
|
+
export { tanstackStartSetup };
|
|
126
|
+
|
|
127
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../../../../src/setup/buildTools/tanstackStart/index.ts"],"sourcesContent":["// TanStack Start setup: configures src/router.tsx, src/start.ts and\n// src/routes/__root.tsx in dependency order, or reports manual steps.\nimport fs from 'node:fs';\nimport path from 'node:path';\nimport { DEFAULT_VITE_TRANSLATIONS_DIR } from '../../../utils/constants.js';\nimport {\n getViteLoaderExport,\n parseModule,\n writeViteLoader,\n type ViteLoaderExport,\n type ViteLoaderResult,\n} from '../../setupViteSPA.js';\nimport type {\n BuildToolContext,\n BuildToolSetup,\n ManualAction,\n} from '../index.js';\nimport { VITE_LOADER_FILE, viteSetup } from '../vite.js';\nimport { applyEdits, getCodeStyle, getImportEdit } from './edits.js';\nimport {\n getMiddlewareAction,\n registersMiddleware,\n START_CONTENT,\n} from './middleware.js';\nimport {\n configureRootRoute,\n findRootComponent,\n getRootFix,\n rendersElement,\n} from './root.js';\nimport {\n findInitializeCall,\n getRouterLines,\n getStorageAction,\n passesLoader,\n} from './router.js';\nimport {\n DOCS_URL,\n inspectTanStackStart,\n readSourceFile,\n type SourceFile,\n} from './source.js';\n\nasync function writeLoader(\n ctx: BuildToolContext & { translationsDir: string }\n): Promise<{ loader: ViteLoaderResult; steps: string[] }> {\n const loader = await writeViteLoader({ ...ctx, create: true });\n const changed = loader === 'created' || loader === 'updated';\n return { loader, steps: changed ? [`${loader} ${VITE_LOADER_FILE}`] : [] };\n}\n\nexport const tanstackStartSetup: BuildToolSetup = {\n framework: 'tanstack-start',\n defaultTranslationsDir: DEFAULT_VITE_TRANSLATIONS_DIR,\n initializer: 'initializeGT',\n ownsLoader: true,\n skipsGTInstall: () => false,\n devCredentialsOption: '--live-translations',\n docsUrl: DOCS_URL,\n async preflight(appDirectory) {\n await inspectTanStackStart(appDirectory);\n },\n // The loader is the same file Vite generates, but a router that loads from\n // the CDN also needs the loader passed to initializeGT.\n async syncLoader(ctx) {\n const result = await viteSetup.syncLoader(ctx);\n if (ctx.keepAppSource) return result;\n const router = await readSourceFile(ctx.appDirectory, 'src/router');\n const initializeCall = router && findInitializeCall(router);\n if (\n !initializeCall ||\n passesLoader(router, initializeCall.arguments[0], ctx) !== false\n ) {\n return result;\n }\n const { loader, steps } = await writeLoader(ctx);\n const loaderExport = await getViteLoaderExport(ctx.appDirectory, loader);\n return {\n steps: [...result.steps, ...steps],\n manualActions: loaderExport\n ? [\n ...result.manualActions,\n getStorageAction(router, ctx, loaderExport, false),\n ]\n : result.manualActions,\n };\n },\n async apply(ctx) {\n const { appDirectory, translationsDir } = ctx;\n const { router, root, start } = await inspectTanStackStart(appDirectory);\n const steps: string[] = [];\n const manualActions: ManualAction[] = [];\n const writeSource = async (file: string, content: string) => {\n await fs.promises.writeFile(path.join(appDirectory, file), content);\n };\n\n let loaderExport: ViteLoaderExport;\n if (translationsDir) {\n const { loader, steps: loaderSteps } = await writeLoader({\n ...ctx,\n translationsDir,\n });\n steps.push(...loaderSteps);\n loaderExport = await getViteLoaderExport(appDirectory, loader);\n if (loader === 'custom') {\n manualActions.push(\n loaderExport\n ? {\n whatHappened: `Your custom ${VITE_LOADER_FILE} was preserved`,\n fix: `Verify ${VITE_LOADER_FILE} loads translations from ${translationsDir}`,\n }\n : {\n whatHappened: `Your custom ${VITE_LOADER_FILE} has no runtime loadTranslations export`,\n fix: `Export a default or named loadTranslations function from ${VITE_LOADER_FILE} that loads translations from ${translationsDir}, then rerun gt init`,\n }\n );\n }\n }\n\n // An insertion that breaks the file's syntax falls back to manual setup.\n const parses = (file: SourceFile, content: string | undefined) =>\n content !== undefined && parseModule(content, file.path) !== undefined\n ? content\n : undefined;\n\n const initializeCall = findInitializeCall(router);\n let routerReady = initializeCall !== undefined;\n let configuredRouter: string | undefined;\n // Storage chosen on a rerun must match how the router loads translations.\n const wantsLoader = Boolean(translationsDir);\n const loaderPassed = passesLoader(\n router,\n initializeCall?.arguments[0],\n ctx\n );\n if (\n loaderPassed !== undefined &&\n loaderPassed !== wantsLoader &&\n (!translationsDir || loaderExport)\n ) {\n manualActions.push(\n getStorageAction(router, ctx, loaderExport, loaderPassed)\n );\n }\n // A custom loader without an export already has its own action.\n if (!routerReady && (!translationsDir || loaderExport)) {\n // Any other mention may be an app-owned initializer; a second\n // initializeGT call would override it.\n if (router.statements && !/\\binitializeGT\\b/.test(router.content)) {\n const style = getCodeStyle(router.content, router.statements);\n configuredRouter = parses(\n router,\n applyEdits(router.content, [\n getImportEdit(\n router.statements,\n getRouterLines(router, ctx, loaderExport, style),\n style.eol\n ),\n ])\n );\n }\n routerReady = configuredRouter !== undefined;\n if (!routerReady) {\n const lines = getRouterLines(router, ctx, loaderExport, {\n quote: \"'\",\n semi: ';',\n });\n manualActions.push({\n whatHappened: `${router.path} was not configured automatically`,\n fix: `Initialize GT after the imports in ${router.path}: ${lines.filter(Boolean).join(' ')}, then rerun gt init (see ${DOCS_URL})`,\n });\n }\n }\n\n const startReady = !start || registersMiddleware(start);\n if (!startReady) {\n manualActions.push(getMiddlewareAction(start!.path));\n }\n\n const rootComponent = root.statements && findRootComponent(root.statements);\n const rootConfigured = rendersElement(\n [rootComponent?.component, rootComponent?.document],\n 'GTProvider'\n );\n // A provider elsewhere may wrap the document indirectly; adding a second\n // one could nest them, so a person decides.\n const providerElsewhere =\n !rootConfigured && rendersElement(root.statements ?? [], 'GTProvider');\n const configuredRoot =\n rootConfigured || providerElsewhere\n ? undefined\n : parses(root, configureRootRoute(root));\n if (!rootConfigured && !configuredRoot) {\n manualActions.push({\n whatHappened: providerElsewhere\n ? `${root.path} renders GTProvider outside the root route's document`\n : `${root.path} does not match the create-start root route`,\n fix: getRootFix(root.path),\n });\n }\n\n // gtMiddleware and the root loader need initializeGT to have run, so\n // they are only added alongside a router that calls it; the actions\n // above ask for a rerun to finish.\n if (routerReady) {\n if (!start) {\n await writeSource('src/start.ts', START_CONTENT);\n steps.push('created src/start.ts');\n }\n if (configuredRouter) {\n await writeSource(router.path, configuredRouter);\n steps.push(`configured ${router.path}`);\n }\n // The root loader reads the request scope gtMiddleware sets up, so\n // without it every page would fail to render.\n if (configuredRoot && startReady) {\n await writeSource(root.path, configuredRoot);\n steps.push(`configured ${root.path}`);\n }\n }\n\n return { steps, manualActions };\n },\n};\n"],"mappings":";;;;;;;;;;;AA2CA,eAAe,YACb,KACwD;CACxD,MAAM,SAAS,MAAM,gBAAgB;EAAE,GAAG;EAAK,QAAQ;EAAM,CAAC;AAE9D,QAAO;EAAE;EAAQ,OADD,WAAW,aAAa,WAAW,YACjB,CAAC,GAAG,OAAO,GAAG,mBAAmB,GAAG,EAAE;EAAE;;AAG5E,MAAa,qBAAqC;CAChD,WAAW;CACX,wBAAwB;CACxB,aAAa;CACb,YAAY;CAC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nD,aACD;EAGD,MAAM,oBACJ,CAAC,kBAAkB,eAAe,KAAK,cAAc,EAAE,EAAE,aAAa;EACxE,MAAM,iBACJ,kBAAkB,oBACd,KAAA,IACA,OAAO,MAAM,mBAAmB,KAAK,CAAC;AAC5C,MAAI,CAAC,kBAAkB,CAAC,eACtB,eAAc,KAAK;GACjB,cAAc,oBACV,GAAG,KAAK,KAAK,yDACb,GAAG,KAAK,KAAK;GACjB,KAAK,WAAW,KAAK,KAAK;GAC3B,CAAC;AAMJ,MAAI,aAAa;AACf,OAAI,CAAC,OAAO;AACV,UAAM,YAAY,gBAAgB,cAAc;AAChD,UAAM,KAAK,uBAAuB;;AAEpC,OAAI,kBAAkB;AACpB,UAAM,YAAY,OAAO,MAAM,iBAAiB;AAChD,UAAM,KAAK,cAAc,OAAO,OAAO;;AAIzC,OAAI,kBAAkB,YAAY;AAChC,UAAM,YAAY,KAAK,MAAM,eAAe;AAC5C,UAAM,KAAK,cAAc,KAAK,OAAO;;;AAIzC,SAAO;GAAE;GAAO;GAAe;;CAElC"}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import type { ManualAction } from '../index.js';
|
|
2
|
+
import { type SourceFile } from './source.js';
|
|
3
|
+
export declare const START_CONTENT = "import { createCsrfMiddleware, createStart } from '@tanstack/react-start';\nimport { gtMiddleware } from 'gt-tanstack-start';\n\nconst csrfMiddleware = createCsrfMiddleware({\n filter: ({ handlerType }) => handlerType === 'serverFn',\n});\n\nexport const startInstance = createStart(() => ({\n requestMiddleware: [csrfMiddleware, gtMiddleware],\n}));\n";
|
|
4
|
+
/**
|
|
5
|
+
* Whether the imported gtMiddleware is in the one requestMiddleware array of
|
|
6
|
+
* the startInstance options. A spread or computed key could override it.
|
|
7
|
+
*/
|
|
8
|
+
export declare function registersMiddleware(start: SourceFile): boolean;
|
|
9
|
+
export declare function getMiddlewareAction(startPath: string): ManualAction;
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import "../../../types/libraries.js";
|
|
2
|
+
import { DOCS_URL, getLocalImport, getPropertyName } from "./source.js";
|
|
3
|
+
import * as t from "@babel/types";
|
|
4
|
+
//#region src/setup/buildTools/tanstackStart/middleware.ts
|
|
5
|
+
const START_CONTENT = `import { createCsrfMiddleware, createStart } from '@tanstack/react-start';
|
|
6
|
+
import { gtMiddleware } from 'gt-tanstack-start';
|
|
7
|
+
|
|
8
|
+
const csrfMiddleware = createCsrfMiddleware({
|
|
9
|
+
filter: ({ handlerType }) => handlerType === 'serverFn',
|
|
10
|
+
});
|
|
11
|
+
|
|
12
|
+
export const startInstance = createStart(() => ({
|
|
13
|
+
requestMiddleware: [csrfMiddleware, gtMiddleware],
|
|
14
|
+
}));
|
|
15
|
+
`;
|
|
16
|
+
/**
|
|
17
|
+
* The options object returned by `export const startInstance = createStart(...)`,
|
|
18
|
+
* the entry Start reads. Only a callback that returns an object literal
|
|
19
|
+
* directly counts; any other shape is left for manual setup.
|
|
20
|
+
*/
|
|
21
|
+
function getStartOptions(start) {
|
|
22
|
+
const createStart = getLocalImport(start, "createStart", "@tanstack/react-start");
|
|
23
|
+
if (!createStart) return void 0;
|
|
24
|
+
for (const statement of start.statements ?? []) {
|
|
25
|
+
if (statement.type !== "ExportNamedDeclaration") continue;
|
|
26
|
+
if (statement.declaration?.type !== "VariableDeclaration") continue;
|
|
27
|
+
for (const { id, init } of statement.declaration.declarations) {
|
|
28
|
+
if (!t.isIdentifier(id, { name: "startInstance" }) || init?.type !== "CallExpression" || !t.isIdentifier(init.callee, { name: createStart })) continue;
|
|
29
|
+
const getOptions = init.arguments[0];
|
|
30
|
+
if (getOptions?.type !== "ArrowFunctionExpression" && getOptions?.type !== "FunctionExpression") return;
|
|
31
|
+
const { body } = getOptions;
|
|
32
|
+
const options = body.type !== "BlockStatement" ? body : body.body.length === 1 && body.body[0].type === "ReturnStatement" ? body.body[0].argument : void 0;
|
|
33
|
+
return options?.type === "ObjectExpression" ? options : void 0;
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* Whether the imported gtMiddleware is in the one requestMiddleware array of
|
|
39
|
+
* the startInstance options. A spread or computed key could override it.
|
|
40
|
+
*/
|
|
41
|
+
function registersMiddleware(start) {
|
|
42
|
+
const local = getLocalImport(start, "gtMiddleware");
|
|
43
|
+
const options = local ? getStartOptions(start) : void 0;
|
|
44
|
+
if (!options) return false;
|
|
45
|
+
const names = options.properties.map(getPropertyName);
|
|
46
|
+
if (names.includes(void 0) || names.filter((name) => name === "requestMiddleware").length !== 1) return false;
|
|
47
|
+
const middleware = options.properties[names.indexOf("requestMiddleware")];
|
|
48
|
+
return middleware.type === "ObjectProperty" && middleware.value.type === "ArrayExpression" && middleware.value.elements.some((element) => t.isIdentifier(element, { name: local }));
|
|
49
|
+
}
|
|
50
|
+
function getMiddlewareAction(startPath) {
|
|
51
|
+
return {
|
|
52
|
+
whatHappened: `${startPath} does not use gtMiddleware`,
|
|
53
|
+
fix: `Import { gtMiddleware } from 'gt-tanstack-start' in ${startPath} and add it to the requestMiddleware of createStart, keeping your existing middleware such as the CSRF middleware, then rerun gt init (see ${DOCS_URL})`
|
|
54
|
+
};
|
|
55
|
+
}
|
|
56
|
+
//#endregion
|
|
57
|
+
export { START_CONTENT, getMiddlewareAction, registersMiddleware };
|
|
58
|
+
|
|
59
|
+
//# sourceMappingURL=middleware.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"middleware.js","names":[],"sources":["../../../../src/setup/buildTools/tanstackStart/middleware.ts"],"sourcesContent":["// src/start.ts: the generated entry and gtMiddleware registration.\nimport * as t from '@babel/types';\nimport { Libraries } from '../../../types/libraries.js';\nimport type { ManualAction } from '../index.js';\nimport {\n DOCS_URL,\n getLocalImport,\n getPropertyName,\n type SourceFile,\n} from './source.js';\n\nexport const START_CONTENT = `import { createCsrfMiddleware, createStart } from '@tanstack/react-start';\nimport { gtMiddleware } from '${Libraries.GT_TANSTACK_START}';\n\nconst csrfMiddleware = createCsrfMiddleware({\n filter: ({ handlerType }) => handlerType === 'serverFn',\n});\n\nexport const startInstance = createStart(() => ({\n requestMiddleware: [csrfMiddleware, gtMiddleware],\n}));\n`;\n\n/**\n * The options object returned by `export const startInstance = createStart(...)`,\n * the entry Start reads. Only a callback that returns an object literal\n * directly counts; any other shape is left for manual setup.\n */\nfunction getStartOptions(start: SourceFile): t.ObjectExpression | undefined {\n const createStart = getLocalImport(\n start,\n 'createStart',\n '@tanstack/react-start'\n );\n if (!createStart) return undefined;\n for (const statement of start.statements ?? []) {\n if (statement.type !== 'ExportNamedDeclaration') continue;\n if (statement.declaration?.type !== 'VariableDeclaration') continue;\n for (const { id, init } of statement.declaration.declarations) {\n if (\n !t.isIdentifier(id, { name: 'startInstance' }) ||\n init?.type !== 'CallExpression' ||\n !t.isIdentifier(init.callee, { name: createStart })\n ) {\n continue;\n }\n const getOptions = init.arguments[0];\n if (\n getOptions?.type !== 'ArrowFunctionExpression' &&\n getOptions?.type !== 'FunctionExpression'\n ) {\n return undefined;\n }\n const { body } = getOptions;\n const options =\n body.type !== 'BlockStatement'\n ? body\n : body.body.length === 1 && body.body[0].type === 'ReturnStatement'\n ? body.body[0].argument\n : undefined;\n return options?.type === 'ObjectExpression' ? options : undefined;\n }\n }\n return undefined;\n}\n\n/**\n * Whether the imported gtMiddleware is in the one requestMiddleware array of\n * the startInstance options. A spread or computed key could override it.\n */\nexport function registersMiddleware(start: SourceFile): boolean {\n const local = getLocalImport(start, 'gtMiddleware');\n const options = local ? getStartOptions(start) : undefined;\n if (!options) return false;\n const names = options.properties.map(getPropertyName);\n if (\n names.includes(undefined) ||\n names.filter((name) => name === 'requestMiddleware').length !== 1\n ) {\n return false;\n }\n const middleware = options.properties[names.indexOf('requestMiddleware')];\n return (\n middleware.type === 'ObjectProperty' &&\n middleware.value.type === 'ArrayExpression' &&\n middleware.value.elements.some((element) =>\n t.isIdentifier(element, { name: local })\n )\n );\n}\n\nexport function getMiddlewareAction(startPath: string): ManualAction {\n return {\n whatHappened: `${startPath} does not use gtMiddleware`,\n fix: `Import { gtMiddleware } from '${Libraries.GT_TANSTACK_START}' in ${startPath} and add it to the requestMiddleware of createStart, keeping your existing middleware such as the CSRF middleware, then rerun gt init (see ${DOCS_URL})`,\n };\n}\n"],"mappings":";;;;AAWA,MAAa,gBAAgB;;;;;;;;;;;;;;;;AAiB7B,SAAS,gBAAgB,OAAmD;CAC1E,MAAM,cAAc,eAClB,OACA,eACA,wBACD;AACD,KAAI,CAAC,YAAa,QAAO,KAAA;AACzB,MAAK,MAAM,aAAa,MAAM,cAAc,EAAE,EAAE;AAC9C,MAAI,UAAU,SAAS,yBAA0B;AACjD,MAAI,UAAU,aAAa,SAAS,sBAAuB;AAC3D,OAAK,MAAM,EAAE,IAAI,UAAU,UAAU,YAAY,cAAc;AAC7D,OACE,CAAC,EAAE,aAAa,IAAI,EAAE,MAAM,iBAAiB,CAAC,IAC9C,MAAM,SAAS,oBACf,CAAC,EAAE,aAAa,KAAK,QAAQ,EAAE,MAAM,aAAa,CAAC,CAEnD;GAEF,MAAM,aAAa,KAAK,UAAU;AAClC,OACE,YAAY,SAAS,6BACrB,YAAY,SAAS,qBAErB;GAEF,MAAM,EAAE,SAAS;GACjB,MAAM,UACJ,KAAK,SAAS,mBACV,OACA,KAAK,KAAK,WAAW,KAAK,KAAK,KAAK,GAAG,SAAS,oBAC9C,KAAK,KAAK,GAAG,WACb,KAAA;AACR,UAAO,SAAS,SAAS,qBAAqB,UAAU,KAAA;;;;;;;;AAU9D,SAAgB,oBAAoB,OAA4B;CAC9D,MAAM,QAAQ,eAAe,OAAO,eAAe;CACnD,MAAM,UAAU,QAAQ,gBAAgB,MAAM,GAAG,KAAA;AACjD,KAAI,CAAC,QAAS,QAAO;CACrB,MAAM,QAAQ,QAAQ,WAAW,IAAI,gBAAgB;AACrD,KACE,MAAM,SAAS,KAAA,EAAU,IACzB,MAAM,QAAQ,SAAS,SAAS,oBAAoB,CAAC,WAAW,EAEhE,QAAO;CAET,MAAM,aAAa,QAAQ,WAAW,MAAM,QAAQ,oBAAoB;AACxE,QACE,WAAW,SAAS,oBACpB,WAAW,MAAM,SAAS,qBAC1B,WAAW,MAAM,SAAS,MAAM,YAC9B,EAAE,aAAa,SAAS,EAAE,MAAM,OAAO,CAAC,CACzC;;AAIL,SAAgB,oBAAoB,WAAiC;AACnE,QAAO;EACL,cAAc,GAAG,UAAU;EAC3B,KAAK,uDAAoE,UAAU,6IAA6I,SAAS;EAC1O"}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import * as t from '@babel/types';
|
|
2
|
+
import { type SourceFile } from './source.js';
|
|
3
|
+
export declare function rendersElement(nodes: (t.Node | undefined)[], name: string): boolean;
|
|
4
|
+
declare function findLocalFunction(statements: t.Statement[], name: string): t.ArrowFunctionExpression | t.FunctionDeclaration | t.FunctionExpression | undefined;
|
|
5
|
+
type LocalFunction = NonNullable<ReturnType<typeof findLocalFunction>>;
|
|
6
|
+
/**
|
|
7
|
+
* The root route, the local function its shellComponent or component names,
|
|
8
|
+
* and the local function that renders its document.
|
|
9
|
+
*/
|
|
10
|
+
export declare function findRootComponent(statements: t.Statement[]): {
|
|
11
|
+
rootRoute: {
|
|
12
|
+
routeName: string;
|
|
13
|
+
options: t.ObjectExpression;
|
|
14
|
+
};
|
|
15
|
+
componentProperty: t.ObjectMethod | t.ObjectProperty | t.SpreadElement | undefined;
|
|
16
|
+
component: t.ArrowFunctionExpression | t.FunctionDeclaration | t.FunctionExpression | undefined;
|
|
17
|
+
isShell: boolean;
|
|
18
|
+
document: LocalFunction | undefined;
|
|
19
|
+
} | undefined;
|
|
20
|
+
/**
|
|
21
|
+
* Configures the create-start root route: `createRootRoute({...})` (or its
|
|
22
|
+
* router-context form) without a loader, whose shellComponent renders
|
|
23
|
+
* `{children}` (or whose component renders `<Outlet />`) once in the `<body>`
|
|
24
|
+
* of a local `<html>` document, either directly or through one local document
|
|
25
|
+
* component that renders its `{children}` there. Returns undefined for any
|
|
26
|
+
* other shape.
|
|
27
|
+
*/
|
|
28
|
+
export declare function configureRootRoute({ content, statements, }: SourceFile): string | undefined;
|
|
29
|
+
export declare function getRootFix(rootPath: string): string;
|
|
30
|
+
export {};
|
|
@@ -0,0 +1,178 @@
|
|
|
1
|
+
import "../../../types/libraries.js";
|
|
2
|
+
import { applyEdits, getCodeStyle, getImportEdit, getLineIndent, getOwnLineIndent } from "./edits.js";
|
|
3
|
+
import { DOCS_URL, getPropertyName } from "./source.js";
|
|
4
|
+
import * as t from "@babel/types";
|
|
5
|
+
//#region src/setup/buildTools/tanstackStart/root.ts
|
|
6
|
+
function isJsxElementNamed(node, name) {
|
|
7
|
+
return node.type === "JSXElement" && t.isJSXIdentifier(node.openingElement.name, { name });
|
|
8
|
+
}
|
|
9
|
+
function isChildrenSlot(node) {
|
|
10
|
+
return node.type === "JSXExpressionContainer" && node.expression.type === "Identifier" && node.expression.name === "children";
|
|
11
|
+
}
|
|
12
|
+
function rendersElement(nodes, name) {
|
|
13
|
+
let found = false;
|
|
14
|
+
for (const node of nodes) t.traverseFast(node, (child) => {
|
|
15
|
+
if (isJsxElementNamed(child, name)) found = true;
|
|
16
|
+
});
|
|
17
|
+
return found;
|
|
18
|
+
}
|
|
19
|
+
function findLocalFunction(statements, name) {
|
|
20
|
+
for (const statement of statements) {
|
|
21
|
+
const declaration = statement.type === "ExportNamedDeclaration" ? statement.declaration : statement;
|
|
22
|
+
if (declaration?.type === "FunctionDeclaration" && declaration.id?.name === name) return declaration;
|
|
23
|
+
if (declaration?.type !== "VariableDeclaration") continue;
|
|
24
|
+
if (declaration.kind !== "const") continue;
|
|
25
|
+
for (const declarator of declaration.declarations) if (t.isIdentifier(declarator.id, { name }) && (declarator.init?.type === "ArrowFunctionExpression" || declarator.init?.type === "FunctionExpression")) return declarator.init;
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
function findRootRoute(statements) {
|
|
29
|
+
for (const statement of statements) {
|
|
30
|
+
const declaration = statement.type === "ExportNamedDeclaration" ? statement.declaration : statement;
|
|
31
|
+
if (declaration?.type !== "VariableDeclaration") continue;
|
|
32
|
+
for (const { id, init } of declaration.declarations) {
|
|
33
|
+
if (id.type !== "Identifier" || init?.type !== "CallExpression" || init.arguments[0]?.type !== "ObjectExpression") continue;
|
|
34
|
+
const { callee } = init;
|
|
35
|
+
if (callee.type === "Identifier" && callee.name === "createRootRoute" || callee.type === "CallExpression" && callee.arguments.length === 0 && callee.callee.type === "Identifier" && callee.callee.name === "createRootRouteWithContext") return {
|
|
36
|
+
routeName: id.name,
|
|
37
|
+
options: init.arguments[0]
|
|
38
|
+
};
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* The local function that renders the document: the route component itself
|
|
44
|
+
* when it renders `<html>`, or the one local component it returns with only
|
|
45
|
+
* the route's slot as its child. A followed document must render nowhere
|
|
46
|
+
* else: another render, such as an errorComponent, has no loader data.
|
|
47
|
+
*/
|
|
48
|
+
function findDocument(statements, component, isShell) {
|
|
49
|
+
if (rendersElement([component.body], "html")) return component;
|
|
50
|
+
const { body } = component;
|
|
51
|
+
const returned = body.type !== "BlockStatement" ? body : body.body.length === 1 && body.body[0].type === "ReturnStatement" ? body.body[0].argument : void 0;
|
|
52
|
+
if (returned?.type !== "JSXElement" || returned.openingElement.name.type !== "JSXIdentifier") return;
|
|
53
|
+
const children = returned.children.filter((child) => child.type !== "JSXText" || child.value.trim() !== "");
|
|
54
|
+
if (children.length !== 1 || !(isShell ? isChildrenSlot(children[0]) : isJsxElementNamed(children[0], "Outlet"))) return;
|
|
55
|
+
const { name } = returned.openingElement.name;
|
|
56
|
+
let uses = 0;
|
|
57
|
+
for (const statement of statements) t.traverseFast(statement, (node) => {
|
|
58
|
+
if (isJsxElementNamed(node, name) || t.isIdentifier(node, { name })) uses++;
|
|
59
|
+
});
|
|
60
|
+
if (uses !== 2) return void 0;
|
|
61
|
+
const document = findLocalFunction(statements, name);
|
|
62
|
+
return document && rendersElement([document.body], "html") ? document : void 0;
|
|
63
|
+
}
|
|
64
|
+
/**
|
|
65
|
+
* The root route, the local function its shellComponent or component names,
|
|
66
|
+
* and the local function that renders its document.
|
|
67
|
+
*/
|
|
68
|
+
function findRootComponent(statements) {
|
|
69
|
+
const rootRoute = findRootRoute(statements);
|
|
70
|
+
if (!rootRoute) return void 0;
|
|
71
|
+
const { properties } = rootRoute.options;
|
|
72
|
+
const componentProperty = properties.find((p) => getPropertyName(p) === "shellComponent") ?? properties.find((p) => getPropertyName(p) === "component");
|
|
73
|
+
const component = componentProperty?.type === "ObjectProperty" && componentProperty.value.type === "Identifier" ? findLocalFunction(statements, componentProperty.value.name) : void 0;
|
|
74
|
+
const isShell = componentProperty !== void 0 && getPropertyName(componentProperty) === "shellComponent";
|
|
75
|
+
return {
|
|
76
|
+
rootRoute,
|
|
77
|
+
componentProperty,
|
|
78
|
+
component,
|
|
79
|
+
isShell,
|
|
80
|
+
document: component && findDocument(statements, component, isShell)
|
|
81
|
+
};
|
|
82
|
+
}
|
|
83
|
+
/**
|
|
84
|
+
* Configures the create-start root route: `createRootRoute({...})` (or its
|
|
85
|
+
* router-context form) without a loader, whose shellComponent renders
|
|
86
|
+
* `{children}` (or whose component renders `<Outlet />`) once in the `<body>`
|
|
87
|
+
* of a local `<html>` document, either directly or through one local document
|
|
88
|
+
* component that renders its `{children}` there. Returns undefined for any
|
|
89
|
+
* other shape.
|
|
90
|
+
*/
|
|
91
|
+
function configureRootRoute({ content, statements }) {
|
|
92
|
+
if (!statements) return void 0;
|
|
93
|
+
if (/\b(?:getLocale|getTranslationsSnapshot)\b/.test(content)) return;
|
|
94
|
+
const found = findRootComponent(statements);
|
|
95
|
+
if (!found) return void 0;
|
|
96
|
+
const { rootRoute, componentProperty, component, isShell, document } = found;
|
|
97
|
+
const { properties } = rootRoute.options;
|
|
98
|
+
if (properties.some((property) => {
|
|
99
|
+
const name = getPropertyName(property);
|
|
100
|
+
return name === void 0 || name === "loader" || name === "beforeLoad" || name === "validateSearch";
|
|
101
|
+
})) return;
|
|
102
|
+
if (componentProperty?.type !== "ObjectProperty" || !component || document?.body.type !== "BlockStatement" || [component, document].some((fn) => /\b(?:locale|translations)\b/.test(content.slice(fn.start, fn.end)))) return;
|
|
103
|
+
const slotIsChildren = isShell || document !== component;
|
|
104
|
+
const htmlElements = [];
|
|
105
|
+
t.traverseFast(document.body, (node) => {
|
|
106
|
+
if (isJsxElementNamed(node, "html")) htmlElements.push(node);
|
|
107
|
+
});
|
|
108
|
+
if (htmlElements.length !== 1) return void 0;
|
|
109
|
+
const [html] = htmlElements;
|
|
110
|
+
const bodies = html.children.filter((child) => isJsxElementNamed(child, "body"));
|
|
111
|
+
if (bodies.length !== 1) return void 0;
|
|
112
|
+
const bodyContent = bodies[0].children.filter((child) => child.type !== "JSXText" || child.value.trim() !== "");
|
|
113
|
+
const scriptsIndex = bodyContent.findIndex((child) => isJsxElementNamed(child, "Scripts"));
|
|
114
|
+
const wrapped = scriptsIndex === -1 ? bodyContent : bodyContent.slice(0, scriptsIndex);
|
|
115
|
+
let slots = 0;
|
|
116
|
+
let multilineLiteral = false;
|
|
117
|
+
for (const child of wrapped) t.traverseFast(child, (node) => {
|
|
118
|
+
if (slotIsChildren ? isChildrenSlot(node) : isJsxElementNamed(node, "Outlet")) slots++;
|
|
119
|
+
if ((node.type === "TemplateLiteral" || node.type === "StringLiteral") && node.loc.start.line !== node.loc.end.line) multilineLiteral = true;
|
|
120
|
+
});
|
|
121
|
+
if (slots !== 1) return void 0;
|
|
122
|
+
const { attributes } = html.openingElement;
|
|
123
|
+
if (attributes.some((attribute) => attribute.type === "JSXSpreadAttribute")) return;
|
|
124
|
+
const lang = attributes.find((attribute) => attribute.type === "JSXAttribute" && t.isJSXIdentifier(attribute.name, { name: "lang" }));
|
|
125
|
+
if (lang && lang.value?.type !== "StringLiteral") return void 0;
|
|
126
|
+
const propertyIndent = getOwnLineIndent(content, componentProperty.start);
|
|
127
|
+
if (propertyIndent === void 0) return void 0;
|
|
128
|
+
const { quote, semi, eol, indent } = getCodeStyle(content, statements);
|
|
129
|
+
const first = wrapped[0];
|
|
130
|
+
const last = wrapped.at(-1);
|
|
131
|
+
const wrappedText = content.slice(first.start, last.end);
|
|
132
|
+
const wrappedIndent = getOwnLineIndent(content, first.start);
|
|
133
|
+
const nestedText = multilineLiteral ? wrappedText : wrappedText.replace(/\n(?=[ \t]*\S)/g, `\n${indent}`);
|
|
134
|
+
const provider = "<GTProvider locale={locale} translations={translations}>";
|
|
135
|
+
const firstStatement = document.body.body[0];
|
|
136
|
+
const statementIndent = (firstStatement && getOwnLineIndent(content, firstStatement.start)) ?? getLineIndent(content, document.start) + indent;
|
|
137
|
+
return applyEdits(content, [
|
|
138
|
+
getImportEdit(statements, [`import { GTProvider, getLocale, getTranslationsSnapshot } from ${quote}gt-tanstack-start${quote}${semi}`], eol),
|
|
139
|
+
{
|
|
140
|
+
start: componentProperty.start,
|
|
141
|
+
text: [
|
|
142
|
+
"loader: async () => {",
|
|
143
|
+
`${propertyIndent}${indent}const locale = getLocale()${semi}`,
|
|
144
|
+
`${propertyIndent}${indent}return { locale, translations: await getTranslationsSnapshot(locale) }${semi}`,
|
|
145
|
+
`${propertyIndent}},`,
|
|
146
|
+
propertyIndent
|
|
147
|
+
].join(eol)
|
|
148
|
+
},
|
|
149
|
+
{
|
|
150
|
+
start: document.body.start + 1,
|
|
151
|
+
text: `${eol}${statementIndent}const { locale, translations } = ${rootRoute.routeName}.useLoaderData()${semi}`
|
|
152
|
+
},
|
|
153
|
+
lang ? {
|
|
154
|
+
start: lang.start,
|
|
155
|
+
end: lang.end,
|
|
156
|
+
text: "lang={locale}"
|
|
157
|
+
} : {
|
|
158
|
+
start: html.openingElement.name.end,
|
|
159
|
+
text: " lang={locale}"
|
|
160
|
+
},
|
|
161
|
+
{
|
|
162
|
+
start: first.start,
|
|
163
|
+
end: last.end,
|
|
164
|
+
text: wrappedIndent === void 0 ? `${provider}${wrappedText}</GTProvider>` : [
|
|
165
|
+
provider,
|
|
166
|
+
`${wrappedIndent}${indent}${nestedText}`,
|
|
167
|
+
`${wrappedIndent}</GTProvider>`
|
|
168
|
+
].join(eol)
|
|
169
|
+
}
|
|
170
|
+
]);
|
|
171
|
+
}
|
|
172
|
+
function getRootFix(rootPath) {
|
|
173
|
+
return `In ${rootPath}, add loader: async () => { const locale = getLocale(); return { locale, translations: await getTranslationsSnapshot(locale) }; } to the root route options, read const { locale, translations } = Route.useLoaderData() in the document, set <html lang={locale}>, and wrap everything its <body> renders before <Scripts /> in <GTProvider locale={locale} translations={translations}>, importing GTProvider, getLocale and getTranslationsSnapshot from 'gt-tanstack-start' (see ${DOCS_URL})`;
|
|
174
|
+
}
|
|
175
|
+
//#endregion
|
|
176
|
+
export { configureRootRoute, findRootComponent, getRootFix, rendersElement };
|
|
177
|
+
|
|
178
|
+
//# sourceMappingURL=root.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"root.js","names":[],"sources":["../../../../src/setup/buildTools/tanstackStart/root.ts"],"sourcesContent":["// src/routes/__root.tsx: recognizing and configuring the root route.\nimport * as t from '@babel/types';\nimport { Libraries } from '../../../types/libraries.js';\nimport {\n applyEdits,\n getCodeStyle,\n getImportEdit,\n getLineIndent,\n getOwnLineIndent,\n} from './edits.js';\nimport { DOCS_URL, getPropertyName, type SourceFile } from './source.js';\n\nfunction isJsxElementNamed(node: t.Node, name: string): node is t.JSXElement {\n return (\n node.type === 'JSXElement' &&\n t.isJSXIdentifier(node.openingElement.name, { name })\n );\n}\n\nfunction isChildrenSlot(node: t.Node): boolean {\n return (\n node.type === 'JSXExpressionContainer' &&\n node.expression.type === 'Identifier' &&\n node.expression.name === 'children'\n );\n}\n\nexport function rendersElement(\n nodes: (t.Node | undefined)[],\n name: string\n): boolean {\n let found = false;\n for (const node of nodes) {\n t.traverseFast(node, (child) => {\n if (isJsxElementNamed(child, name)) found = true;\n });\n }\n return found;\n}\n\nfunction findLocalFunction(statements: t.Statement[], name: string) {\n for (const statement of statements) {\n const declaration =\n statement.type === 'ExportNamedDeclaration'\n ? statement.declaration\n : statement;\n if (\n declaration?.type === 'FunctionDeclaration' &&\n declaration.id?.name === name\n ) {\n return declaration;\n }\n if (declaration?.type !== 'VariableDeclaration') continue;\n if (declaration.kind !== 'const') continue;\n for (const declarator of declaration.declarations) {\n if (\n t.isIdentifier(declarator.id, { name }) &&\n (declarator.init?.type === 'ArrowFunctionExpression' ||\n declarator.init?.type === 'FunctionExpression')\n ) {\n return declarator.init;\n }\n }\n }\n return undefined;\n}\n\nfunction findRootRoute(statements: t.Statement[]) {\n for (const statement of statements) {\n const declaration =\n statement.type === 'ExportNamedDeclaration'\n ? statement.declaration\n : statement;\n if (declaration?.type !== 'VariableDeclaration') continue;\n for (const { id, init } of declaration.declarations) {\n if (\n id.type !== 'Identifier' ||\n init?.type !== 'CallExpression' ||\n init.arguments[0]?.type !== 'ObjectExpression'\n ) {\n continue;\n }\n const { callee } = init;\n // Router context adds a call: createRootRouteWithContext<Ctx>()({...}).\n if (\n (callee.type === 'Identifier' && callee.name === 'createRootRoute') ||\n (callee.type === 'CallExpression' &&\n callee.arguments.length === 0 &&\n callee.callee.type === 'Identifier' &&\n callee.callee.name === 'createRootRouteWithContext')\n ) {\n return { routeName: id.name, options: init.arguments[0] };\n }\n }\n }\n return undefined;\n}\n\ntype LocalFunction = NonNullable<ReturnType<typeof findLocalFunction>>;\n\n/**\n * The local function that renders the document: the route component itself\n * when it renders `<html>`, or the one local component it returns with only\n * the route's slot as its child. A followed document must render nowhere\n * else: another render, such as an errorComponent, has no loader data.\n */\nfunction findDocument(\n statements: t.Statement[],\n component: LocalFunction,\n isShell: boolean\n): LocalFunction | undefined {\n if (rendersElement([component.body], 'html')) return component;\n const { body } = component;\n const returned =\n body.type !== 'BlockStatement'\n ? body\n : body.body.length === 1 && body.body[0].type === 'ReturnStatement'\n ? body.body[0].argument\n : undefined;\n if (\n returned?.type !== 'JSXElement' ||\n returned.openingElement.name.type !== 'JSXIdentifier'\n ) {\n return undefined;\n }\n const children = returned.children.filter(\n (child) => child.type !== 'JSXText' || child.value.trim() !== ''\n );\n if (\n children.length !== 1 ||\n !(isShell\n ? isChildrenSlot(children[0])\n : isJsxElementNamed(children[0], 'Outlet'))\n ) {\n return undefined;\n }\n const { name } = returned.openingElement.name;\n // Its declaration and the route component's element are the only uses.\n let uses = 0;\n for (const statement of statements) {\n t.traverseFast(statement, (node) => {\n if (isJsxElementNamed(node, name) || t.isIdentifier(node, { name })) {\n uses++;\n }\n });\n }\n if (uses !== 2) return undefined;\n const document = findLocalFunction(statements, name);\n return document && rendersElement([document.body], 'html')\n ? document\n : undefined;\n}\n\n/**\n * The root route, the local function its shellComponent or component names,\n * and the local function that renders its document.\n */\nexport function findRootComponent(statements: t.Statement[]) {\n const rootRoute = findRootRoute(statements);\n if (!rootRoute) return undefined;\n const { properties } = rootRoute.options;\n const componentProperty =\n properties.find((p) => getPropertyName(p) === 'shellComponent') ??\n properties.find((p) => getPropertyName(p) === 'component');\n const component =\n componentProperty?.type === 'ObjectProperty' &&\n componentProperty.value.type === 'Identifier'\n ? findLocalFunction(statements, componentProperty.value.name)\n : undefined;\n const isShell =\n componentProperty !== undefined &&\n getPropertyName(componentProperty) === 'shellComponent';\n const document = component && findDocument(statements, component, isShell);\n return { rootRoute, componentProperty, component, isShell, document };\n}\n\n/**\n * Configures the create-start root route: `createRootRoute({...})` (or its\n * router-context form) without a loader, whose shellComponent renders\n * `{children}` (or whose component renders `<Outlet />`) once in the `<body>`\n * of a local `<html>` document, either directly or through one local document\n * component that renders its `{children}` there. Returns undefined for any\n * other shape.\n */\nexport function configureRootRoute({\n content,\n statements,\n}: SourceFile): string | undefined {\n if (!statements) return undefined;\n // Generated bindings must not shadow or collide with the app's own.\n if (/\\b(?:getLocale|getTranslationsSnapshot)\\b/.test(content)) {\n return undefined;\n }\n const found = findRootComponent(statements);\n if (!found) return undefined;\n const { rootRoute, componentProperty, component, isShell, document } = found;\n const { properties } = rootRoute.options;\n if (\n properties.some((property) => {\n const name = getPropertyName(property);\n // A spread or computed key could be any of the options below.\n // A throwing beforeLoad or validateSearch skips the loader, so the\n // shell would render without the locale and translations it reads.\n return (\n name === undefined ||\n name === 'loader' ||\n name === 'beforeLoad' ||\n name === 'validateSearch'\n );\n })\n ) {\n return undefined;\n }\n if (\n componentProperty?.type !== 'ObjectProperty' ||\n !component ||\n document?.body.type !== 'BlockStatement' ||\n [component, document].some((fn) =>\n /\\b(?:locale|translations)\\b/.test(content.slice(fn.start!, fn.end!))\n )\n ) {\n return undefined;\n }\n // A followed document receives the route's slot as its children.\n const slotIsChildren = isShell || document !== component;\n const htmlElements: t.JSXElement[] = [];\n t.traverseFast(document.body, (node) => {\n if (isJsxElementNamed(node, 'html')) htmlElements.push(node);\n });\n if (htmlElements.length !== 1) return undefined;\n const [html] = htmlElements;\n const bodies = html.children.filter((child) =>\n isJsxElementNamed(child, 'body')\n );\n if (bodies.length !== 1) return undefined;\n // Headers, footers and app providers around the slot render GT too, so the\n // provider wraps everything the body renders before <Scripts />.\n const bodyContent = bodies[0].children.filter(\n (child) => child.type !== 'JSXText' || child.value.trim() !== ''\n );\n const scriptsIndex = bodyContent.findIndex((child) =>\n isJsxElementNamed(child, 'Scripts')\n );\n const wrapped =\n scriptsIndex === -1 ? bodyContent : bodyContent.slice(0, scriptsIndex);\n let slots = 0;\n let multilineLiteral = false;\n for (const child of wrapped) {\n t.traverseFast(child, (node) => {\n if (\n slotIsChildren\n ? isChildrenSlot(node)\n : isJsxElementNamed(node, 'Outlet')\n ) {\n slots++;\n }\n if (\n (node.type === 'TemplateLiteral' || node.type === 'StringLiteral') &&\n node.loc!.start.line !== node.loc!.end.line\n ) {\n multilineLiteral = true;\n }\n });\n }\n if (slots !== 1) return undefined;\n const { attributes } = html.openingElement;\n if (attributes.some((attribute) => attribute.type === 'JSXSpreadAttribute')) {\n return undefined;\n }\n const lang = attributes.find(\n (attribute): attribute is t.JSXAttribute =>\n attribute.type === 'JSXAttribute' &&\n t.isJSXIdentifier(attribute.name, { name: 'lang' })\n );\n // A computed lang is the app's own locale logic.\n if (lang && lang.value?.type !== 'StringLiteral') return undefined;\n const propertyIndent = getOwnLineIndent(content, componentProperty.start!);\n if (propertyIndent === undefined) return undefined;\n\n const { quote, semi, eol, indent } = getCodeStyle(content, statements);\n const first = wrapped[0];\n const last = wrapped.at(-1)!;\n const wrappedText = content.slice(first.start!, last.end!);\n const wrappedIndent = getOwnLineIndent(content, first.start!);\n // Reindenting would change the value of a literal that spans lines, such\n // as a template, a backslash-continued string or a JSX attribute string.\n const nestedText = multilineLiteral\n ? wrappedText\n : wrappedText.replace(/\\n(?=[ \\t]*\\S)/g, `\\n${indent}`);\n const provider = '<GTProvider locale={locale} translations={translations}>';\n const firstStatement = document.body.body[0];\n const statementIndent =\n (firstStatement && getOwnLineIndent(content, firstStatement.start!)) ??\n getLineIndent(content, document.start!) + indent;\n return applyEdits(content, [\n getImportEdit(\n statements,\n [\n `import { GTProvider, getLocale, getTranslationsSnapshot } from ${quote}${Libraries.GT_TANSTACK_START}${quote}${semi}`,\n ],\n eol\n ),\n {\n start: componentProperty.start!,\n text: [\n 'loader: async () => {',\n `${propertyIndent}${indent}const locale = getLocale()${semi}`,\n `${propertyIndent}${indent}return { locale, translations: await getTranslationsSnapshot(locale) }${semi}`,\n `${propertyIndent}},`,\n propertyIndent,\n ].join(eol),\n },\n {\n start: document.body.start! + 1,\n text: `${eol}${statementIndent}const { locale, translations } = ${rootRoute.routeName}.useLoaderData()${semi}`,\n },\n lang\n ? { start: lang.start!, end: lang.end!, text: 'lang={locale}' }\n : { start: html.openingElement.name.end!, text: ' lang={locale}' },\n {\n start: first.start!,\n end: last.end!,\n text:\n wrappedIndent === undefined\n ? `${provider}${wrappedText}</GTProvider>`\n : [\n provider,\n `${wrappedIndent}${indent}${nestedText}`,\n `${wrappedIndent}</GTProvider>`,\n ].join(eol),\n },\n ]);\n}\n\nexport function getRootFix(rootPath: string): string {\n return `In ${rootPath}, add loader: async () => { const locale = getLocale(); return { locale, translations: await getTranslationsSnapshot(locale) }; } to the root route options, read const { locale, translations } = Route.useLoaderData() in the document, set <html lang={locale}>, and wrap everything its <body> renders before <Scripts /> in <GTProvider locale={locale} translations={translations}>, importing GTProvider, getLocale and getTranslationsSnapshot from '${Libraries.GT_TANSTACK_START}' (see ${DOCS_URL})`;\n}\n"],"mappings":";;;;;AAYA,SAAS,kBAAkB,MAAc,MAAoC;AAC3E,QACE,KAAK,SAAS,gBACd,EAAE,gBAAgB,KAAK,eAAe,MAAM,EAAE,MAAM,CAAC;;AAIzD,SAAS,eAAe,MAAuB;AAC7C,QACE,KAAK,SAAS,4BACd,KAAK,WAAW,SAAS,gBACzB,KAAK,WAAW,SAAS;;AAI7B,SAAgB,eACd,OACA,MACS;CACT,IAAI,QAAQ;AACZ,MAAK,MAAM,QAAQ,MACjB,GAAE,aAAa,OAAO,UAAU;AAC9B,MAAI,kBAAkB,OAAO,KAAK,CAAE,SAAQ;GAC5C;AAEJ,QAAO;;AAGT,SAAS,kBAAkB,YAA2B,MAAc;AAClE,MAAK,MAAM,aAAa,YAAY;EAClC,MAAM,cACJ,UAAU,SAAS,2BACf,UAAU,cACV;AACN,MACE,aAAa,SAAS,yBACtB,YAAY,IAAI,SAAS,KAEzB,QAAO;AAET,MAAI,aAAa,SAAS,sBAAuB;AACjD,MAAI,YAAY,SAAS,QAAS;AAClC,OAAK,MAAM,cAAc,YAAY,aACnC,KACE,EAAE,aAAa,WAAW,IAAI,EAAE,MAAM,CAAC,KACtC,WAAW,MAAM,SAAS,6BACzB,WAAW,MAAM,SAAS,sBAE5B,QAAO,WAAW;;;AAO1B,SAAS,cAAc,YAA2B;AAChD,MAAK,MAAM,aAAa,YAAY;EAClC,MAAM,cACJ,UAAU,SAAS,2BACf,UAAU,cACV;AACN,MAAI,aAAa,SAAS,sBAAuB;AACjD,OAAK,MAAM,EAAE,IAAI,UAAU,YAAY,cAAc;AACnD,OACE,GA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7D,MAAM,aAAa,mBACf,cACA,YAAY,QAAQ,mBAAmB,KAAK,SAAS;CACzD,MAAM,WAAW;CACjB,MAAM,iBAAiB,SAAS,KAAK,KAAK;CAC1C,MAAM,mBACH,kBAAkB,iBAAiB,SAAS,eAAe,MAAO,KACnE,cAAc,SAAS,SAAS,MAAO,GAAG;AAC5C,QAAO,WAAW,SAAS;EACzB,cACE,YACA,CACE,kEAAkE,yBAAsC,QAAQ,OACjH,EACD,IACD;EACD;GACE,OAAO,kBAAkB;GACzB,MAAM;IACJ;IACA,GAAG,iBAAiB,OAAO,4BAA4B;IACvD,GAAG,iBAAiB,OAAO,wEAAwE;IACnG,GAAG,eAAe;IAClB;IACD,CAAC,KAAK,IAAI;GACZ;EACD;GACE,OAAO,SAAS,KAAK,QAAS;GAC9B,MAAM,GAAG,MAAM,gBAAgB,mCAAmC,UAAU,UAAU,kBAAkB;GACzG;EACD,OACI;GAAE,OAAO,KAAK;GAAQ,KAAK,KAAK;GAAM,MAAM;GAAiB,GAC7D;GAAE,OAAO,KAAK,eAAe,KAAK;GAAM,MAAM;GAAkB;EACpE;GACE,OAAO,MAAM;GACb,KAAK,KAAK;GACV,MACE,kBAAkB,KAAA,IACd,GAAG,WAAW,YAAY,iBAC1B;IACE;IACA,GAAG,gBAAgB,SAAS;IAC5B,GAAG,cAAc;IAClB,CAAC,KAAK,IAAI;GAClB;EACF,CAAC;;AAGJ,SAAgB,WAAW,UAA0B;AACnD,QAAO,MAAM,SAAS,udAAoe,SAAS"}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import * as t from '@babel/types';
|
|
2
|
+
import { type ViteLoaderExport } from '../../setupViteSPA.js';
|
|
3
|
+
import type { BuildToolContext, ManualAction } from '../index.js';
|
|
4
|
+
import type { CodeStyle } from './edits.js';
|
|
5
|
+
import { type SourceFile } from './source.js';
|
|
6
|
+
/** The module-scope `initializeGT(...)` call, which must run before requests. */
|
|
7
|
+
export declare function findInitializeCall(file: SourceFile): t.CallExpression | undefined;
|
|
8
|
+
/**
|
|
9
|
+
* Whether the initializeGT options pass a loader: false for the config alone,
|
|
10
|
+
* undefined when the options hide it (other spreads, variables, computed keys).
|
|
11
|
+
*/
|
|
12
|
+
export declare function passesLoader(router: SourceFile, options: t.Node | undefined, { appDirectory, configFilepath }: BuildToolContext): boolean | undefined;
|
|
13
|
+
export declare function getRouterLines(router: SourceFile, { appDirectory, configFilepath }: BuildToolContext, loaderExport: ViteLoaderExport, { quote, semi }: Pick<CodeStyle, 'quote' | 'semi'>): string[];
|
|
14
|
+
/** The initializeGT change for a router whose storage no longer matches. */
|
|
15
|
+
export declare function getStorageAction(router: SourceFile, ctx: BuildToolContext, loaderExport: ViteLoaderExport, loaderPassed: boolean): ManualAction;
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import "../../../types/libraries.js";
|
|
2
|
+
import { toRelativeImport } from "../../setupViteSPA.js";
|
|
3
|
+
import { DOCS_URL, getLocalImport, getPropertyName } from "./source.js";
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
import * as t from "@babel/types";
|
|
6
|
+
//#region src/setup/buildTools/tanstackStart/router.ts
|
|
7
|
+
/** The module-scope `initializeGT(...)` call, which must run before requests. */
|
|
8
|
+
function findInitializeCall(file) {
|
|
9
|
+
const local = getLocalImport(file, "initializeGT");
|
|
10
|
+
if (!local) return void 0;
|
|
11
|
+
for (const statement of file.statements ?? []) if (statement.type === "ExpressionStatement" && statement.expression.type === "CallExpression" && t.isIdentifier(statement.expression.callee, { name: local })) return statement.expression;
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* Whether the initializeGT options pass a loader: false for the config alone,
|
|
15
|
+
* undefined when the options hide it (other spreads, variables, computed keys).
|
|
16
|
+
*/
|
|
17
|
+
function passesLoader(router, options, { appDirectory, configFilepath }) {
|
|
18
|
+
const configPath = path.resolve(appDirectory, configFilepath);
|
|
19
|
+
const routerDirectory = path.dirname(path.join(appDirectory, router.path));
|
|
20
|
+
const configBinding = router.statements?.filter((statement) => statement.type === "ImportDeclaration").find((statement) => path.resolve(routerDirectory, statement.source.value) === configPath)?.specifiers.find((specifier) => specifier.type === "ImportDefaultSpecifier")?.local.name;
|
|
21
|
+
const isConfig = (node) => node.type === "Identifier" && node.name === configBinding;
|
|
22
|
+
if (!options) return void 0;
|
|
23
|
+
if (isConfig(options)) return false;
|
|
24
|
+
if (options.type !== "ObjectExpression") return void 0;
|
|
25
|
+
let loader = false;
|
|
26
|
+
for (const property of options.properties) {
|
|
27
|
+
if (property.type === "SpreadElement") {
|
|
28
|
+
if (!isConfig(property.argument)) return void 0;
|
|
29
|
+
continue;
|
|
30
|
+
}
|
|
31
|
+
const name = getPropertyName(property);
|
|
32
|
+
if (name === void 0) return void 0;
|
|
33
|
+
if (name === "loadTranslations") loader = true;
|
|
34
|
+
}
|
|
35
|
+
return loader;
|
|
36
|
+
}
|
|
37
|
+
function getRouterLines(router, { appDirectory, configFilepath }, loaderExport, { quote, semi }) {
|
|
38
|
+
const configImport = toRelativeImport(path.dirname(path.join(appDirectory, router.path)), path.resolve(appDirectory, configFilepath));
|
|
39
|
+
const importFrom = (bindings, source) => `import ${bindings} from ${quote}${source}${quote}${semi}`;
|
|
40
|
+
return [
|
|
41
|
+
importFrom("{ initializeGT }", "gt-tanstack-start"),
|
|
42
|
+
importFrom("gtConfig", configImport),
|
|
43
|
+
...loaderExport ? [importFrom(loaderExport === "default" ? "loadTranslations" : "{ loadTranslations }", "./loadTranslations")] : [],
|
|
44
|
+
"",
|
|
45
|
+
`initializeGT(${loaderExport ? "{ ...gtConfig, loadTranslations }" : "gtConfig"})${semi}`
|
|
46
|
+
];
|
|
47
|
+
}
|
|
48
|
+
/** The initializeGT change for a router whose storage no longer matches. */
|
|
49
|
+
function getStorageAction(router, ctx, loaderExport, loaderPassed) {
|
|
50
|
+
const lines = getRouterLines(router, ctx, loaderExport, {
|
|
51
|
+
quote: "'",
|
|
52
|
+
semi: ""
|
|
53
|
+
});
|
|
54
|
+
const call = lines.at(-1);
|
|
55
|
+
const loaderImport = loaderExport ? lines.find((line) => line.endsWith("'./loadTranslations'")) : void 0;
|
|
56
|
+
return {
|
|
57
|
+
whatHappened: `${router.path} initializes GT for ${loaderPassed ? "local translation files" : "CDN translations"}, but translations are now ${ctx.translationsDir ? `stored in ${ctx.translationsDir}` : "loaded from the CDN"}`,
|
|
58
|
+
fix: `Change the initializeGT call in ${router.path} to ${call}${loaderImport ? ` and add ${loaderImport}` : " and remove the loadTranslations import"} (see ${DOCS_URL})`
|
|
59
|
+
};
|
|
60
|
+
}
|
|
61
|
+
//#endregion
|
|
62
|
+
export { findInitializeCall, getRouterLines, getStorageAction, passesLoader };
|
|
63
|
+
|
|
64
|
+
//# sourceMappingURL=router.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"router.js","names":[],"sources":["../../../../src/setup/buildTools/tanstackStart/router.ts"],"sourcesContent":["// src/router.tsx: the initializeGT call and its translation loader.\nimport * as t from '@babel/types';\nimport path from 'node:path';\nimport { Libraries } from '../../../types/libraries.js';\nimport { toRelativeImport, type ViteLoaderExport } from '../../setupViteSPA.js';\nimport type { BuildToolContext, ManualAction } from '../index.js';\nimport type { CodeStyle } from './edits.js';\nimport {\n DOCS_URL,\n getLocalImport,\n getPropertyName,\n type SourceFile,\n} from './source.js';\n\n/** The module-scope `initializeGT(...)` call, which must run before requests. */\nexport function findInitializeCall(\n file: SourceFile\n): t.CallExpression | undefined {\n const local = getLocalImport(file, 'initializeGT');\n if (!local) return undefined;\n for (const statement of file.statements ?? []) {\n if (\n statement.type === 'ExpressionStatement' &&\n statement.expression.type === 'CallExpression' &&\n t.isIdentifier(statement.expression.callee, { name: local })\n ) {\n return statement.expression;\n }\n }\n return undefined;\n}\n\n/**\n * Whether the initializeGT options pass a loader: false for the config alone,\n * undefined when the options hide it (other spreads, variables, computed keys).\n */\nexport function passesLoader(\n router: SourceFile,\n options: t.Node | undefined,\n { appDirectory, configFilepath }: BuildToolContext\n): boolean | undefined {\n const configPath = path.resolve(appDirectory, configFilepath);\n const routerDirectory = path.dirname(path.join(appDirectory, router.path));\n const configBinding = router.statements\n ?.filter((statement) => statement.type === 'ImportDeclaration')\n .find(\n (statement) =>\n path.resolve(routerDirectory, statement.source.value) === configPath\n )\n ?.specifiers.find(\n (specifier) => specifier.type === 'ImportDefaultSpecifier'\n )?.local.name;\n const isConfig = (node: t.Node) =>\n node.type === 'Identifier' && node.name === configBinding;\n if (!options) return undefined;\n if (isConfig(options)) return false;\n if (options.type !== 'ObjectExpression') return undefined;\n let loader = false;\n for (const property of options.properties) {\n if (property.type === 'SpreadElement') {\n if (!isConfig(property.argument)) return undefined;\n continue;\n }\n const name = getPropertyName(property);\n if (name === undefined) return undefined;\n if (name === 'loadTranslations') loader = true;\n }\n return loader;\n}\n\nexport function getRouterLines(\n router: SourceFile,\n { appDirectory, configFilepath }: BuildToolContext,\n loaderExport: ViteLoaderExport,\n { quote, semi }: Pick<CodeStyle, 'quote' | 'semi'>\n): string[] {\n const configImport = toRelativeImport(\n path.dirname(path.join(appDirectory, router.path)),\n path.resolve(appDirectory, configFilepath)\n );\n const importFrom = (bindings: string, source: string) =>\n `import ${bindings} from ${quote}${source}${quote}${semi}`;\n return [\n importFrom('{ initializeGT }', Libraries.GT_TANSTACK_START),\n importFrom('gtConfig', configImport),\n ...(loaderExport\n ? [\n importFrom(\n loaderExport === 'default'\n ? 'loadTranslations'\n : '{ loadTranslations }',\n './loadTranslations'\n ),\n ]\n : []),\n '',\n `initializeGT(${loaderExport ? '{ ...gtConfig, loadTranslations }' : 'gtConfig'})${semi}`,\n ];\n}\n\n/** The initializeGT change for a router whose storage no longer matches. */\nexport function getStorageAction(\n router: SourceFile,\n ctx: BuildToolContext,\n loaderExport: ViteLoaderExport,\n loaderPassed: boolean\n): ManualAction {\n const lines = getRouterLines(router, ctx, loaderExport, {\n quote: \"'\",\n semi: '',\n });\n const call = lines.at(-1)!;\n const loaderImport = loaderExport\n ? lines.find((line) => line.endsWith(\"'./loadTranslations'\"))\n : undefined;\n return {\n whatHappened: `${router.path} initializes GT for ${loaderPassed ? 'local translation files' : 'CDN translations'}, but translations are now ${ctx.translationsDir ? `stored in ${ctx.translationsDir}` : 'loaded from the CDN'}`,\n fix: `Change the initializeGT call in ${router.path} to ${call}${loaderImport ? ` and add ${loaderImport}` : ' and remove the loadTranslations import'} (see ${DOCS_URL})`,\n };\n}\n"],"mappings":";;;;;;;AAeA,SAAgB,mBACd,MAC8B;CAC9B,MAAM,QAAQ,eAAe,MAAM,eAAe;AAClD,KAAI,CAAC,MAAO,QAAO,KAAA;AACnB,MAAK,MAAM,aAAa,KAAK,cAAc,EAAE,CAC3C,KACE,UAAU,SAAS,yBACnB,UAAU,WAAW,SAAS,oBAC9B,EAAE,aAAa,UAAU,WAAW,QAAQ,EAAE,MAAM,OAAO,CAAC,CAE5D,QAAO,UAAU;;;;;;AAUvB,SAAgB,aACd,QACA,SACA,EAAE,cAAc,kBACK;CACrB,MAAM,aAAa,KAAK,QAAQ,cAAc,eAAe;CAC7D,MAAM,kBAAkB,KAAK,QAAQ,KAAK,KAAK,cAAc,OAAO,KAAK,CAAC;CAC1E,MAAM,gBAAgB,OAAO,YACzB,QAAQ,cAAc,UAAU,SAAS,oBAAoB,CAC9D,MACE,cACC,KAAK,QAAQ,iBAAiB,UAAU,OAAO,MAAM,KAAK,WAC7D,EACC,WAAW,MACV,cAAc,UAAU,SAAS,yBACnC,EAAE,MAAM;CACX,MAAM,YAAY,SAChB,KAAK,SAAS,gBAAgB,KAAK,SAAS;AAC9C,KAAI,CAAC,QAAS,QAAO,KAAA;AACrB,KAAI,SAAS,QAAQ,CAAE,QAAO;AAC9B,KAAI,QAAQ,SAAS,mBAAoB,QAAO,KAAA;CAChD,IAAI,SAAS;AACb,MAAK,MAAM,YAAY,QAAQ,YAAY;AACzC,MAAI,SAAS,SAAS,iBAAiB;AACrC,OAAI,CAAC,SAAS,SAAS,SAAS,CAAE,QAAO,KAAA;AACzC;;EAEF,MAAM,OAAO,gBAAgB,SAAS;AACtC,MAAI,SAAS,KAAA,EAAW,QAAO,KAAA;AAC/B,MAAI,SAAS,mBAAoB,UAAS;;AAE5C,QAAO;;AAGT,SAAgB,eACd,QACA,EAAE,cAAc,kBAChB,cACA,EAAE,OAAO,QACC;CACV,MAAM,eAAe,iBACnB,KAAK,QAAQ,KAAK,KAAK,cAAc,OAAO,KAAK,CAAC,EAClD,KAAK,QAAQ,cAAc,eAAe,CAC3C;CACD,MAAM,cAAc,UAAkB,WACpC,UAAU,SAAS,QAAQ,QAAQ,SAAS,QAAQ;AACtD,QAAO;EACL,WAAW,oBAAA,oBAAgD;EAC3D,WAAW,YAAY,aAAa;EACpC,GAAI,eACA,CACE,WACE,iBAAiB,YACb,qBACA,wBACJ,qBACD,CACF,GACD,EAAE;EACN;EACA,gBAAgB,eAAe,sCAAsC,WAAW,GAAG;EACpF;;;AAIH,SAAgB,iBACd,QACA,KACA,cACA,cACc;CACd,MAAM,QAAQ,eAAe,QAAQ,KAAK,cAAc;EACtD,OAAO;EACP,MAAM;EACP,CAAC;CACF,MAAM,OAAO,MAAM,GAAG,GAAG;CACzB,MAAM,eAAe,eACjB,MAAM,MAAM,SAAS,KAAK,SAAS,uBAAuB,CAAC,GAC3D,KAAA;AACJ,QAAO;EACL,cAAc,GAAG,OAAO,KAAK,sBAAsB,eAAe,4BAA4B,mBAAmB,6BAA6B,IAAI,kBAAkB,aAAa,IAAI,oBAAoB;EACzM,KAAK,mCAAmC,OAAO,KAAK,MAAM,OAAO,eAAe,YAAY,iBAAiB,0CAA0C,QAAQ,SAAS;EACzK"}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import * as t from '@babel/types';
|
|
2
|
+
export declare const DOCS_URL = "https://generaltranslation.com/docs/react/tanstack-start/setup";
|
|
3
|
+
export type SourceFile = {
|
|
4
|
+
/** Relative to the app, with forward slashes. */
|
|
5
|
+
path: string;
|
|
6
|
+
content: string;
|
|
7
|
+
/** Undefined when the file cannot be parsed. */
|
|
8
|
+
statements?: t.Statement[];
|
|
9
|
+
};
|
|
10
|
+
export declare function readSourceFile(appDirectory: string, basename: string): Promise<SourceFile | undefined>;
|
|
11
|
+
/** Reads the Start entries without writing, so a missing one stops setup. */
|
|
12
|
+
export declare function inspectTanStackStart(appDirectory: string): Promise<{
|
|
13
|
+
router: SourceFile;
|
|
14
|
+
root: SourceFile;
|
|
15
|
+
start: SourceFile | undefined;
|
|
16
|
+
}>;
|
|
17
|
+
/** The local name `name` is imported as from `source` (gt-tanstack-start). */
|
|
18
|
+
export declare function getLocalImport(file: SourceFile, name: string, source?: string): string | undefined;
|
|
19
|
+
export declare function getPropertyName(property: t.ObjectExpression['properties'][number]): string | undefined;
|