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,66 @@
|
|
|
1
|
+
import "../../../types/libraries.js";
|
|
2
|
+
import { parseModule } from "../../setupViteSPA.js";
|
|
3
|
+
import { createDiagnosticMessage } from "generaltranslation/internal";
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
import fs from "node:fs";
|
|
6
|
+
import * as t from "@babel/types";
|
|
7
|
+
//#region src/setup/buildTools/tanstackStart/source.ts
|
|
8
|
+
const DOCS_URL = "https://generaltranslation.com/docs/react/tanstack-start/setup";
|
|
9
|
+
const SOURCE_EXTENSIONS = [
|
|
10
|
+
".tsx",
|
|
11
|
+
".ts",
|
|
12
|
+
".jsx",
|
|
13
|
+
".js"
|
|
14
|
+
];
|
|
15
|
+
async function readSourceFile(appDirectory, basename) {
|
|
16
|
+
for (const extension of SOURCE_EXTENSIONS) {
|
|
17
|
+
const relativePath = `${basename}${extension}`;
|
|
18
|
+
const absolutePath = path.join(appDirectory, relativePath);
|
|
19
|
+
if (!fs.existsSync(absolutePath)) continue;
|
|
20
|
+
const content = await fs.promises.readFile(absolutePath, "utf8");
|
|
21
|
+
return {
|
|
22
|
+
path: relativePath,
|
|
23
|
+
content,
|
|
24
|
+
statements: parseModule(content, relativePath)
|
|
25
|
+
};
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
function getMissingFileError(file) {
|
|
29
|
+
return new Error(createDiagnosticMessage({
|
|
30
|
+
source: "gt",
|
|
31
|
+
severity: "Error",
|
|
32
|
+
whatHappened: "GT cannot configure this TanStack Start app",
|
|
33
|
+
why: `${file} was not found`,
|
|
34
|
+
reassurance: "Nothing was changed",
|
|
35
|
+
fix: "Run `npx gt@latest init` from the app root, or set up GT manually",
|
|
36
|
+
docsUrl: DOCS_URL
|
|
37
|
+
}));
|
|
38
|
+
}
|
|
39
|
+
/** Reads the Start entries without writing, so a missing one stops setup. */
|
|
40
|
+
async function inspectTanStackStart(appDirectory) {
|
|
41
|
+
const router = await readSourceFile(appDirectory, "src/router");
|
|
42
|
+
if (!router) throw getMissingFileError("src/router.tsx");
|
|
43
|
+
const root = await readSourceFile(appDirectory, "src/routes/__root");
|
|
44
|
+
if (!root) throw getMissingFileError("src/routes/__root.tsx");
|
|
45
|
+
return {
|
|
46
|
+
router,
|
|
47
|
+
root,
|
|
48
|
+
start: await readSourceFile(appDirectory, "src/start")
|
|
49
|
+
};
|
|
50
|
+
}
|
|
51
|
+
/** The local name `name` is imported as from `source` (gt-tanstack-start). */
|
|
52
|
+
function getLocalImport(file, name, source = "gt-tanstack-start") {
|
|
53
|
+
for (const statement of file.statements ?? []) {
|
|
54
|
+
if (statement.type !== "ImportDeclaration" || statement.source.value !== source || statement.importKind === "type") continue;
|
|
55
|
+
for (const specifier of statement.specifiers) if (specifier.type === "ImportSpecifier" && specifier.importKind !== "type" && t.isIdentifier(specifier.imported, { name })) return specifier.local.name;
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
function getPropertyName(property) {
|
|
59
|
+
if (property.type === "SpreadElement" || property.computed) return void 0;
|
|
60
|
+
if (property.key.type === "Identifier") return property.key.name;
|
|
61
|
+
if (property.key.type === "StringLiteral") return property.key.value;
|
|
62
|
+
}
|
|
63
|
+
//#endregion
|
|
64
|
+
export { DOCS_URL, getLocalImport, getPropertyName, inspectTanStackStart, readSourceFile };
|
|
65
|
+
|
|
66
|
+
//# sourceMappingURL=source.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"source.js","names":[],"sources":["../../../../src/setup/buildTools/tanstackStart/source.ts"],"sourcesContent":["// Reads the Start entries and the AST lookups shared by every entry.\nimport * as t from '@babel/types';\nimport { createDiagnosticMessage } from 'generaltranslation/internal';\nimport fs from 'node:fs';\nimport path from 'node:path';\nimport { Libraries } from '../../../types/libraries.js';\nimport { parseModule } from '../../setupViteSPA.js';\n\nexport const DOCS_URL =\n 'https://generaltranslation.com/docs/react/tanstack-start/setup';\n\n// Start resolves its entries by basename, so any of these may be the entry.\nconst SOURCE_EXTENSIONS = ['.tsx', '.ts', '.jsx', '.js'];\n\nexport type SourceFile = {\n /** Relative to the app, with forward slashes. */\n path: string;\n content: string;\n /** Undefined when the file cannot be parsed. */\n statements?: t.Statement[];\n};\n\nexport async function readSourceFile(\n appDirectory: string,\n basename: string\n): Promise<SourceFile | undefined> {\n for (const extension of SOURCE_EXTENSIONS) {\n const relativePath = `${basename}${extension}`;\n const absolutePath = path.join(appDirectory, relativePath);\n if (!fs.existsSync(absolutePath)) continue;\n const content = await fs.promises.readFile(absolutePath, 'utf8');\n return {\n path: relativePath,\n content,\n statements: parseModule(content, relativePath),\n };\n }\n return undefined;\n}\n\nfunction getMissingFileError(file: string): Error {\n return new Error(\n createDiagnosticMessage({\n source: 'gt',\n severity: 'Error',\n whatHappened: 'GT cannot configure this TanStack Start app',\n why: `${file} was not found`,\n reassurance: 'Nothing was changed',\n fix: 'Run `npx gt@latest init` from the app root, or set up GT manually',\n docsUrl: DOCS_URL,\n })\n );\n}\n\n/** Reads the Start entries without writing, so a missing one stops setup. */\nexport async function inspectTanStackStart(appDirectory: string) {\n const router = await readSourceFile(appDirectory, 'src/router');\n if (!router) throw getMissingFileError('src/router.tsx');\n const root = await readSourceFile(appDirectory, 'src/routes/__root');\n if (!root) throw getMissingFileError('src/routes/__root.tsx');\n return {\n router,\n root,\n start: await readSourceFile(appDirectory, 'src/start'),\n };\n}\n\n/** The local name `name` is imported as from `source` (gt-tanstack-start). */\nexport function getLocalImport(\n file: SourceFile,\n name: string,\n source: string = Libraries.GT_TANSTACK_START\n): string | undefined {\n for (const statement of file.statements ?? []) {\n if (\n statement.type !== 'ImportDeclaration' ||\n statement.source.value !== source ||\n statement.importKind === 'type'\n ) {\n continue;\n }\n for (const specifier of statement.specifiers) {\n if (\n specifier.type === 'ImportSpecifier' &&\n specifier.importKind !== 'type' &&\n t.isIdentifier(specifier.imported, { name })\n ) {\n return specifier.local.name;\n }\n }\n }\n return undefined;\n}\n\nexport function getPropertyName(\n property: t.ObjectExpression['properties'][number]\n): string | undefined {\n if (property.type === 'SpreadElement' || property.computed) return undefined;\n if (property.key.type === 'Identifier') return property.key.name;\n if (property.key.type === 'StringLiteral') return property.key.value;\n return undefined;\n}\n"],"mappings":";;;;;;;AAQA,MAAa,WACX;AAGF,MAAM,oBAAoB;CAAC;CAAQ;CAAO;CAAQ;CAAM;AAUxD,eAAsB,eACpB,cACA,UACiC;AACjC,MAAK,MAAM,aAAa,mBAAmB;EACzC,MAAM,eAAe,GAAG,WAAW;EACnC,MAAM,eAAe,KAAK,KAAK,cAAc,aAAa;AAC1D,MAAI,CAAC,GAAG,WAAW,aAAa,CAAE;EAClC,MAAM,UAAU,MAAM,GAAG,SAAS,SAAS,cAAc,OAAO;AAChE,SAAO;GACL,MAAM;GACN;GACA,YAAY,YAAY,SAAS,aAAa;GAC/C;;;AAKL,SAAS,oBAAoB,MAAqB;AAChD,QAAO,IAAI,MACT,wBAAwB;EACtB,QAAQ;EACR,UAAU;EACV,cAAc;EACd,KAAK,GAAG,KAAK;EACb,aAAa;EACb,KAAK;EACL,SAAS;EACV,CAAC,CACH;;;AAIH,eAAsB,qBAAqB,cAAsB;CAC/D,MAAM,SAAS,MAAM,eAAe,cAAc,aAAa;AAC/D,KAAI,CAAC,OAAQ,OAAM,oBAAoB,iBAAiB;CACxD,MAAM,OAAO,MAAM,eAAe,cAAc,oBAAoB;AACpE,KAAI,CAAC,KAAM,OAAM,oBAAoB,wBAAwB;AAC7D,QAAO;EACL;EACA;EACA,OAAO,MAAM,eAAe,cAAc,YAAY;EACvD;;;AAIH,SAAgB,eACd,MACA,MACA,SAAA,qBACoB;AACpB,MAAK,MAAM,aAAa,KAAK,cAAc,EAAE,EAAE;AAC7C,MACE,UAAU,SAAS,uBACnB,UAAU,OAAO,UAAU,UAC3B,UAAU,eAAe,OAEzB;AAEF,OAAK,MAAM,aAAa,UAAU,WAChC,KACE,UAAU,SAAS,qBACnB,UAAU,eAAe,UACzB,EAAE,aAAa,UAAU,UAAU,EAAE,MAAM,CAAC,CAE5C,QAAO,UAAU,MAAM;;;AAO/B,SAAgB,gBACd,UACoB;AACpB,KAAI,SAAS,SAAS,mBAAmB,SAAS,SAAU,QAAO,KAAA;AACnE,KAAI,SAAS,IAAI,SAAS,aAAc,QAAO,SAAS,IAAI;AAC5D,KAAI,SAAS,IAAI,SAAS,gBAAiB,QAAO,SAAS,IAAI"}
|
|
@@ -26,7 +26,7 @@ const viteSetup = {
|
|
|
26
26
|
async syncLoader({ appDirectory, defaultLocale, locales, translationsDir, previousTranslationsDir, keepAppSource }) {
|
|
27
27
|
if (keepAppSource) return {
|
|
28
28
|
steps: [],
|
|
29
|
-
manualActions: fs.existsSync(path.join(appDirectory,
|
|
29
|
+
manualActions: fs.existsSync(path.join(appDirectory, "src/loadTranslations.ts")) ? loaderUpdateActions(translationsDir, previousTranslationsDir, false) : []
|
|
30
30
|
};
|
|
31
31
|
const loader = await writeViteLoader({
|
|
32
32
|
appDirectory,
|
|
@@ -37,7 +37,7 @@ const viteSetup = {
|
|
|
37
37
|
create: false
|
|
38
38
|
});
|
|
39
39
|
return {
|
|
40
|
-
steps: loader === "
|
|
40
|
+
steps: loader === "updated" ? [`updated ${VITE_LOADER_FILE}`] : [],
|
|
41
41
|
manualActions: loader === "custom" ? loaderUpdateActions(translationsDir, previousTranslationsDir, true) : []
|
|
42
42
|
};
|
|
43
43
|
},
|
|
@@ -56,6 +56,6 @@ const viteSetup = {
|
|
|
56
56
|
}
|
|
57
57
|
};
|
|
58
58
|
//#endregion
|
|
59
|
-
export { viteSetup };
|
|
59
|
+
export { VITE_LOADER_FILE, viteSetup };
|
|
60
60
|
|
|
61
61
|
//# sourceMappingURL=vite.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"vite.js","names":[],"sources":["../../../src/setup/buildTools/vite.ts"],"sourcesContent":["import fs from 'node:fs';\nimport path from 'node:path';\nimport { DEFAULT_VITE_TRANSLATIONS_DIR } from '../../utils/constants.js';\nimport {\n inspectViteSPA,\n setupViteSPA,\n writeViteLoader,\n} from '../setupViteSPA.js';\nimport type { BuildToolSetup, ManualAction } from './index.js';\n\
|
|
1
|
+
{"version":3,"file":"vite.js","names":[],"sources":["../../../src/setup/buildTools/vite.ts"],"sourcesContent":["import fs from 'node:fs';\nimport path from 'node:path';\nimport { DEFAULT_VITE_TRANSLATIONS_DIR } from '../../utils/constants.js';\nimport {\n inspectViteSPA,\n setupViteSPA,\n writeViteLoader,\n} from '../setupViteSPA.js';\nimport type { BuildToolSetup, ManualAction } from './index.js';\n\nexport const VITE_LOADER_FILE = 'src/loadTranslations.ts';\n\n/** A loader left unchanged may not read the newly chosen directory. */\nfunction loaderUpdateActions(\n translationsDir: string,\n previousTranslationsDir: string | undefined,\n custom: boolean\n): ManualAction[] {\n if (translationsDir === previousTranslationsDir) return [];\n const fix = `Update ${custom ? 'your custom ' : ''}${VITE_LOADER_FILE} to load translations from ${translationsDir}`;\n return [\n {\n whatHappened: custom\n ? `Your custom ${VITE_LOADER_FILE} was left unchanged, but translations now go to ${translationsDir}`\n : `${VITE_LOADER_FILE} was left unchanged because the React setup was skipped, but translations now go to ${translationsDir}`,\n fix,\n },\n ];\n}\n\nexport const viteSetup: BuildToolSetup = {\n framework: 'vite',\n defaultTranslationsDir: DEFAULT_VITE_TRANSLATIONS_DIR,\n initializer: 'initializeGTSPA',\n ownsLoader: true,\n skipsGTInstall: (isUsingGT) => isUsingGT,\n devCredentialsOption: '--live-translations',\n async preflight(appDirectory) {\n await inspectViteSPA(appDirectory);\n },\n // Configure keeps an existing loader in sync; init leaves application\n // source to the person.\n async syncLoader({\n appDirectory,\n defaultLocale,\n locales,\n translationsDir,\n previousTranslationsDir,\n keepAppSource,\n }) {\n if (keepAppSource) {\n return {\n steps: [],\n manualActions: fs.existsSync(path.join(appDirectory, VITE_LOADER_FILE))\n ? loaderUpdateActions(translationsDir, previousTranslationsDir, false)\n : [],\n };\n }\n const loader = await writeViteLoader({\n appDirectory,\n defaultLocale,\n locales,\n translationsDir,\n previousTranslationsDir,\n create: false,\n });\n return {\n steps: loader === 'updated' ? [`updated ${VITE_LOADER_FILE}`] : [],\n manualActions:\n loader === 'custom'\n ? loaderUpdateActions(translationsDir, previousTranslationsDir, true)\n : [],\n };\n },\n async apply(ctx) {\n const { manualAction } = await setupViteSPA(ctx);\n return manualAction\n ? {\n steps: [],\n manualActions: [\n {\n whatHappened: 'The existing Vite setup needs a manual review',\n fix: manualAction,\n },\n ],\n }\n : { steps: ['configured initializeGTSPA'], manualActions: [] };\n },\n};\n"],"mappings":";;;;;AAUA,MAAa,mBAAmB;;AAGhC,SAAS,oBACP,iBACA,yBACA,QACgB;AAChB,KAAI,oBAAoB,wBAAyB,QAAO,EAAE;CAC1D,MAAM,MAAM,UAAU,SAAS,iBAAiB,KAAK,iBAAiB,6BAA6B;AACnG,QAAO,CACL;EACE,cAAc,SACV,eAAe,iBAAiB,kDAAkD,oBAClF,GAAG,iBAAiB,sFAAsF;EAC9G;EACD,CACF;;AAGH,MAAa,YAA4B;CACvC,WAAW;CACX,wBAAwB;CACxB,aAAa;CACb,YAAY;CACZ,iBAAiB,cAAc;CAC/B,sBAAsB;CACtB,MAAM,UAAU,cAAc;AAC5B,QAAM,eAAe,aAAa;;CAIpC,MAAM,WAAW,EACf,cACA,eACA,SACA,iBACA,yBACA,iBACC;AACD,MAAI,cACF,QAAO;GACL,OAAO,EAAE;GACT,eAAe,GAAG,WAAW,KAAK,KAAK,cAAA,0BAA+B,CAAC,GACnE,oBAAoB,iBAAiB,yBAAyB,MAAM,GACpE,EAAE;GACP;EAEH,MAAM,SAAS,MAAM,gBAAgB;GACnC;GACA;GACA;GACA;GACA;GACA,QAAQ;GACT,CAAC;AACF,SAAO;GACL,OAAO,WAAW,YAAY,CAAC,WAAW,mBAAmB,GAAG,EAAE;GAClE,eACE,WAAW,WACP,oBAAoB,iBAAiB,yBAAyB,KAAK,GACnE,EAAE;GACT;;CAEH,MAAM,MAAM,KAAK;EACf,MAAM,EAAE,iBAAiB,MAAM,aAAa,IAAI;AAChD,SAAO,eACH;GACE,OAAO,EAAE;GACT,eAAe,CACb;IACE,cAAc;IACd,KAAK;IACN,CACF;GACF,GACD;GAAE,OAAO,CAAC,6BAA6B;GAAE,eAAe,EAAE;GAAE;;CAEnE"}
|
|
@@ -3,7 +3,7 @@ import { FrameworkObject } from '../types/index.js';
|
|
|
3
3
|
* Detects the frontend framework used in the current project.
|
|
4
4
|
*
|
|
5
5
|
* Analyzes the project structure and dependencies to identify the framework.
|
|
6
|
-
* Detection order: Mintlify → Next.js (App/Pages Router) → Gatsby → RedwoodJS → Vite → React.
|
|
6
|
+
* Detection order: Mintlify → Next.js (App/Pages Router) → Gatsby → RedwoodJS → TanStack Start → Vite → React.
|
|
7
7
|
*
|
|
8
8
|
* For Next.js projects, further determines whether it uses App Router or Pages Router
|
|
9
9
|
* by checking for the presence of `app/` or `pages/` directories.
|
|
@@ -6,7 +6,7 @@ import fs from "node:fs";
|
|
|
6
6
|
* Detects the frontend framework used in the current project.
|
|
7
7
|
*
|
|
8
8
|
* Analyzes the project structure and dependencies to identify the framework.
|
|
9
|
-
* Detection order: Mintlify → Next.js (App/Pages Router) → Gatsby → RedwoodJS → Vite → React.
|
|
9
|
+
* Detection order: Mintlify → Next.js (App/Pages Router) → Gatsby → RedwoodJS → TanStack Start → Vite → React.
|
|
10
10
|
*
|
|
11
11
|
* For Next.js projects, further determines whether it uses App Router or Pages Router
|
|
12
12
|
* by checking for the presence of `app/` or `pages/` directories.
|
|
@@ -45,6 +45,10 @@ async function detectFramework() {
|
|
|
45
45
|
name: "redwood",
|
|
46
46
|
type: "react"
|
|
47
47
|
};
|
|
48
|
+
if (isPackageInstalled("@tanstack/react-start", packageJson, false, true)) return {
|
|
49
|
+
name: "tanstack-start",
|
|
50
|
+
type: "react"
|
|
51
|
+
};
|
|
48
52
|
if (isPackageInstalled("vite", packageJson, false, true)) return {
|
|
49
53
|
name: "vite",
|
|
50
54
|
type: "react"
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"detectFramework.js","names":[],"sources":["../../src/setup/detectFramework.ts"],"sourcesContent":["import { FrameworkObject } from '../types/index.js';\nimport { isPackageInstalled } from '../utils/packageJson.js';\nimport { searchForPackageJson } from '../utils/packageJson.js';\nimport fs from 'node:fs';\nimport path from 'node:path';\n\n/* ----- MAIN ----- */\n\n/**\n * Detects the frontend framework used in the current project.\n *\n * Analyzes the project structure and dependencies to identify the framework.\n * Detection order: Mintlify → Next.js (App/Pages Router) → Gatsby → RedwoodJS → Vite → React.\n *\n * For Next.js projects, further determines whether it uses App Router or Pages Router\n * by checking for the presence of `app/` or `pages/` directories.\n *\n * @returns A promise resolving to a FrameworkObject containing:\n * - `name`: The detected framework identifier (e.g., 'next-app', 'gatsby', 'react')\n * or undefined if no framework is detected\n * - `type`: The framework category (currently only 'react' for React-based frameworks)\n */\nexport async function detectFramework(): Promise<\n FrameworkObject | { name: undefined; type?: undefined }\n> {\n const packageJson = await searchForPackageJson();\n\n if (isMintlifyProject(packageJson)) {\n return { name: 'mintlify' };\n }\n\n if (!packageJson) {\n return { name: undefined };\n }\n\n // Check for Next.js first\n if (isPackageInstalled('next', packageJson, false, true)) {\n // Determine if it's App Router or Pages Router\n const cwd = process.cwd();\n const hasAppDir =\n fs.existsSync(path.join(cwd, 'app')) ||\n fs.existsSync(path.join(cwd, 'src', 'app'));\n const hasPagesDir =\n fs.existsSync(path.join(cwd, 'pages')) ||\n fs.existsSync(path.join(cwd, 'src', 'pages'));\n\n // App Router takes precedence if both exist\n if (hasAppDir) {\n return { name: 'next-app', type: 'react' };\n }\n if (hasPagesDir) {\n return { name: 'next-pages', type: 'react' };\n }\n // Default to app router for new Next.js projects\n return { name: 'next-app', type: 'react' };\n }\n\n // Check for Gatsby\n if (isPackageInstalled('gatsby', packageJson, false, true)) {\n return { name: 'gatsby', type: 'react' };\n }\n\n // Check for RedwoodJS\n if (isPackageInstalled('@redwoodjs/core', packageJson, false, true)) {\n return { name: 'redwood', type: 'react' };\n }\n\n // Check for Vite\n if (isPackageInstalled('vite', packageJson, false, true)) {\n return { name: 'vite', type: 'react' };\n }\n\n // Check for React (generic)\n if (isPackageInstalled('react', packageJson, false, true)) {\n return { name: 'react', type: 'react' };\n }\n\n return { name: undefined };\n}\n\n// ----- HELPER FUNCTIONS ----- //\n\n/**\n * Detects if the current project is a Mintlify documentation project.\n *\n * Checks for the presence of docs.json (preferred) or mint.json (legacy) files.\n * For docs.json, validates that the $schema field contains \"mintlify.com/docs.json\".\n * Rejects projects with Next.js config files to avoid misclassification.\n *\n * @param _packageJson - The parsed package.json object (not used for Mintlify detection,\n * but kept for API consistency with other detection functions)\n * @returns True if the project is identified as a Mintlify project, false otherwise\n */\nexport function isMintlifyProject(\n _packageJson: Record<string, unknown> | null\n): boolean {\n const cwd = process.cwd();\n\n // Check for Next.js config files - if present, this is not a Mintlify project\n const nextConfigFiles = [\n 'next.config.js',\n 'next.config.ts',\n 'next.config.mjs',\n 'next.config.cjs',\n ];\n\n for (const configFile of nextConfigFiles) {\n if (fs.existsSync(path.join(cwd, configFile))) {\n return false;\n }\n }\n\n // Check for docs.json (preferred format)\n const docsJsonPath = path.join(cwd, 'docs.json');\n if (fs.existsSync(docsJsonPath)) {\n try {\n const docsJson = JSON.parse(fs.readFileSync(docsJsonPath, 'utf-8'));\n // Validate the $schema field contains mintlify.com/docs.json\n if (\n docsJson.$schema &&\n docsJson.$schema.includes('mintlify.com/docs.json')\n ) {\n return true;\n }\n } catch {\n return false;\n }\n }\n\n return false;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAsBA,eAAsB,kBAEpB;CACA,MAAM,cAAc,MAAM,sBAAsB;AAEhD,KAAI,kBAAkB,YAAY,CAChC,QAAO,EAAE,MAAM,YAAY;AAG7B,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,QAAQ,CAAC;AAEnE,MACE,SAAS,WACT,SAAS,QAAQ,SAAS,yBAAyB,CAEnD,QAAO;SAEH;AACN,SAAO;;AAIX,QAAO"}
|
|
1
|
+
{"version":3,"file":"detectFramework.js","names":[],"sources":["../../src/setup/detectFramework.ts"],"sourcesContent":["import { FrameworkObject } from '../types/index.js';\nimport { isPackageInstalled } from '../utils/packageJson.js';\nimport { searchForPackageJson } from '../utils/packageJson.js';\nimport fs from 'node:fs';\nimport path from 'node:path';\n\n/* ----- MAIN ----- */\n\n/**\n * Detects the frontend framework used in the current project.\n *\n * Analyzes the project structure and dependencies to identify the framework.\n * Detection order: Mintlify → Next.js (App/Pages Router) → Gatsby → RedwoodJS → TanStack Start → Vite → React.\n *\n * For Next.js projects, further determines whether it uses App Router or Pages Router\n * by checking for the presence of `app/` or `pages/` directories.\n *\n * @returns A promise resolving to a FrameworkObject containing:\n * - `name`: The detected framework identifier (e.g., 'next-app', 'gatsby', 'react')\n * or undefined if no framework is detected\n * - `type`: The framework category (currently only 'react' for React-based frameworks)\n */\nexport async function detectFramework(): Promise<\n FrameworkObject | { name: undefined; type?: undefined }\n> {\n const packageJson = await searchForPackageJson();\n\n if (isMintlifyProject(packageJson)) {\n return { name: 'mintlify' };\n }\n\n if (!packageJson) {\n return { name: undefined };\n }\n\n // Check for Next.js first\n if (isPackageInstalled('next', packageJson, false, true)) {\n // Determine if it's App Router or Pages Router\n const cwd = process.cwd();\n const hasAppDir =\n fs.existsSync(path.join(cwd, 'app')) ||\n fs.existsSync(path.join(cwd, 'src', 'app'));\n const hasPagesDir =\n fs.existsSync(path.join(cwd, 'pages')) ||\n fs.existsSync(path.join(cwd, 'src', 'pages'));\n\n // App Router takes precedence if both exist\n if (hasAppDir) {\n return { name: 'next-app', type: 'react' };\n }\n if (hasPagesDir) {\n return { name: 'next-pages', type: 'react' };\n }\n // Default to app router for new Next.js projects\n return { name: 'next-app', type: 'react' };\n }\n\n // Check for Gatsby\n if (isPackageInstalled('gatsby', packageJson, false, true)) {\n return { name: 'gatsby', type: 'react' };\n }\n\n // Check for RedwoodJS\n if (isPackageInstalled('@redwoodjs/core', packageJson, false, true)) {\n return { name: 'redwood', type: 'react' };\n }\n\n // TanStack Start depends on Vite, so check it first\n if (isPackageInstalled('@tanstack/react-start', packageJson, false, true)) {\n return { name: 'tanstack-start', type: 'react' };\n }\n\n // Check for Vite\n if (isPackageInstalled('vite', packageJson, false, true)) {\n return { name: 'vite', type: 'react' };\n }\n\n // Check for React (generic)\n if (isPackageInstalled('react', packageJson, false, true)) {\n return { name: 'react', type: 'react' };\n }\n\n return { name: undefined };\n}\n\n// ----- HELPER FUNCTIONS ----- //\n\n/**\n * Detects if the current project is a Mintlify documentation project.\n *\n * Checks for the presence of docs.json (preferred) or mint.json (legacy) files.\n * For docs.json, validates that the $schema field contains \"mintlify.com/docs.json\".\n * Rejects projects with Next.js config files to avoid misclassification.\n *\n * @param _packageJson - The parsed package.json object (not used for Mintlify detection,\n * but kept for API consistency with other detection functions)\n * @returns True if the project is identified as a Mintlify project, false otherwise\n */\nexport function isMintlifyProject(\n _packageJson: Record<string, unknown> | null\n): boolean {\n const cwd = process.cwd();\n\n // Check for Next.js config files - if present, this is not a Mintlify project\n const nextConfigFiles = [\n 'next.config.js',\n 'next.config.ts',\n 'next.config.mjs',\n 'next.config.cjs',\n ];\n\n for (const configFile of nextConfigFiles) {\n if (fs.existsSync(path.join(cwd, configFile))) {\n return false;\n }\n }\n\n // Check for docs.json (preferred format)\n const docsJsonPath = path.join(cwd, 'docs.json');\n if (fs.existsSync(docsJsonPath)) {\n try {\n const docsJson = JSON.parse(fs.readFileSync(docsJsonPath, 'utf-8'));\n // Validate the $schema field contains mintlify.com/docs.json\n if (\n docsJson.$schema &&\n docsJson.$schema.includes('mintlify.com/docs.json')\n ) {\n return true;\n }\n } catch {\n return false;\n }\n }\n\n return false;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAsBA,eAAsB,kBAEpB;CACA,MAAM,cAAc,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K,KAAK,KAAK,WAAW,CAAC,CAC3C,QAAO;CAKX,MAAM,eAAe,KAAK,KAAK,KAAK,YAAY;AAChD,KAAI,GAAG,WAAW,aAAa,CAC7B,KAAI;EACF,MAAM,WAAW,KAAK,MAAM,GAAG,aAAa,cAAc,QAAQ,CAAC;AAEnE,MACE,SAAS,WACT,SAAS,QAAQ,SAAS,yBAAyB,CAEnD,QAAO;SAEH;AACN,SAAO;;AAIX,QAAO"}
|
|
@@ -123,7 +123,10 @@ async function resolveDevelopmentProject(session, settings, options, cwd = proce
|
|
|
123
123
|
}]
|
|
124
124
|
}) });
|
|
125
125
|
if (choice === void 0) return void 0;
|
|
126
|
-
return choice ? {
|
|
126
|
+
return choice ? {
|
|
127
|
+
id: choice.id,
|
|
128
|
+
name: choice.name
|
|
129
|
+
} : resolveNewProject(session, settings, options, cwd);
|
|
127
130
|
}
|
|
128
131
|
/**
|
|
129
132
|
* Creates the chosen project if needed, mints a development key limited to
|
|
@@ -132,8 +135,11 @@ async function resolveDevelopmentProject(session, settings, options, cwd = proce
|
|
|
132
135
|
*/
|
|
133
136
|
async function provisionDevelopmentCredentials(session, project, settings, framework, cwd = process.cwd()) {
|
|
134
137
|
let projectId;
|
|
135
|
-
|
|
136
|
-
|
|
138
|
+
let projectName;
|
|
139
|
+
if ("id" in project) {
|
|
140
|
+
projectId = project.id;
|
|
141
|
+
projectName = project.name;
|
|
142
|
+
} else {
|
|
137
143
|
const { orgId, name } = project.create;
|
|
138
144
|
const { project: created } = await api.createProject(orgId, {
|
|
139
145
|
name,
|
|
@@ -145,6 +151,7 @@ async function provisionDevelopmentCredentials(session, project, settings, frame
|
|
|
145
151
|
logger.info(`Created ${created.name} (${created.id})`);
|
|
146
152
|
session.step(`created project ${created.id}`);
|
|
147
153
|
projectId = created.id;
|
|
154
|
+
projectName = created.name;
|
|
148
155
|
}
|
|
149
156
|
const { apiKey } = await api.createProjectApiKey(projectId, {
|
|
150
157
|
name: DEVELOPMENT_KEY_NAME,
|
|
@@ -156,7 +163,8 @@ async function provisionDevelopmentCredentials(session, project, settings, frame
|
|
|
156
163
|
apiKey: apiKey.key
|
|
157
164
|
}, framework, cwd);
|
|
158
165
|
session.step("saved development credentials to .env.local");
|
|
159
|
-
|
|
166
|
+
const projectLabel = projectName ? `${projectName} (${projectId})` : projectId;
|
|
167
|
+
logger.success(`Created development key "${apiKey.name}" for project ${projectLabel} and saved both to ${chalk.cyan(".env.local")}.`);
|
|
160
168
|
}
|
|
161
169
|
//#endregion
|
|
162
170
|
export { checkDevelopmentProjectInputs, productionRuntimeKeyGuidance, provisionDevelopmentCredentials, resolveDevelopmentProject, signInForSetup };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"developmentCredentials.js","names":[],"sources":["../../src/setup/developmentCredentials.ts"],"sourcesContent":["import path from 'node:path';\nimport chalk from 'chalk';\nimport { ProjectApiKeyPermission } from 'generaltranslation/api';\nimport {\n createDiagnosticMessage,\n formatDiagnosticErrorDetails,\n} from 'generaltranslation/diagnostics';\nimport { ApiError } from 'generaltranslation/errors';\nimport { logger } from '../console/logger.js';\nimport { promptConfirm, promptSelect, promptText } from '../console/logging.js';\nimport type { Settings, SupportedFrameworks } from '../types/index.js';\nimport { api } from '../utils/api.js';\nimport { setCredentials } from '../utils/credentials.js';\nimport { createUserAuthError } from '../auth/errors.js';\nimport { loginInteractively } from '../auth/interactiveLogin.js';\nimport { OnboardingError, type OnboardingSession } from './onboarding.js';\n\nconst DEVELOPMENT_KEY_NAME = 'Development key (gt init)';\n\n/** .env.local never reaches production; the runtime key there is set on the host. */\nexport function productionRuntimeKeyGuidance(dashboardUrl: string): string {\n return `${chalk.dim('For runtime translation in production, create an API key in the dashboard')} ${chalk.cyan(dashboardUrl)} ${chalk.dim('and set GT_API_KEY and GT_PROJECT_ID in your hosting environment.')}`;\n}\n\n/**\n * Interactive setup keeps the browser login with its device fallback;\n * noninteractive setup always shows a device code (and emits it as a JSON\n * event) and waits for a person to approve it, without opening a browser.\n */\nexport async function signInForSetup(\n session: OnboardingSession,\n baseUrl: string | undefined\n): Promise<void> {\n try {\n await loginInteractively(baseUrl, session.interactive, (deviceCode) =>\n session.emit({ type: 'authorization_required', ...deviceCode })\n );\n } catch (error) {\n throw new OnboardingError(createUserAuthError('Sign in failed', error));\n }\n logger.message('You are now signed in.');\n}\n\ntype ProjectChoice = Awaited<ReturnType<typeof api.listProjects>>[number];\n\n/** An existing project, or the inputs for creating one. */\nexport type DevelopmentProject =\n | { id: string }\n | { create: { orgId: string; name: string } };\n\nexport type DevelopmentProjectOptions = {\n createProject?: boolean;\n orgId?: string;\n projectName?: string;\n};\n\nfunction noAccessibleOrgError(dashboardUrl: string): string {\n return createDiagnosticMessage({\n source: 'gt',\n severity: 'Error',\n whatHappened: 'No accessible organizations were found',\n fix: `Create an organization in the dashboard ${dashboardUrl} or ask an admin for access, then rerun the setup wizard`,\n });\n}\n\nfunction projectCreationDeniedError(orgId: string, error: unknown): string {\n return createDiagnosticMessage({\n source: 'gt',\n severity: 'Error',\n whatHappened: `Project creation was denied for organization ${orgId}`,\n why: 'Listing an organization does not confirm permission to create projects in it',\n fix: 'Ask an organization admin for org:projects:create, or use credentials that have that permission for this organization',\n details: formatDiagnosticErrorDetails(error),\n });\n}\n\nconst noProjectChosenError = createDiagnosticMessage({\n source: 'gt',\n severity: 'Error',\n whatHappened: 'No project was chosen for the development credentials',\n reassurance: 'No project files were changed',\n fix: 'Rerun with --project-id <id> or --create-project, or skip them with --no-dev-credentials',\n});\n\nasync function resolveNewProject(\n session: OnboardingSession,\n settings: Settings,\n options: DevelopmentProjectOptions,\n cwd: string\n): Promise<DevelopmentProject | undefined> {\n // Discovery lists accessible organizations, not creation permissions.\n // The API enforces creation permission when provisioning the project.\n const orgs = await api.listOrgs();\n if (orgs.length === 0) {\n throw new OnboardingError(noAccessibleOrgError(settings.dashboardUrl));\n }\n if (options.orgId && !orgs.some((org) => org.id === options.orgId)) {\n session.reject(\n `--org-id ${options.orgId} is not an accessible organization`\n );\n }\n const orgId = await session.answer('--org-id', {\n explicit: options.orgId,\n // One organization is not a choice between options.\n configured: orgs.length === 1 ? orgs[0].id : undefined,\n ask: () =>\n promptSelect({\n message: 'Which organization should own the new project?',\n options: orgs.map((org) => ({ value: org.id, label: org.name })),\n }),\n });\n const name = await session.answer('--project-name', {\n explicit: options.projectName?.trim() || undefined,\n ask: async () =>\n (\n await promptText({\n message: 'What should the project be called?',\n defaultValue: path.basename(cwd),\n })\n ).trim() || path.basename(cwd),\n });\n return orgId && name ? { create: { orgId, name } } : undefined;\n}\n\n/**\n * Records project inputs a noninteractive run is missing, before signing in,\n * so it never waits for approval only to fail on a missing flag.\n */\nexport function checkDevelopmentProjectInputs(\n session: OnboardingSession,\n settings: Settings,\n options: DevelopmentProjectOptions,\n /** Where settings.projectId came from, so a person can remove it. */\n projectIdSource: string\n): void {\n if (settings.projectId && options.createProject) {\n session.reject(\n `--create-project cannot be combined with project ${settings.projectId} from ${projectIdSource}; remove --create-project to keep using it, or remove the project ID from ${projectIdSource} to create a new project`\n );\n }\n if (settings.projectId || session.interactive) return;\n if (!options.createProject) {\n session.require('--project-id or --create-project');\n } else if (!options.projectName?.trim()) {\n session.require('--project-name');\n }\n}\n\n/**\n * Chooses the project for development credentials without creating anything:\n * a supplied or configured ID, explicit creation inputs, or (interactively)\n * a selection among the account's projects.\n */\nexport async function resolveDevelopmentProject(\n session: OnboardingSession,\n settings: Settings,\n options: DevelopmentProjectOptions,\n cwd: string = process.cwd()\n): Promise<DevelopmentProject | undefined> {\n if (settings.projectId) return { id: settings.projectId };\n if (options.createProject) {\n return resolveNewProject(session, settings, options, cwd);\n }\n const projects = await api.listProjects();\n if (projects.length === 0) {\n // Creating a project is its own choice, separate from creating a key.\n const create = await session.answer('--project-id or --create-project', {\n ask: () =>\n promptConfirm({\n message: 'No projects found for your account. Create a new project?',\n defaultValue: true,\n }),\n });\n if (create === false) throw new OnboardingError(noProjectChosenError);\n return create\n ? resolveNewProject(session, settings, options, cwd)\n : undefined;\n }\n const choice = await session.answer<ProjectChoice | null>(\n '--project-id or --create-project',\n {\n ask: () =>\n promptSelect<ProjectChoice | null>({\n message: 'Which project should this app use?',\n options: [\n ...projects.map((project) => ({\n value: project,\n label: project.name,\n hint: project.orgName,\n })),\n { value: null, label: 'Create a new project' },\n ],\n }),\n }\n );\n if (choice === undefined) return undefined;\n return choice\n ? { id: choice.id }\n : resolveNewProject(session, settings, options, cwd);\n}\n\n/**\n * Creates the chosen project if needed, mints a development key limited to\n * runtime translation, and saves both to .env.local. Callers inspect\n * .env.local first; the key is never printed.\n */\nexport async function provisionDevelopmentCredentials(\n session: OnboardingSession,\n project: DevelopmentProject,\n settings: Settings,\n framework: SupportedFrameworks | undefined,\n cwd: string = process.cwd()\n): Promise<void> {\n let projectId: string;\n if ('id' in project) {\n projectId = project.id;\n } else {\n const { orgId, name } = project.create;\n const { project: created } = await api\n .createProject(orgId, { name, defaultLocale: settings.defaultLocale })\n .catch((error: unknown) => {\n if (!(error instanceof ApiError) || error.code !== 403) throw error;\n throw new OnboardingError(projectCreationDeniedError(orgId, error));\n });\n logger.info(`Created ${created.name} (${created.id})`);\n session.step(`created project ${created.id}`);\n projectId = created.id;\n }\n const { apiKey } = await api.createProjectApiKey(projectId, {\n name: DEVELOPMENT_KEY_NAME,\n permissions: [ProjectApiKeyPermission['PROJECT:TRANSLATIONS:GENERATE']],\n });\n session.step('created a development key');\n await setCredentials({ projectId, apiKey: apiKey.key }, framework, cwd);\n session.step('saved development credentials to .env.local');\n logger.success(\n `Saved the project ID and a development key to ${chalk.cyan('.env.local')}.`\n );\n}\n"],"mappings":";;;;;;;;;;;;;AAiBA,MAAM,uBAAuB;;AAG7B,SAAgB,6BAA6B,cAA8B;AACzE,QAAO,GAAG,MAAM,IAAI,4EAA4E,CAAC,GAAG,MAAM,KAAK,aAAa,CAAC,GAAG,MAAM,IAAI,oEAAoE;;;;;;;AAQhN,eAAsB,eACpB,SACA,SACe;AACf,KAAI;AACF,QAA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,EAAE,IAAI,OAAO,IAAI,GACjB,kBAAkB,SAAS,UAAU,SAAS,IAAI;;;;;;;AAQxD,eAAsB,gCACpB,SACA,SACA,UACA,WACA,MAAc,QAAQ,KAAK,EACZ;CACf,IAAI;AACJ,KAAI,QAAQ,QACV,aAAY,QAAQ;MACf;EACL,MAAM,EAAE,OAAO,SAAS,QAAQ;EAChC,MAAM,EAAE,SAAS,YAAY,MAAM,IAChC,cAAc,OAAO;GAAE;GAAM,eAAe,SAAS;GAAe,CAAC,CACrE,OAAO,UAAmB;AACzB,OAAI,EAAE,iBAAiB,aAAa,MAAM,SAAS,IAAK,OAAM;AAC9D,SAAM,IAAI,gBAAgB,2BAA2B,OAAO,MAAM,CAAC;IACnE;AACJ,SAAO,KAAK,WAAW,QAAQ,KAAK,IAAI,QAAQ,GAAG,GAAG;AACtD,UAAQ,KAAK,mBAAmB,QAAQ,KAAK;AAC7C,cAAY,QAAQ;;CAEtB,MAAM,EAAE,WAAW,MAAM,IAAI,oBAAoB,WAAW;EAC1D,MAAM;EACN,aAAa,CAAC,wBAAwB,iCAAiC;EACxE,CAAC;AACF,SAAQ,KAAK,4BAA4B;AACzC,OAAM,eAAe;EAAE;EAAW,QAAQ,OAAO;EAAK,EAAE,WAAW,IAAI;AACvE,SAAQ,KAAK,8CAA8C;AAC3D,QAAO,QACL,iDAAiD,MAAM,KAAK,aAAa,CAAC,GAC3E"}
|
|
1
|
+
{"version":3,"file":"developmentCredentials.js","names":[],"sources":["../../src/setup/developmentCredentials.ts"],"sourcesContent":["import path from 'node:path';\nimport chalk from 'chalk';\nimport { ProjectApiKeyPermission } from 'generaltranslation/api';\nimport {\n createDiagnosticMessage,\n formatDiagnosticErrorDetails,\n} from 'generaltranslation/diagnostics';\nimport { ApiError } from 'generaltranslation/errors';\nimport { logger } from '../console/logger.js';\nimport { promptConfirm, promptSelect, promptText } from '../console/logging.js';\nimport type { Settings, SupportedFrameworks } from '../types/index.js';\nimport { api } from '../utils/api.js';\nimport { setCredentials } from '../utils/credentials.js';\nimport { createUserAuthError } from '../auth/errors.js';\nimport { loginInteractively } from '../auth/interactiveLogin.js';\nimport { OnboardingError, type OnboardingSession } from './onboarding.js';\n\nconst DEVELOPMENT_KEY_NAME = 'Development key (gt init)';\n\n/** .env.local never reaches production; the runtime key there is set on the host. */\nexport function productionRuntimeKeyGuidance(dashboardUrl: string): string {\n return `${chalk.dim('For runtime translation in production, create an API key in the dashboard')} ${chalk.cyan(dashboardUrl)} ${chalk.dim('and set GT_API_KEY and GT_PROJECT_ID in your hosting environment.')}`;\n}\n\n/**\n * Interactive setup keeps the browser login with its device fallback;\n * noninteractive setup always shows a device code (and emits it as a JSON\n * event) and waits for a person to approve it, without opening a browser.\n */\nexport async function signInForSetup(\n session: OnboardingSession,\n baseUrl: string | undefined\n): Promise<void> {\n try {\n await loginInteractively(baseUrl, session.interactive, (deviceCode) =>\n session.emit({ type: 'authorization_required', ...deviceCode })\n );\n } catch (error) {\n throw new OnboardingError(createUserAuthError('Sign in failed', error));\n }\n logger.message('You are now signed in.');\n}\n\ntype ProjectChoice = Awaited<ReturnType<typeof api.listProjects>>[number];\n\n/** An existing project, or the inputs for creating one. */\nexport type DevelopmentProject =\n | { id: string; name?: string }\n | { create: { orgId: string; name: string } };\n\nexport type DevelopmentProjectOptions = {\n createProject?: boolean;\n orgId?: string;\n projectName?: string;\n};\n\nfunction noAccessibleOrgError(dashboardUrl: string): string {\n return createDiagnosticMessage({\n source: 'gt',\n severity: 'Error',\n whatHappened: 'No accessible organizations were found',\n fix: `Create an organization in the dashboard ${dashboardUrl} or ask an admin for access, then rerun the setup wizard`,\n });\n}\n\nfunction projectCreationDeniedError(orgId: string, error: unknown): string {\n return createDiagnosticMessage({\n source: 'gt',\n severity: 'Error',\n whatHappened: `Project creation was denied for organization ${orgId}`,\n why: 'Listing an organization does not confirm permission to create projects in it',\n fix: 'Ask an organization admin for org:projects:create, or use credentials that have that permission for this organization',\n details: formatDiagnosticErrorDetails(error),\n });\n}\n\nconst noProjectChosenError = createDiagnosticMessage({\n source: 'gt',\n severity: 'Error',\n whatHappened: 'No project was chosen for the development credentials',\n reassurance: 'No project files were changed',\n fix: 'Rerun with --project-id <id> or --create-project, or skip them with --no-dev-credentials',\n});\n\nasync function resolveNewProject(\n session: OnboardingSession,\n settings: Settings,\n options: DevelopmentProjectOptions,\n cwd: string\n): Promise<DevelopmentProject | undefined> {\n // Discovery lists accessible organizations, not creation permissions.\n // The API enforces creation permission when provisioning the project.\n const orgs = await api.listOrgs();\n if (orgs.length === 0) {\n throw new OnboardingError(noAccessibleOrgError(settings.dashboardUrl));\n }\n if (options.orgId && !orgs.some((org) => org.id === options.orgId)) {\n session.reject(\n `--org-id ${options.orgId} is not an accessible organization`\n );\n }\n const orgId = await session.answer('--org-id', {\n explicit: options.orgId,\n // One organization is not a choice between options.\n configured: orgs.length === 1 ? orgs[0].id : undefined,\n ask: () =>\n promptSelect({\n message: 'Which organization should own the new project?',\n options: orgs.map((org) => ({ value: org.id, label: org.name })),\n }),\n });\n const name = await session.answer('--project-name', {\n explicit: options.projectName?.trim() || undefined,\n ask: async () =>\n (\n await promptText({\n message: 'What should the project be called?',\n defaultValue: path.basename(cwd),\n })\n ).trim() || path.basename(cwd),\n });\n return orgId && name ? { create: { orgId, name } } : undefined;\n}\n\n/**\n * Records project inputs a noninteractive run is missing, before signing in,\n * so it never waits for approval only to fail on a missing flag.\n */\nexport function checkDevelopmentProjectInputs(\n session: OnboardingSession,\n settings: Settings,\n options: DevelopmentProjectOptions,\n /** Where settings.projectId came from, so a person can remove it. */\n projectIdSource: string\n): void {\n if (settings.projectId && options.createProject) {\n session.reject(\n `--create-project cannot be combined with project ${settings.projectId} from ${projectIdSource}; remove --create-project to keep using it, or remove the project ID from ${projectIdSource} to create a new project`\n );\n }\n if (settings.projectId || session.interactive) return;\n if (!options.createProject) {\n session.require('--project-id or --create-project');\n } else if (!options.projectName?.trim()) {\n session.require('--project-name');\n }\n}\n\n/**\n * Chooses the project for development credentials without creating anything:\n * a supplied or configured ID, explicit creation inputs, or (interactively)\n * a selection among the account's projects.\n */\nexport async function resolveDevelopmentProject(\n session: OnboardingSession,\n settings: Settings,\n options: DevelopmentProjectOptions,\n cwd: string = process.cwd()\n): Promise<DevelopmentProject | undefined> {\n if (settings.projectId) return { id: settings.projectId };\n if (options.createProject) {\n return resolveNewProject(session, settings, options, cwd);\n }\n const projects = await api.listProjects();\n if (projects.length === 0) {\n // Creating a project is its own choice, separate from creating a key.\n const create = await session.answer('--project-id or --create-project', {\n ask: () =>\n promptConfirm({\n message: 'No projects found for your account. Create a new project?',\n defaultValue: true,\n }),\n });\n if (create === false) throw new OnboardingError(noProjectChosenError);\n return create\n ? resolveNewProject(session, settings, options, cwd)\n : undefined;\n }\n const choice = await session.answer<ProjectChoice | null>(\n '--project-id or --create-project',\n {\n ask: () =>\n promptSelect<ProjectChoice | null>({\n message: 'Which project should this app use?',\n options: [\n ...projects.map((project) => ({\n value: project,\n label: project.name,\n hint: project.orgName,\n })),\n { value: null, label: 'Create a new project' },\n ],\n }),\n }\n );\n if (choice === undefined) return undefined;\n return choice\n ? { id: choice.id, name: choice.name }\n : resolveNewProject(session, settings, options, cwd);\n}\n\n/**\n * Creates the chosen project if needed, mints a development key limited to\n * runtime translation, and saves both to .env.local. Callers inspect\n * .env.local first; the key is never printed.\n */\nexport async function provisionDevelopmentCredentials(\n session: OnboardingSession,\n project: DevelopmentProject,\n settings: Settings,\n framework: SupportedFrameworks | undefined,\n cwd: string = process.cwd()\n): Promise<void> {\n let projectId: string;\n let projectName: string | undefined;\n if ('id' in project) {\n projectId = project.id;\n projectName = project.name;\n } else {\n const { orgId, name } = project.create;\n const { project: created } = await api\n .createProject(orgId, { name, defaultLocale: settings.defaultLocale })\n .catch((error: unknown) => {\n if (!(error instanceof ApiError) || error.code !== 403) throw error;\n throw new OnboardingError(projectCreationDeniedError(orgId, error));\n });\n logger.info(`Created ${created.name} (${created.id})`);\n session.step(`created project ${created.id}`);\n projectId = created.id;\n projectName = created.name;\n }\n const { apiKey } = await api.createProjectApiKey(projectId, {\n name: DEVELOPMENT_KEY_NAME,\n permissions: [ProjectApiKeyPermission['PROJECT:TRANSLATIONS:GENERATE']],\n });\n session.step('created a development key');\n await setCredentials({ projectId, apiKey: apiKey.key }, framework, cwd);\n session.step('saved development credentials to .env.local');\n const projectLabel = projectName\n ? `${projectName} (${projectId})`\n : projectId;\n logger.success(\n `Created development key \"${apiKey.name}\" for project ${projectLabel} and saved both to ${chalk.cyan('.env.local')}.`\n );\n}\n"],"mappings":";;;;;;;;;;;;;AAiBA,MAAM,uBAAuB;;AAG7B,SAAgB,6BAA6B,cAA8B;AACzE,QAAO,GAAG,MAAM,IAAI,4EAA4E,CAAC,GAAG,MAAM,KAAK,aAAa,CAAC,GAAG,MAAM,IAAI,oEAAoE;;;;;;;AAQhN,eAAsB,eACpB,SACA,SACe;AACf,KAAI;AACF,QAAM,mBAAmB,SAAS,QAAQ,cAAc,eACtD,QAAQ,KAAK;GAAE,MAAM;GAA0B,GAAG;GAAY,CAAC,CAChE;UACM,OAAO;AACd,QAAM,IAAI,gBAAgB,oBAAoB,kBAAkB,MAAM,CAAC;;AAEzE,QAAO,QAAQ,yBAAyB;;AAgB1C,SAAS,qBAAqB,cAA8B;AAC1D,QAAO,wBAAwB;EAC7B,QAAQ;EACR,UAAU;EACV,cAAc;EACd,KAAK,2CAA2C,aAAa;EAC9D,CAAC;;AAGJ,SAAS,2BAA2B,OAAe,OAAwB;AACzE,QAAO,wBAAwB;EAC7B,QAAQ;EACR,UAAU;EACV,cAAc,gDAAgD;EAC9D,KAAK;EACL,KAAK;EACL,SAAS,6BAA6B,MAAM;EAC7C,CAAC;;AAGJ,MAAM,uBAAuB,wBAAwB;CACnD,QAAQ;CACR,UAAU;CACV,cAAc;CACd,aAAa;CACb,KAAK;CACN,CAAC;AAEF,eAAe,kBACb,SACA,UACA,SACA,KACyC;CAGzC,MAAM,OAAO,MAAM,IAAI,UAAU;AACjC,KAAI,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AM,EAAE,WAAW,MAAM,IAAI,oBAAoB,WAAW;EAC1D,MAAM;EACN,aAAa,CAAC,wBAAwB,iCAAiC;EACxE,CAAC;AACF,SAAQ,KAAK,4BAA4B;AACzC,OAAM,eAAe;EAAE;EAAW,QAAQ,OAAO;EAAK,EAAE,WAAW,IAAI;AACvE,SAAQ,KAAK,8CAA8C;CAC3D,MAAM,eAAe,cACjB,GAAG,YAAY,IAAI,UAAU,KAC7B;AACJ,QAAO,QACL,4BAA4B,OAAO,KAAK,gBAAgB,aAAa,qBAAqB,MAAM,KAAK,aAAa,CAAC,GACpH"}
|
|
@@ -7,11 +7,14 @@ function getFrameworkDisplayName(frameworkObject) {
|
|
|
7
7
|
if (frameworkObject.name === "vite") return "Vite + React";
|
|
8
8
|
if (frameworkObject.name === "gatsby") return "Gatsby";
|
|
9
9
|
if (frameworkObject.name === "redwood") return "RedwoodJS";
|
|
10
|
+
if (frameworkObject.name === "tanstack-start") return "TanStack Start";
|
|
10
11
|
if (frameworkObject.type === "react") return "React";
|
|
11
12
|
return "another framework";
|
|
12
13
|
}
|
|
13
14
|
function getReactFrameworkLibrary(frameworkObject) {
|
|
14
|
-
|
|
15
|
+
if (frameworkObject.name === "next-app") return "gt-next";
|
|
16
|
+
if (frameworkObject.name === "tanstack-start") return "gt-tanstack-start";
|
|
17
|
+
return "gt-react";
|
|
15
18
|
}
|
|
16
19
|
//#endregion
|
|
17
20
|
export { getFrameworkDisplayName, getReactFrameworkLibrary };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"frameworkUtils.js","names":[],"sources":["../../src/setup/frameworkUtils.ts"],"sourcesContent":["import { FrameworkObject, ReactFrameworkObject } from '../types/index.js';\nimport { Libraries } from '../types/libraries.js';\n\nexport function getFrameworkDisplayName(\n frameworkObject: FrameworkObject\n): string {\n if (frameworkObject.name === 'mintlify') {\n return 'Mintlify';\n }\n if (frameworkObject.name === 'next-app') {\n return 'Next.js App Router';\n }\n if (frameworkObject.name === 'next-pages') {\n return 'Next.js Pages Router';\n }\n if (frameworkObject.name === 'vite') {\n return 'Vite + React';\n }\n if (frameworkObject.name === 'gatsby') {\n return 'Gatsby';\n }\n if (frameworkObject.name === 'redwood') {\n return 'RedwoodJS';\n }\n if (frameworkObject.type === 'react') {\n return 'React';\n }\n return 'another framework';\n}\n\nexport function getReactFrameworkLibrary(\n frameworkObject: ReactFrameworkObject\n): string {\n
|
|
1
|
+
{"version":3,"file":"frameworkUtils.js","names":[],"sources":["../../src/setup/frameworkUtils.ts"],"sourcesContent":["import { FrameworkObject, ReactFrameworkObject } from '../types/index.js';\nimport { Libraries } from '../types/libraries.js';\n\nexport function getFrameworkDisplayName(\n frameworkObject: FrameworkObject\n): string {\n if (frameworkObject.name === 'mintlify') {\n return 'Mintlify';\n }\n if (frameworkObject.name === 'next-app') {\n return 'Next.js App Router';\n }\n if (frameworkObject.name === 'next-pages') {\n return 'Next.js Pages Router';\n }\n if (frameworkObject.name === 'vite') {\n return 'Vite + React';\n }\n if (frameworkObject.name === 'gatsby') {\n return 'Gatsby';\n }\n if (frameworkObject.name === 'redwood') {\n return 'RedwoodJS';\n }\n if (frameworkObject.name === 'tanstack-start') {\n return 'TanStack Start';\n }\n if (frameworkObject.type === 'react') {\n return 'React';\n }\n return 'another framework';\n}\n\nexport function getReactFrameworkLibrary(\n frameworkObject: ReactFrameworkObject\n): string {\n if (frameworkObject.name === 'next-app') return Libraries.GT_NEXT;\n if (frameworkObject.name === 'tanstack-start') {\n return Libraries.GT_TANSTACK_START;\n }\n return Libraries.GT_REACT;\n}\n"],"mappings":";;AAGA,SAAgB,wBACd,iBACQ;AACR,KAAI,gBAAgB,SAAS,WAC3B,QAAO;AAET,KAAI,gBAAgB,SAAS,WAC3B,QAAO;AAET,KAAI,gBAAgB,SAAS,aAC3B,QAAO;AAET,KAAI,gBAAgB,SAAS,OAC3B,QAAO;AAET,KAAI,gBAAgB,SAAS,SAC3B,QAAO;AAET,KAAI,gBAAgB,SAAS,UAC3B,QAAO;AAET,KAAI,gBAAgB,SAAS,iBAC3B,QAAO;AAET,KAAI,gBAAgB,SAAS,QAC3B,QAAO;AAET,QAAO;;AAGT,SAAgB,yBACd,iBACQ;AACR,KAAI,gBAAgB,SAAS,WAAY,QAAA;AACzC,KAAI,gBAAgB,SAAS,iBAC3B,QAAA;AAEF,QAAA"}
|
package/dist/setup/onboarding.js
CHANGED
|
@@ -5,8 +5,8 @@ import findFilepath from "../fs/findFilepath.js";
|
|
|
5
5
|
import { withJsonExtension } from "../fs/config/loadConfig.js";
|
|
6
6
|
import { SETUP_FILE_FORMATS } from "../formats/files/supportedFiles.js";
|
|
7
7
|
import { getFrameworkDisplayName, getReactFrameworkLibrary } from "./frameworkUtils.js";
|
|
8
|
-
import { SUPPORTED_REACT_FRAMEWORKS } from "../types/index.js";
|
|
9
8
|
import { getBuildToolSetup } from "./buildTools/index.js";
|
|
9
|
+
import { SUPPORTED_REACT_FRAMEWORKS } from "../types/index.js";
|
|
10
10
|
import { NoPackageManagerError, getPackageManager, packageManagers } from "../utils/packageManager.js";
|
|
11
11
|
import { installPackage } from "../utils/installPackage.js";
|
|
12
12
|
import { createDiagnosticMessage, formatDiagnosticErrorDetails } from "generaltranslation/internal";
|
|
@@ -15,7 +15,7 @@ import { Option } from "commander";
|
|
|
15
15
|
//#region src/setup/onboarding.ts
|
|
16
16
|
/** Flags for every configuration question; values prefill interactive runs. */
|
|
17
17
|
function attachConfigureFlags(command, sourceHelp) {
|
|
18
|
-
return reportJsonArgumentErrors(command).option("--src <paths...>", sourceHelp).option("-c, --config <path>", "Filepath to config file, by default gt.config.json", findFilepath(["gt.config.json"])).option("--no-interactive", "Never prompt; fail listing the options still needed. Automatic when stdin or stdout is not a terminal").option("--json", "Write JSON events (sign-in, handoff, result) to stdout and all other output to stderr; implies --no-interactive").option("--defaults", "Accept the recommended value for every local choice that no flag or gt.config.json answers; never creates projects or keys").option("--no-defaults", "Do not offer the recommended defaults").option("--default-locale <locale>", "Default locale, e.g. en").option("--locales <locales...>", "Locales to translate into, e.g. fr es; replaces the configured list").addOption(new Option("--storage <storage>", "Where GT translations are stored for GT runtimes").choices(["local", "cdn"])).option("--translations-dir <path>", "Directory for local GT translation files").addOption(new Option("--file-formats <formats...>", "Additional file formats to translate, or none").choices([...SETUP_FILE_FORMATS, "none"])).option("--file-patterns <patterns...>", "Glob patterns as <format>=<glob> including [locale], e.g. json=./locales/[locale]/*.json; selects the format").option("--live-translations", "Local Vite storage: set up live development translations (creates a development key)").option("--no-live-translations", "Skip live development translations").
|
|
18
|
+
return reportJsonArgumentErrors(command).option("--src <paths...>", sourceHelp).option("-c, --config <path>", "Filepath to config file, by default gt.config.json", findFilepath(["gt.config.json"])).option("--no-interactive", "Never prompt; fail listing the options still needed. Automatic when stdin or stdout is not a terminal").option("--json", "Write JSON events (sign-in, handoff, result) to stdout and all other output to stderr; implies --no-interactive").option("--defaults", "Accept the recommended value for every local choice that no flag or gt.config.json answers; never creates projects or keys").option("--no-defaults", "Do not offer the recommended defaults").option("--default-locale <locale>", "Default locale, e.g. en").option("--locales <locales...>", "Locales to translate into, e.g. fr es; replaces the configured list").addOption(new Option("--storage <storage>", "Where GT translations are stored for GT runtimes").choices(["local", "cdn"])).option("--translations-dir <path>", "Directory for local GT translation files").addOption(new Option("--file-formats <formats...>", "Additional file formats to translate, or none").choices([...SETUP_FILE_FORMATS, "none"])).option("--file-patterns <patterns...>", "Glob patterns as <format>=<glob> including [locale], e.g. json=./locales/[locale]/*.json; selects the format").option("--live-translations", "Local Vite storage: set up live development translations (creates a development key)").option("--no-live-translations", "Skip live development translations").addOption(new Option("--dev-credentials", "Save a project ID and a new development key to .env.local").conflicts("liveTranslations")).option("--no-dev-credentials", "Do not create development credentials").option("--project-id <id>", "Existing project for the development credentials").option("--create-project", "Create a new project for the development credentials").option("--org-id <id>", "Organization that owns --create-project").option("--project-name <name>", "Name for --create-project").addOption(new Option("--package-manager <id>", "Package manager for installs when it cannot be detected").choices(packageManagers.map((packageManager) => packageManager.id)));
|
|
19
19
|
}
|
|
20
20
|
let commandBeforeOnboarding;
|
|
21
21
|
function reportExitBeforeOnboarding(code) {
|
|
@@ -119,7 +119,7 @@ var OnboardingSession = class {
|
|
|
119
119
|
whatHappened: missingOptions.length > 0 ? `Setup needs these options: ${missingOptions.join(", ")}` : "Setup received invalid options",
|
|
120
120
|
reassurance: "No project files were changed",
|
|
121
121
|
details: this.invalid,
|
|
122
|
-
fix: "Pass the options (see --help), add --defaults to accept the recommended local choices, or rerun in an interactive terminal"
|
|
122
|
+
fix: this.defaults ? "Pass the options (see --help), or rerun in an interactive terminal" : "Pass the options (see --help), add --defaults to accept the recommended local choices, or rerun in an interactive terminal"
|
|
123
123
|
}), missingOptions);
|
|
124
124
|
}
|
|
125
125
|
step(name) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"onboarding.js","names":[],"sources":["../../src/setup/onboarding.ts"],"sourcesContent":["import fs from 'node:fs';\nimport { Command, Option, type CommanderError } from 'commander';\nimport {\n createDiagnosticMessage,\n formatDiagnosticErrorDetails,\n} from 'generaltranslation/internal';\nimport findFilepath from '../fs/findFilepath.js';\nimport { withJsonExtension } from '../fs/config/loadConfig.js';\nimport { logger } from '../console/logger.js';\nimport {\n displayHeader,\n getLastExitError,\n logErrorAndExit,\n stripAnsi,\n} from '../console/logging.js';\nimport {\n SUPPORTED_REACT_FRAMEWORKS,\n type FrameworkObject,\n type SupportedReactFrameworks,\n} from '../types/index.js';\nimport { DEFAULT_TRANSLATIONS_DIR } from '../utils/constants.js';\nimport { getBuildToolSetup } from './buildTools/index.js';\nimport {\n getFrameworkDisplayName,\n getReactFrameworkLibrary,\n} from './frameworkUtils.js';\nimport {\n SETUP_FILE_FORMATS,\n type SetupFileFormat,\n} from '../formats/files/supportedFiles.js';\nimport {\n getPackageManager,\n NoPackageManagerError,\n packageManagers,\n type PackageManager,\n} from '../utils/packageManager.js';\nimport { installPackage } from '../utils/installPackage.js';\n\n/** Answers accepted by `gt configure` (and the gt-vue `gt init`). */\nexport type ConfigureOptions = {\n config: string;\n src?: string[];\n interactive?: boolean;\n json?: boolean;\n defaults?: boolean;\n defaultLocale?: string;\n locales?: string[];\n storage?: 'local' | 'cdn';\n translationsDir?: string;\n fileFormats?: Array<SetupFileFormat | 'none'>;\n filePatterns?: string[];\n liveTranslations?: boolean;\n devCredentials?: boolean;\n projectId?: string;\n createProject?: boolean;\n orgId?: string;\n projectName?: string;\n packageManager?: string;\n};\n\n/** Answers accepted by the React-aware `gt init`. */\nexport type InitOptions = ConfigureOptions & {\n locadex?: boolean;\n reactSetup?: boolean;\n framework?: SupportedReactFrameworks;\n format?: boolean;\n};\n\n/** Flags for every configuration question; values prefill interactive runs. */\nexport function attachConfigureFlags(\n command: Command,\n sourceHelp: string\n): Command {\n return reportJsonArgumentErrors(command)\n .option('--src <paths...>', sourceHelp)\n .option(\n '-c, --config <path>',\n 'Filepath to config file, by default gt.config.json',\n findFilepath(['gt.config.json'])\n )\n .option(\n '--no-interactive',\n 'Never prompt; fail listing the options still needed. Automatic when stdin or stdout is not a terminal'\n )\n .option(\n '--json',\n 'Write JSON events (sign-in, handoff, result) to stdout and all other output to stderr; implies --no-interactive'\n )\n .option(\n '--defaults',\n 'Accept the recommended value for every local choice that no flag or gt.config.json answers; never creates projects or keys'\n )\n .option('--no-defaults', 'Do not offer the recommended defaults')\n .option('--default-locale <locale>', 'Default locale, e.g. en')\n .option(\n '--locales <locales...>',\n 'Locales to translate into, e.g. fr es; replaces the configured list'\n )\n .addOption(\n new Option(\n '--storage <storage>',\n 'Where GT translations are stored for GT runtimes'\n ).choices(['local', 'cdn'])\n )\n .option(\n '--translations-dir <path>',\n 'Directory for local GT translation files'\n )\n .addOption(\n new Option(\n '--file-formats <formats...>',\n 'Additional file formats to translate, or none'\n ).choices([...SETUP_FILE_FORMATS, 'none'])\n )\n .option(\n '--file-patterns <patterns...>',\n 'Glob patterns as <format>=<glob> including [locale], e.g. json=./locales/[locale]/*.json; selects the format'\n )\n .option(\n '--live-translations',\n 'Local Vite storage: set up live development translations (creates a development key)'\n )\n .option('--no-live-translations', 'Skip live development translations')\n .option(\n '--dev-credentials',\n 'Save a project ID and a new development key to .env.local'\n )\n .option('--no-dev-credentials', 'Do not create development credentials')\n .option(\n '--project-id <id>',\n 'Existing project for the development credentials'\n )\n .option(\n '--create-project',\n 'Create a new project for the development credentials'\n )\n .option('--org-id <id>', 'Organization that owns --create-project')\n .option('--project-name <name>', 'Name for --create-project')\n .addOption(\n new Option(\n '--package-manager <id>',\n 'Package manager for installs when it cannot be detected'\n ).choices(packageManagers.map((packageManager) => packageManager.id))\n );\n}\n\nlet commandBeforeOnboarding: string | undefined;\n\nfunction reportExitBeforeOnboarding(code: number): void {\n if (code === 0 || commandBeforeOnboarding === undefined) return;\n fs.writeSync(\n process.stdout.fd,\n `${JSON.stringify({\n type: 'result',\n command: commandBeforeOnboarding,\n outcome: 'failed',\n completedSteps: [],\n error: stripAnsi(\n getLastExitError() ?? 'Setup exited before it started; see stderr'\n ),\n } satisfies OnboardingEvent)}\\n`\n );\n}\n\n/**\n * Pre-action hooks, such as the monorepo version check, can exit before\n * runOnboarding installs its own result reporting; `--json` callers still\n * get a result. runOnboarding takes over once it starts.\n */\nexport function reportJsonExitsBeforeOnboarding(command: string): void {\n commandBeforeOnboarding = command;\n process.once('exit', reportExitBeforeOnboarding);\n}\n\n/**\n * Argument errors happen before the action runs, so `--json` callers would\n * otherwise get no result. Commander prints the error to stderr, then calls\n * this exit hook; returning lets it exit with the same code as before. The\n * hook replaces an exit override inherited from the program.\n */\nfunction reportJsonArgumentErrors(command: Command): Command {\n return command.exitOverride((error: CommanderError) => {\n if (error.exitCode === 0) return; // help and version output\n // An option after the failing argument is not parsed yet.\n const json =\n command.opts().json === true || process.argv.includes('--json');\n if (!json) return;\n fs.writeSync(\n process.stdout.fd,\n `${JSON.stringify({\n type: 'result',\n command: command.name(),\n outcome: 'failed',\n completedSteps: [],\n error: stripAnsi(error.message),\n } satisfies OnboardingEvent)}\\n`\n );\n });\n}\n\n/** Configuration flags plus the React application setup and Locadex choices. */\nexport function attachInitFlags(command: Command, sourceHelp: string) {\n return attachConfigureFlags(command, sourceHelp)\n .option(\n '--locadex',\n 'Mintlify and Next.js App Router: hand setup to the Locadex AI agent through GitHub instead'\n )\n .option('--no-locadex', 'Set up this project locally')\n .option(\n '--react-setup',\n 'React projects: install the GT library and add GTProvider or initializeGTSPA'\n )\n .option('--no-react-setup', 'Do not modify application source')\n .addOption(\n new Option(\n '--framework <framework>',\n 'React framework for --react-setup; overrides detection'\n ).choices(SUPPORTED_REACT_FRAMEWORKS)\n )\n .option(\n '--format',\n 'Next.js App Router: format files changed by setup with the detected formatter'\n )\n .option('--no-format', 'Leave files changed by setup unformatted');\n}\n\nexport type OnboardingEvent =\n | {\n type: 'authorization_required';\n verificationUri: string;\n verificationUriComplete?: string;\n userCode: string;\n }\n | { type: 'handoff'; url: string; reason: 'locadex' }\n | {\n type: 'result';\n command: string;\n outcome: 'success' | 'needs_human_action' | 'failed';\n completedSteps: string[];\n url?: string;\n /** Manual steps setup could not do, for needs_human_action. */\n actions?: string[];\n missingOptions?: string[];\n error?: string;\n };\n\n/** Needs-input and validation failures, raised before setup changes files. */\nexport class OnboardingError extends Error {\n constructor(\n message: string,\n readonly missingOptions: string[] = []\n ) {\n super(message);\n this.name = 'OnboardingError';\n }\n}\n\nfunction isInteractiveTerminal(): boolean {\n return process.stdin.isTTY === true && process.stdout.isTTY === true;\n}\n\n/**\n * One setup run: how unanswered questions are resolved, which options are\n * still missing, and which steps already changed the project.\n */\nexport class OnboardingSession {\n readonly interactive: boolean;\n readonly json: boolean;\n defaults = false;\n readonly completedSteps: string[] = [];\n /** Manual steps left for a person; they make the outcome needs_human_action. */\n readonly humanActions: string[] = [];\n private readonly missing = new Set<string>();\n private readonly invalid: string[] = [];\n private reported = false;\n\n constructor(\n readonly command: string,\n options: Pick<ConfigureOptions, 'json' | 'interactive'>\n ) {\n this.json = options.json === true;\n this.interactive =\n options.interactive !== false && !this.json && isInteractiveTerminal();\n }\n\n /**\n * Explicit flag, then existing config, then the recommended value when\n * defaults were accepted, then a prompt. Noninteractive runs use the\n * fallback of an optional question, or record the option as missing.\n */\n async answer<T>(\n option: string,\n {\n explicit,\n configured,\n recommended,\n fallback,\n ask,\n }: {\n explicit?: T;\n configured?: T;\n recommended?: T;\n fallback?: T;\n ask: () => Promise<T>;\n }\n ): Promise<T | undefined> {\n if (explicit !== undefined) return explicit;\n if (configured !== undefined) return configured;\n if (this.defaults && recommended !== undefined) return recommended;\n if (this.interactive) return ask();\n if (fallback !== undefined) return fallback;\n this.require(option);\n return undefined;\n }\n\n require(option: string): void {\n this.missing.add(option);\n }\n\n reject(problem: string): void {\n this.invalid.push(problem);\n }\n\n /** Stops before any change when an answer is missing or invalid. */\n assertResolved(): void {\n if (this.missing.size === 0 && this.invalid.length === 0) return;\n const missingOptions = [...this.missing];\n throw new OnboardingError(\n createDiagnosticMessage({\n source: 'gt',\n severity: 'Error',\n whatHappened:\n missingOptions.length > 0\n ? `Setup needs these options: ${missingOptions.join(', ')}`\n : 'Setup received invalid options',\n reassurance: 'No project files were changed',\n details: this.invalid,\n fix: 'Pass the options (see --help), add --defaults to accept the recommended local choices, or rerun in an interactive terminal',\n }),\n missingOptions\n );\n }\n\n step(name: string): void {\n this.completedSteps.push(name);\n }\n\n emit(event: OnboardingEvent): void {\n if (!this.json) return;\n if (event.type === 'result') this.reported = true;\n // Synchronous so events survive an immediate process.exit.\n fs.writeSync(process.stdout.fd, `${JSON.stringify(event)}\\n`);\n }\n\n /** A result for exits that bypass runOnboarding (e.g. settings validation). */\n reportUnexpectedExit(code: number): void {\n if (this.reported || code === 0) return;\n this.emit({\n type: 'result',\n command: this.command,\n outcome: 'failed',\n completedSteps: this.completedSteps,\n error: stripAnsi(\n getLastExitError() ?? 'Setup exited before it finished; see stderr'\n ),\n });\n }\n}\n\nexport type OnboardingOutcome =\n | { outcome: 'success' }\n | { outcome: 'needs_human_action'; url: string };\n\nfunction partialSetupWarning(session: OnboardingSession): string {\n return createDiagnosticMessage({\n source: 'gt',\n severity: 'Warning',\n whatHappened: `Setup stopped after these steps: ${session.completedSteps.join(', ')}`,\n why: 'the error below happened before the remaining steps ran',\n fix: `Review those changes, fix the error, then rerun \\`gt ${session.command}\\`; it reuses the saved configuration and credentials`,\n });\n}\n\n/**\n * Runs one setup command: selects prompt and output modes, then reports the\n * outcome. Failures exit nonzero with the steps that already ran.\n */\nexport async function runOnboarding(\n command: string,\n options: Pick<ConfigureOptions, 'json' | 'interactive'>,\n run: (session: OnboardingSession) => Promise<OnboardingOutcome>\n): Promise<void> {\n commandBeforeOnboarding = undefined;\n process.removeListener('exit', reportExitBeforeOnboarding);\n const session = new OnboardingSession(command, options);\n if (session.json) logger.setConsoleOutput('stderr');\n // Per-run modes; console routing is reset per command by BaseCLI.\n const progressWasAnimated = logger.setAnimatedProgress(session.interactive);\n const reportExit = (code: number) => session.reportUnexpectedExit(code);\n process.once('exit', reportExit);\n try {\n const result = await run(session);\n const needsHuman =\n result.outcome === 'needs_human_action' ||\n session.humanActions.length > 0;\n session.emit({\n type: 'result',\n command,\n outcome: needsHuman ? 'needs_human_action' : 'success',\n completedSteps: session.completedSteps,\n ...(result.outcome === 'needs_human_action' && { url: result.url }),\n ...(session.humanActions.length > 0 && {\n actions: session.humanActions,\n }),\n });\n } catch (error) {\n const message =\n error instanceof Error\n ? error.message\n : (formatDiagnosticErrorDetails(error) ?? 'Setup failed');\n session.emit({\n type: 'result',\n command,\n outcome: 'failed',\n completedSteps: session.completedSteps,\n error: stripAnsi(message),\n ...(error instanceof OnboardingError &&\n error.missingOptions.length > 0 && {\n missingOptions: error.missingOptions,\n }),\n });\n if (session.completedSteps.length > 0) {\n logger.warn(partialSetupWarning(session));\n }\n return logErrorAndExit(message);\n } finally {\n process.removeListener('exit', reportExit);\n logger.setAnimatedProgress(progressWasAnimated);\n }\n}\n\nexport function asRecord(value: unknown): Record<string, unknown> | undefined {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n ? (value as Record<string, unknown>)\n : undefined;\n}\n\n/** Reads the setup config, failing before any change when it is unusable. */\nexport function readSetupConfig(\n configFilepath: string\n): Record<string, unknown> {\n if (!fs.existsSync(configFilepath)) return {};\n try {\n const config = asRecord(\n JSON.parse(fs.readFileSync(configFilepath, 'utf8'))\n );\n if (config) return config;\n throw new Error('the file does not contain a JSON object');\n } catch (error) {\n throw new OnboardingError(\n createDiagnosticMessage({\n source: 'gt',\n severity: 'Error',\n whatHappened: `${configFilepath} is not a valid JSON config`,\n reassurance: 'No project files were changed',\n details: formatDiagnosticErrorDetails(error),\n fix: 'Fix or remove the file, then rerun the command',\n })\n );\n }\n}\n\nexport const INIT_SOURCE_HELP =\n \"Space-separated list of glob patterns containing the app's source code, by default 'src/**/*.{js,jsx,ts,tsx}' 'app/**/*.{js,jsx,ts,tsx}' 'pages/**/*.{js,jsx,ts,tsx}' 'components/**/*.{js,jsx,ts,tsx}'\";\n\nexport function setupConfigPath(\n options: Pick<ConfigureOptions, 'config'>\n): string {\n return options.config ? withJsonExtension(options.config) : 'gt.config.json';\n}\n\nexport function getConfiguredFramework(\n config: Record<string, unknown>\n): SupportedReactFrameworks | 'mintlify' | undefined {\n const framework = config.framework;\n return typeof framework === 'string' &&\n [...SUPPORTED_REACT_FRAMEWORKS, 'mintlify'].includes(\n framework as SupportedReactFrameworks\n )\n ? (framework as SupportedReactFrameworks | 'mintlify')\n : undefined;\n}\n\n/** JSON mode keeps the banner off stdout. */\nexport function displaySetupHeader(\n session: OnboardingSession,\n message: string\n) {\n if (session.json) logger.startCommand(message);\n else displayHeader(message);\n}\n\nexport function describeDefaults(\n framework: FrameworkObject | undefined\n): string {\n const buildTool = getBuildToolSetup(framework?.name);\n const translationsDir =\n buildTool?.defaultTranslationsDir ?? DEFAULT_TRANSLATIONS_DIR;\n if (framework?.type !== 'react') {\n return `Files saved locally in ${translationsDir}`;\n }\n const library = getReactFrameworkLibrary(framework);\n const setup = buildTool?.initializer ?? 'GTProvider';\n return `${library} & ${setup}, ${getFrameworkDisplayName(framework)}, Files saved locally in ${translationsDir}`;\n}\n\n/** Setup patterns name where each locale's files live, so they need [locale]. */\nexport function validateSetupPattern(pattern: string): true | string {\n return (\n pattern.includes('[locale]') ||\n `\"${pattern}\" must include [locale], e.g. ./locales/[locale]/*.json`\n );\n}\n\n/** Parses `--file-patterns <format>=<glob>` values, grouped by format. */\nexport function parseFilePatterns(\n session: OnboardingSession,\n values: string[] = []\n): Map<SetupFileFormat, string[]> {\n const patterns = new Map<SetupFileFormat, string[]>();\n for (const value of values) {\n const separator = value.indexOf('=');\n const format = value.slice(0, separator) as SetupFileFormat;\n const pattern = value.slice(separator + 1).trim();\n if (separator < 0 || !SETUP_FILE_FORMATS.includes(format) || !pattern) {\n session.reject(\n `--file-patterns \"${value}\" must look like <format>=<glob> with a format of ${SETUP_FILE_FORMATS.join(', ')}`\n );\n continue;\n }\n const problem = validateSetupPattern(pattern);\n if (problem !== true) {\n session.reject(`--file-patterns \"${value}\": ${problem}`);\n continue;\n }\n patterns.set(format, [...(patterns.get(format) ?? []), pattern]);\n }\n return patterns;\n}\n\n/** Detects the package manager, or asks only when prompts are allowed. */\nexport async function resolvePackageManager(\n session: OnboardingSession,\n specified?: string\n): Promise<PackageManager | undefined> {\n try {\n return await getPackageManager(\n process.cwd(),\n specified,\n !session.interactive\n );\n } catch (error) {\n if (!(error instanceof NoPackageManagerError)) throw error;\n session.require('--package-manager');\n return undefined;\n }\n}\n\nexport async function installWithProgress(\n session: OnboardingSession,\n packageName: string,\n packageManager: PackageManager,\n asDevDependency: boolean\n): Promise<void> {\n const spinner = logger.createSpinner('timer');\n spinner.start(\n `Installing ${packageName}${asDevDependency ? ' as a dev dependency' : ''} with ${packageManager.name}...`\n );\n try {\n await installPackage(packageName, packageManager, asDevDependency);\n } catch (error) {\n spinner.stop(`Could not install ${packageName}.`, 2);\n throw new Error(\n createDiagnosticMessage({\n source: 'gt',\n severity: 'Error',\n whatHappened: `Failed to install ${packageName}`,\n details: formatDiagnosticErrorDetails(error),\n fix: `Install it with \\`${packageManager.name} ${packageManager.installCommand} ${packageName}\\`, then rerun the command`,\n })\n );\n }\n spinner.stop(`Installed ${packageName}.`);\n session.step(`installed ${packageName}`);\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAqEA,SAAgB,qBACd,SACA,YACS;AACT,QAAO,yBAAyB,QAAQ,CACrC,OAAO,oBAAoB,WAAW,CACtC,OACC,uBACA,sDACA,aAAa,CAAC,iBAAiB,CAAC,CACjC,CACA,OACC,oBACA,wGACD,CACA,OACC,UACA,kHACD,CACA,OACC,cACA,6HACD,CACA,OAAO,iBAAiB,wCAAwC,CAChE,OAAO,6BAA6B,0BAA0B,CAC9D,OACC,0BACA,sEACD,CACA,UACC,IAAI,OACF,uBACA,mDACD,CAAC,QAAQ,CAAC,SAAS,MAAM,CAAC,CAC5B,CACA,OACC,6BACA,2CACD,CACA,UACC,IAAI,OACF,+BACA,gDACD,CAAC,QAAQ,CAAC,GAAG,oBAAoB,OAAO,CAAC,CAC3C,CACA,OACC,iCACA,+GACD,CACA,OACC,uBACA,uFACD,CACA,OAAO,0BAA0B,qCAAqC,CACtE,OACC,qBACA,4DACD,CACA,OAAO,wBAAwB,wCAAwC,CACvE,OACC,qBACA,mDACD,CACA,OACC,oBACA,uDACD,CACA,OAAO,iBAAiB,0CAA0C,CAClE,OAAO,yBAAyB,4BAA4B,CAC5D,UACC,IAAI,OACF,0BACA,0DACD,CAAC,QAAQ,gBAAgB,KAAK,mBAAmB,eAAe,GAAG,CAAC,CACtE;;AAGL,IAAI;AAEJ,SAAS,2BAA2B,MAAoB;AACtD,KAAI,SAAS,KAAK,4BAA4B,KAAA,EAAW;AACzD,IAAG,UACD,QAAQ,OAAO,IACf,GAAG,KAAK,UAAU;EAChB,MAAM;EACN,SAAS;EACT,SAAS;EACT,gBAAgB,EAAE;EAClB,OAAO,UACL,kBAAkB,IAAI,6CACvB;EAC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nimport { Command, Option, type CommanderError } from 'commander';\nimport {\n createDiagnosticMessage,\n formatDiagnosticErrorDetails,\n} from 'generaltranslation/internal';\nimport findFilepath from '../fs/findFilepath.js';\nimport { withJsonExtension } from '../fs/config/loadConfig.js';\nimport { logger } from '../console/logger.js';\nimport {\n displayHeader,\n getLastExitError,\n logErrorAndExit,\n stripAnsi,\n} from '../console/logging.js';\nimport {\n SUPPORTED_REACT_FRAMEWORKS,\n type FrameworkObject,\n type SupportedReactFrameworks,\n} from '../types/index.js';\nimport { DEFAULT_TRANSLATIONS_DIR } from '../utils/constants.js';\nimport { getBuildToolSetup } from './buildTools/index.js';\nimport {\n getFrameworkDisplayName,\n getReactFrameworkLibrary,\n} from './frameworkUtils.js';\nimport {\n SETUP_FILE_FORMATS,\n type SetupFileFormat,\n} from '../formats/files/supportedFiles.js';\nimport {\n getPackageManager,\n NoPackageManagerError,\n packageManagers,\n type PackageManager,\n} from '../utils/packageManager.js';\nimport { installPackage } from '../utils/installPackage.js';\n\n/** Answers accepted by `gt configure` (and the gt-vue `gt init`). */\nexport type ConfigureOptions = {\n config: string;\n src?: string[];\n interactive?: boolean;\n json?: boolean;\n defaults?: boolean;\n defaultLocale?: string;\n locales?: string[];\n storage?: 'local' | 'cdn';\n translationsDir?: string;\n fileFormats?: Array<SetupFileFormat | 'none'>;\n filePatterns?: string[];\n liveTranslations?: boolean;\n devCredentials?: boolean;\n projectId?: string;\n createProject?: boolean;\n orgId?: string;\n projectName?: string;\n packageManager?: string;\n};\n\n/** Answers accepted by the React-aware `gt init`. */\nexport type InitOptions = ConfigureOptions & {\n locadex?: boolean;\n reactSetup?: boolean;\n framework?: SupportedReactFrameworks;\n format?: boolean;\n};\n\n/** Flags for every configuration question; values prefill interactive runs. */\nexport function attachConfigureFlags(\n command: Command,\n sourceHelp: string\n): Command {\n return reportJsonArgumentErrors(command)\n .option('--src <paths...>', sourceHelp)\n .option(\n '-c, --config <path>',\n 'Filepath to config file, by default gt.config.json',\n findFilepath(['gt.config.json'])\n )\n .option(\n '--no-interactive',\n 'Never prompt; fail listing the options still needed. Automatic when stdin or stdout is not a terminal'\n )\n .option(\n '--json',\n 'Write JSON events (sign-in, handoff, result) to stdout and all other output to stderr; implies --no-interactive'\n )\n .option(\n '--defaults',\n 'Accept the recommended value for every local choice that no flag or gt.config.json answers; never creates projects or keys'\n )\n .option('--no-defaults', 'Do not offer the recommended defaults')\n .option('--default-locale <locale>', 'Default locale, e.g. en')\n .option(\n '--locales <locales...>',\n 'Locales to translate into, e.g. fr es; replaces the configured list'\n )\n .addOption(\n new Option(\n '--storage <storage>',\n 'Where GT translations are stored for GT runtimes'\n ).choices(['local', 'cdn'])\n )\n .option(\n '--translations-dir <path>',\n 'Directory for local GT translation files'\n )\n .addOption(\n new Option(\n '--file-formats <formats...>',\n 'Additional file formats to translate, or none'\n ).choices([...SETUP_FILE_FORMATS, 'none'])\n )\n .option(\n '--file-patterns <patterns...>',\n 'Glob patterns as <format>=<glob> including [locale], e.g. json=./locales/[locale]/*.json; selects the format'\n )\n .option(\n '--live-translations',\n 'Local Vite storage: set up live development translations (creates a development key)'\n )\n .option('--no-live-translations', 'Skip live development translations')\n .addOption(\n new Option(\n '--dev-credentials',\n 'Save a project ID and a new development key to .env.local'\n ).conflicts('liveTranslations')\n )\n .option('--no-dev-credentials', 'Do not create development credentials')\n .option(\n '--project-id <id>',\n 'Existing project for the development credentials'\n )\n .option(\n '--create-project',\n 'Create a new project for the development credentials'\n )\n .option('--org-id <id>', 'Organization that owns --create-project')\n .option('--project-name <name>', 'Name for --create-project')\n .addOption(\n new Option(\n '--package-manager <id>',\n 'Package manager for installs when it cannot be detected'\n ).choices(packageManagers.map((packageManager) => packageManager.id))\n );\n}\n\nlet commandBeforeOnboarding: string | undefined;\n\nfunction reportExitBeforeOnboarding(code: number): void {\n if (code === 0 || commandBeforeOnboarding === undefined) return;\n fs.writeSync(\n process.stdout.fd,\n `${JSON.stringify({\n type: 'result',\n command: commandBeforeOnboarding,\n outcome: 'failed',\n completedSteps: [],\n error: stripAnsi(\n getLastExitError() ?? 'Setup exited before it started; see stderr'\n ),\n } satisfies OnboardingEvent)}\\n`\n );\n}\n\n/**\n * Pre-action hooks, such as the monorepo version check, can exit before\n * runOnboarding installs its own result reporting; `--json` callers still\n * get a result. runOnboarding takes over once it starts.\n */\nexport function reportJsonExitsBeforeOnboarding(command: string): void {\n commandBeforeOnboarding = command;\n process.once('exit', reportExitBeforeOnboarding);\n}\n\n/**\n * Argument errors happen before the action runs, so `--json` callers would\n * otherwise get no result. Commander prints the error to stderr, then calls\n * this exit hook; returning lets it exit with the same code as before. The\n * hook replaces an exit override inherited from the program.\n */\nfunction reportJsonArgumentErrors(command: Command): Command {\n return command.exitOverride((error: CommanderError) => {\n if (error.exitCode === 0) return; // help and version output\n // An option after the failing argument is not parsed yet.\n const json =\n command.opts().json === true || process.argv.includes('--json');\n if (!json) return;\n fs.writeSync(\n process.stdout.fd,\n `${JSON.stringify({\n type: 'result',\n command: command.name(),\n outcome: 'failed',\n completedSteps: [],\n error: stripAnsi(error.message),\n } satisfies OnboardingEvent)}\\n`\n );\n });\n}\n\n/** Configuration flags plus the React application setup and Locadex choices. */\nexport function attachInitFlags(command: Command, sourceHelp: string) {\n return attachConfigureFlags(command, sourceHelp)\n .option(\n '--locadex',\n 'Mintlify and Next.js App Router: hand setup to the Locadex AI agent through GitHub instead'\n )\n .option('--no-locadex', 'Set up this project locally')\n .option(\n '--react-setup',\n 'React projects: install the GT library and add GTProvider or initializeGTSPA'\n )\n .option('--no-react-setup', 'Do not modify application source')\n .addOption(\n new Option(\n '--framework <framework>',\n 'React framework for --react-setup; overrides detection'\n ).choices(SUPPORTED_REACT_FRAMEWORKS)\n )\n .option(\n '--format',\n 'Next.js App Router: format files changed by setup with the detected formatter'\n )\n .option('--no-format', 'Leave files changed by setup unformatted');\n}\n\nexport type OnboardingEvent =\n | {\n type: 'authorization_required';\n verificationUri: string;\n verificationUriComplete?: string;\n userCode: string;\n }\n | { type: 'handoff'; url: string; reason: 'locadex' }\n | {\n type: 'result';\n command: string;\n outcome: 'success' | 'needs_human_action' | 'failed';\n completedSteps: string[];\n url?: string;\n /** Manual steps setup could not do, for needs_human_action. */\n actions?: string[];\n missingOptions?: string[];\n error?: string;\n };\n\n/** Needs-input and validation failures, raised before setup changes files. */\nexport class OnboardingError extends Error {\n constructor(\n message: string,\n readonly missingOptions: string[] = []\n ) {\n super(message);\n this.name = 'OnboardingError';\n }\n}\n\nfunction isInteractiveTerminal(): boolean {\n return process.stdin.isTTY === true && process.stdout.isTTY === true;\n}\n\n/**\n * One setup run: how unanswered questions are resolved, which options are\n * still missing, and which steps already changed the project.\n */\nexport class OnboardingSession {\n readonly interactive: boolean;\n readonly json: boolean;\n defaults = false;\n readonly completedSteps: string[] = [];\n /** Manual steps left for a person; they make the outcome needs_human_action. */\n readonly humanActions: string[] = [];\n private readonly missing = new Set<string>();\n private readonly invalid: string[] = [];\n private reported = false;\n\n constructor(\n readonly command: string,\n options: Pick<ConfigureOptions, 'json' | 'interactive'>\n ) {\n this.json = options.json === true;\n this.interactive =\n options.interactive !== false && !this.json && isInteractiveTerminal();\n }\n\n /**\n * Explicit flag, then existing config, then the recommended value when\n * defaults were accepted, then a prompt. Noninteractive runs use the\n * fallback of an optional question, or record the option as missing.\n */\n async answer<T>(\n option: string,\n {\n explicit,\n configured,\n recommended,\n fallback,\n ask,\n }: {\n explicit?: T;\n configured?: T;\n recommended?: T;\n fallback?: T;\n ask: () => Promise<T>;\n }\n ): Promise<T | undefined> {\n if (explicit !== undefined) return explicit;\n if (configured !== undefined) return configured;\n if (this.defaults && recommended !== undefined) return recommended;\n if (this.interactive) return ask();\n if (fallback !== undefined) return fallback;\n this.require(option);\n return undefined;\n }\n\n require(option: string): void {\n this.missing.add(option);\n }\n\n reject(problem: string): void {\n this.invalid.push(problem);\n }\n\n /** Stops before any change when an answer is missing or invalid. */\n assertResolved(): void {\n if (this.missing.size === 0 && this.invalid.length === 0) return;\n const missingOptions = [...this.missing];\n throw new OnboardingError(\n createDiagnosticMessage({\n source: 'gt',\n severity: 'Error',\n whatHappened:\n missingOptions.length > 0\n ? `Setup needs these options: ${missingOptions.join(', ')}`\n : 'Setup received invalid options',\n reassurance: 'No project files were changed',\n details: this.invalid,\n fix: this.defaults\n ? 'Pass the options (see --help), or rerun in an interactive terminal'\n : 'Pass the options (see --help), add --defaults to accept the recommended local choices, or rerun in an interactive terminal',\n }),\n missingOptions\n );\n }\n\n step(name: string): void {\n this.completedSteps.push(name);\n }\n\n emit(event: OnboardingEvent): void {\n if (!this.json) return;\n if (event.type === 'result') this.reported = true;\n // Synchronous so events survive an immediate process.exit.\n fs.writeSync(process.stdout.fd, `${JSON.stringify(event)}\\n`);\n }\n\n /** A result for exits that bypass runOnboarding (e.g. settings validation). */\n reportUnexpectedExit(code: number): void {\n if (this.reported || code === 0) return;\n this.emit({\n type: 'result',\n command: this.command,\n outcome: 'failed',\n completedSteps: this.completedSteps,\n error: stripAnsi(\n getLastExitError() ?? 'Setup exited before it finished; see stderr'\n ),\n });\n }\n}\n\nexport type OnboardingOutcome =\n | { outcome: 'success' }\n | { outcome: 'needs_human_action'; url: string };\n\nfunction partialSetupWarning(session: OnboardingSession): string {\n return createDiagnosticMessage({\n source: 'gt',\n severity: 'Warning',\n whatHappened: `Setup stopped after these steps: ${session.completedSteps.join(', ')}`,\n why: 'the error below happened before the remaining steps ran',\n fix: `Review those changes, fix the error, then rerun \\`gt ${session.command}\\`; it reuses the saved configuration and credentials`,\n });\n}\n\n/**\n * Runs one setup command: selects prompt and output modes, then reports the\n * outcome. Failures exit nonzero with the steps that already ran.\n */\nexport async function runOnboarding(\n command: string,\n options: Pick<ConfigureOptions, 'json' | 'interactive'>,\n run: (session: OnboardingSession) => Promise<OnboardingOutcome>\n): Promise<void> {\n commandBeforeOnboarding = undefined;\n process.removeListener('exit', reportExitBeforeOnboarding);\n const session = new OnboardingSession(command, options);\n if (session.json) logger.setConsoleOutput('stderr');\n // Per-run modes; console routing is reset per command by BaseCLI.\n const progressWasAnimated = logger.setAnimatedProgress(session.interactive);\n const reportExit = (code: number) => session.reportUnexpectedExit(code);\n process.once('exit', reportExit);\n try {\n const result = await run(session);\n const needsHuman =\n result.outcome === 'needs_human_action' ||\n session.humanActions.length > 0;\n session.emit({\n type: 'result',\n command,\n outcome: needsHuman ? 'needs_human_action' : 'success',\n completedSteps: session.completedSteps,\n ...(result.outcome === 'needs_human_action' && { url: result.url }),\n ...(session.humanActions.length > 0 && {\n actions: session.humanActions,\n }),\n });\n } catch (error) {\n const message =\n error instanceof Error\n ? error.message\n : (formatDiagnosticErrorDetails(error) ?? 'Setup failed');\n session.emit({\n type: 'result',\n command,\n outcome: 'failed',\n completedSteps: session.completedSteps,\n error: stripAnsi(message),\n ...(error instanceof OnboardingError &&\n error.missingOptions.length > 0 && {\n missingOptions: error.missingOptions,\n }),\n });\n if (session.completedSteps.length > 0) {\n logger.warn(partialSetupWarning(session));\n }\n return logErrorAndExit(message);\n } finally {\n process.removeListener('exit', reportExit);\n logger.setAnimatedProgress(progressWasAnimated);\n }\n}\n\nexport function asRecord(value: unknown): Record<string, unknown> | undefined {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n ? (value as Record<string, unknown>)\n : undefined;\n}\n\n/** Reads the setup config, failing before any change when it is unusable. */\nexport function readSetupConfig(\n configFilepath: string\n): Record<string, unknown> {\n if (!fs.existsSync(configFilepath)) return {};\n try {\n const config = asRecord(\n JSON.parse(fs.readFileSync(configFilepath, 'utf8'))\n );\n if (config) return config;\n throw new Error('the file does not contain a JSON object');\n } catch (error) {\n throw new OnboardingError(\n createDiagnosticMessage({\n source: 'gt',\n severity: 'Error',\n whatHappened: `${configFilepath} is not a valid JSON config`,\n reassurance: 'No project files were changed',\n details: formatDiagnosticErrorDetails(error),\n fix: 'Fix or remove the file, then rerun the command',\n })\n );\n }\n}\n\nexport const INIT_SOURCE_HELP =\n \"Space-separated list of glob patterns containing the app's source code, by default 'src/**/*.{js,jsx,ts,tsx}' 'app/**/*.{js,jsx,ts,tsx}' 'pages/**/*.{js,jsx,ts,tsx}' 'components/**/*.{js,jsx,ts,tsx}'\";\n\nexport function setupConfigPath(\n options: Pick<ConfigureOptions, 'config'>\n): string {\n return options.config ? withJsonExtension(options.config) : 'gt.config.json';\n}\n\nexport function getConfiguredFramework(\n config: Record<string, unknown>\n): SupportedReactFrameworks | 'mintlify' | undefined {\n const framework = config.framework;\n return typeof framework === 'string' &&\n [...SUPPORTED_REACT_FRAMEWORKS, 'mintlify'].includes(\n framework as SupportedReactFrameworks\n )\n ? (framework as SupportedReactFrameworks | 'mintlify')\n : undefined;\n}\n\n/** JSON mode keeps the banner off stdout. */\nexport function displaySetupHeader(\n session: OnboardingSession,\n message: string\n) {\n if (session.json) logger.startCommand(message);\n else displayHeader(message);\n}\n\nexport function describeDefaults(\n framework: FrameworkObject | undefined\n): string {\n const buildTool = getBuildToolSetup(framework?.name);\n const translationsDir =\n buildTool?.defaultTranslationsDir ?? DEFAULT_TRANSLATIONS_DIR;\n if (framework?.type !== 'react') {\n return `Files saved locally in ${translationsDir}`;\n }\n const library = getReactFrameworkLibrary(framework);\n const setup = buildTool?.initializer ?? 'GTProvider';\n return `${library} & ${setup}, ${getFrameworkDisplayName(framework)}, Files saved locally in ${translationsDir}`;\n}\n\n/** Setup patterns name where each locale's files live, so they need [locale]. */\nexport function validateSetupPattern(pattern: string): true | string {\n return (\n pattern.includes('[locale]') ||\n `\"${pattern}\" must include [locale], e.g. ./locales/[locale]/*.json`\n );\n}\n\n/** Parses `--file-patterns <format>=<glob>` values, grouped by format. */\nexport function parseFilePatterns(\n session: OnboardingSession,\n values: string[] = []\n): Map<SetupFileFormat, string[]> {\n const patterns = new Map<SetupFileFormat, string[]>();\n for (const value of values) {\n const separator = value.indexOf('=');\n const format = value.slice(0, separator) as SetupFileFormat;\n const pattern = value.slice(separator + 1).trim();\n if (separator < 0 || !SETUP_FILE_FORMATS.includes(format) || !pattern) {\n session.reject(\n `--file-patterns \"${value}\" must look like <format>=<glob> with a format of ${SETUP_FILE_FORMATS.join(', ')}`\n );\n continue;\n }\n const problem = validateSetupPattern(pattern);\n if (problem !== true) {\n session.reject(`--file-patterns \"${value}\": ${problem}`);\n continue;\n }\n patterns.set(format, [...(patterns.get(format) ?? []), pattern]);\n }\n return patterns;\n}\n\n/** Detects the package manager, or asks only when prompts are allowed. */\nexport async function resolvePackageManager(\n session: OnboardingSession,\n specified?: string\n): Promise<PackageManager | undefined> {\n try {\n return await getPackageManager(\n process.cwd(),\n specified,\n !session.interactive\n );\n } catch (error) {\n if (!(error instanceof NoPackageManagerError)) throw error;\n session.require('--package-manager');\n return undefined;\n }\n}\n\nexport async function installWithProgress(\n session: OnboardingSession,\n packageName: string,\n packageManager: PackageManager,\n asDevDependency: boolean\n): Promise<void> {\n const spinner = logger.createSpinner('timer');\n spinner.start(\n `Installing ${packageName}${asDevDependency ? ' as a dev dependency' : ''} with ${packageManager.name}...`\n );\n try {\n await installPackage(packageName, packageManager, asDevDependency);\n } catch (error) {\n spinner.stop(`Could not install ${packageName}.`, 2);\n throw new Error(\n createDiagnosticMessage({\n source: 'gt',\n severity: 'Error',\n whatHappened: `Failed to install ${packageName}`,\n details: formatDiagnosticErrorDetails(error),\n fix: `Install it with \\`${packageManager.name} ${packageManager.installCommand} ${packageName}\\`, then rerun the command`,\n })\n );\n }\n spinner.stop(`Installed ${packageName}.`);\n session.step(`installed ${packageName}`);\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAqEA,SAAgB,qBACd,SACA,YACS;AACT,QAAO,yBAAyB,QAAQ,CACrC,OAAO,oBAAoB,WAAW,CACtC,OACC,uBACA,sDACA,aAAa,CAAC,iBAAiB,CAAC,CACjC,CACA,OACC,oBACA,wGACD,CACA,OACC,UACA,kHACD,CACA,OACC,cACA,6HACD,CACA,OAAO,iBAAiB,wCAAwC,CAChE,OAAO,6BAA6B,0BAA0B,CAC9D,OACC,0BACA,sEACD,CACA,UACC,IAAI,OACF,uB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AAI;AACF,SAAO,MAAM,kBACX,QAAQ,KAAK,EACb,WACA,CAAC,QAAQ,YACV;UACM,OAAO;AACd,MAAI,EAAE,iBAAiB,uBAAwB,OAAM;AACrD,UAAQ,QAAQ,oBAAoB;AACpC;;;AAIJ,eAAsB,oBACpB,SACA,aACA,gBACA,iBACe;CACf,MAAM,UAAU,OAAO,cAAc,QAAQ;AAC7C,SAAQ,MACN,cAAc,cAAc,kBAAkB,yBAAyB,GAAG,QAAQ,eAAe,KAAK,KACvG;AACD,KAAI;AACF,QAAM,eAAe,aAAa,gBAAgB,gBAAgB;UAC3D,OAAO;AACd,UAAQ,KAAK,qBAAqB,YAAY,IAAI,EAAE;AACpD,QAAM,IAAI,MACR,wBAAwB;GACtB,QAAQ;GACR,UAAU;GACV,cAAc,qBAAqB;GACnC,SAAS,6BAA6B,MAAM;GAC5C,KAAK,qBAAqB,eAAe,KAAK,GAAG,eAAe,eAAe,GAAG,YAAY;GAC/F,CAAC,CACH;;AAEH,SAAQ,KAAK,aAAa,YAAY,GAAG;AACzC,SAAQ,KAAK,aAAa,cAAc"}
|
|
@@ -6,6 +6,12 @@ type SetupViteSPAOptions = {
|
|
|
6
6
|
translationsDir?: string;
|
|
7
7
|
previousTranslationsDir?: string;
|
|
8
8
|
};
|
|
9
|
+
/**
|
|
10
|
+
* Top-level statements, or undefined for syntax this inspector cannot parse
|
|
11
|
+
* but Vite may accept, such as decorators.
|
|
12
|
+
*/
|
|
13
|
+
export declare function parseModule(content: string, filename: string): import("@babel/types").Statement[] | undefined;
|
|
14
|
+
export declare function toRelativeImport(fromDirectory: string, toPath: string): string;
|
|
9
15
|
/**
|
|
10
16
|
* Reads the Vite entry and bootstrap without writing, so setup can report an
|
|
11
17
|
* unsupported layout before changing any file.
|
|
@@ -22,7 +28,7 @@ export declare function inspectViteSPA(appDirectory: string): Promise<{
|
|
|
22
28
|
bootstrapPath: string;
|
|
23
29
|
entryImport: string;
|
|
24
30
|
}>;
|
|
25
|
-
export type ViteLoaderResult = '
|
|
31
|
+
export type ViteLoaderResult = 'created' | 'updated' | 'unchanged' | 'custom' | 'missing';
|
|
26
32
|
/**
|
|
27
33
|
* Points the generated src/loadTranslations.ts at translationsDir and adds
|
|
28
34
|
* empty locale stubs. Only a template matching the previous config is
|
|
@@ -33,6 +39,9 @@ export declare function writeViteLoader({ appDirectory, defaultLocale, locales,
|
|
|
33
39
|
translationsDir: string;
|
|
34
40
|
create: boolean;
|
|
35
41
|
}): Promise<ViteLoaderResult>;
|
|
42
|
+
export type ViteLoaderExport = 'default' | 'loadTranslations' | undefined;
|
|
43
|
+
/** The generated loader's export, or a custom loader's own if it has one. */
|
|
44
|
+
export declare function getViteLoaderExport(appDirectory: string, loader: ViteLoaderResult): Promise<ViteLoaderExport>;
|
|
36
45
|
export declare function setupViteSPA({ appDirectory, configFilepath, defaultLocale, locales, translationsDir, previousTranslationsDir, }: SetupViteSPAOptions): Promise<{
|
|
37
46
|
loader?: ViteLoaderResult;
|
|
38
47
|
manualAction?: string;
|
|
@@ -71,6 +71,14 @@ function getModuleEntry(indexHtml) {
|
|
|
71
71
|
async function inspectViteSPA(appDirectory) {
|
|
72
72
|
const indexHtmlPath = path.join(appDirectory, "index.html");
|
|
73
73
|
const sourceDirectory = path.join(appDirectory, "src");
|
|
74
|
+
if (!fs.existsSync(indexHtmlPath)) throw new Error(createDiagnosticMessage({
|
|
75
|
+
source: "gt",
|
|
76
|
+
severity: "Error",
|
|
77
|
+
whatHappened: "This is not a Vite single-page app",
|
|
78
|
+
why: "index.html was not found",
|
|
79
|
+
reassurance: "Nothing was changed",
|
|
80
|
+
fix: "Rerun `npx gt@latest init` with `--framework` set to your framework, or set up GT manually"
|
|
81
|
+
}));
|
|
74
82
|
const indexHtml = await fs.promises.readFile(indexHtmlPath, "utf8");
|
|
75
83
|
const { script, source } = getModuleEntry(indexHtml);
|
|
76
84
|
const declaredEntryPath = getEntryPath(appDirectory, source);
|
|
@@ -133,8 +141,13 @@ async function writeViteLoader({ appDirectory, defaultLocale, locales, translati
|
|
|
133
141
|
if (!fs.existsSync(stubPath)) await fs.promises.writeFile(stubPath, "{}\n");
|
|
134
142
|
}
|
|
135
143
|
if (custom) return "custom";
|
|
144
|
+
if (existingLoader === content) return "unchanged";
|
|
136
145
|
await fs.promises.writeFile(loaderPath, content);
|
|
137
|
-
return "
|
|
146
|
+
return existingLoader === void 0 ? "created" : "updated";
|
|
147
|
+
}
|
|
148
|
+
/** The generated loader's export, or a custom loader's own if it has one. */
|
|
149
|
+
async function getViteLoaderExport(appDirectory, loader) {
|
|
150
|
+
return loader === "custom" ? getLoaderExport(await fs.promises.readFile(path.join(appDirectory, "src", "loadTranslations.ts"), "utf8")) : "default";
|
|
138
151
|
}
|
|
139
152
|
function getLoaderExport(content) {
|
|
140
153
|
const statements = parseModule(content, "loadTranslations.ts");
|
|
@@ -169,7 +182,7 @@ async function setupViteSPA({ appDirectory, configFilepath, defaultLocale, local
|
|
|
169
182
|
previousTranslationsDir,
|
|
170
183
|
create: true
|
|
171
184
|
});
|
|
172
|
-
const loaderExport =
|
|
185
|
+
const loaderExport = await getViteLoaderExport(appDirectory, loader);
|
|
173
186
|
if (!loaderExport) return {
|
|
174
187
|
loader,
|
|
175
188
|
manualAction: `Update your custom src/loadTranslations.ts to load translations from ${translationsDir} and export a default or named loadTranslations function, then rerun gt init`
|
|
@@ -196,6 +209,6 @@ await import('${entryImport}');
|
|
|
196
209
|
};
|
|
197
210
|
}
|
|
198
211
|
//#endregion
|
|
199
|
-
export { inspectViteSPA, setupViteSPA, writeViteLoader };
|
|
212
|
+
export { getViteLoaderExport, inspectViteSPA, parseModule, setupViteSPA, toRelativeImport, writeViteLoader };
|
|
200
213
|
|
|
201
214
|
//# sourceMappingURL=setupViteSPA.js.map
|