gt 2.25.1 → 2.25.2
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 +14 -0
- package/dist/auth/callbackPage.d.ts +15 -1
- package/dist/auth/callbackPage.js +141 -41
- package/dist/auth/callbackPage.js.map +1 -1
- package/dist/auth/loopback.d.ts +36 -2
- package/dist/auth/loopback.js +79 -24
- package/dist/auth/loopback.js.map +1 -1
- package/dist/auth/oauth.d.ts +2 -0
- package/dist/auth/oauth.js +57 -7
- package/dist/auth/oauth.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/setup/buildTools/{tanstackStart → shared}/edits.js +1 -1
- package/dist/setup/buildTools/shared/edits.js.map +1 -0
- package/dist/setup/buildTools/shared/jsx.d.ts +4 -0
- package/dist/setup/buildTools/shared/jsx.js +19 -0
- package/dist/setup/buildTools/shared/jsx.js.map +1 -0
- package/dist/setup/buildTools/shared/source.d.ts +12 -0
- package/dist/setup/buildTools/shared/source.js +40 -0
- package/dist/setup/buildTools/shared/source.js.map +1 -0
- package/dist/setup/buildTools/tanstackStart/index.js +5 -3
- package/dist/setup/buildTools/tanstackStart/index.js.map +1 -1
- package/dist/setup/buildTools/tanstackStart/middleware.d.ts +1 -1
- package/dist/setup/buildTools/tanstackStart/middleware.js +3 -2
- package/dist/setup/buildTools/tanstackStart/middleware.js.map +1 -1
- package/dist/setup/buildTools/tanstackStart/root.d.ts +1 -2
- package/dist/setup/buildTools/tanstackStart/root.js +5 -16
- package/dist/setup/buildTools/tanstackStart/root.js.map +1 -1
- package/dist/setup/buildTools/tanstackStart/router.d.ts +2 -2
- package/dist/setup/buildTools/tanstackStart/router.js +3 -2
- package/dist/setup/buildTools/tanstackStart/router.js.map +1 -1
- package/dist/setup/buildTools/tanstackStart/source.d.ts +3 -15
- package/dist/setup/buildTools/tanstackStart/source.js +2 -37
- package/dist/setup/buildTools/tanstackStart/source.js.map +1 -1
- package/dist/setup/setupViteSPA.d.ts +7 -6
- package/dist/setup/setupViteSPA.js +13 -12
- package/dist/setup/setupViteSPA.js.map +1 -1
- package/package.json +5 -5
- package/dist/auth/loopback.test.d.ts +0 -1
- package/dist/setup/buildTools/tanstackStart/edits.js.map +0 -1
- /package/dist/setup/buildTools/{tanstackStart → shared}/edits.d.ts +0 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"root.js","names":[],"sources":["../../../../src/setup/buildTools/tanstackStart/root.ts"],"sourcesContent":["// src/routes/__root.tsx: recognizing and configuring the root route.\nimport * as t from '@babel/types';\nimport { Libraries } from '../../../types/libraries.js';\nimport {\n applyEdits,\n getCodeStyle,\n getImportEdit,\n getLineIndent,\n getOwnLineIndent,\n} from './edits.js';\nimport { DOCS_URL, getPropertyName, type SourceFile } from './source.js';\n\nfunction isJsxElementNamed(node: t.Node, name: string): node is t.JSXElement {\n return (\n node.type === 'JSXElement' &&\n t.isJSXIdentifier(node.openingElement.name, { name })\n );\n}\n\nfunction isChildrenSlot(node: t.Node): boolean {\n return (\n node.type === 'JSXExpressionContainer' &&\n node.expression.type === 'Identifier' &&\n node.expression.name === 'children'\n );\n}\n\nexport function rendersElement(\n nodes: (t.Node | undefined)[],\n name: string\n): boolean {\n let found = false;\n for (const node of nodes) {\n t.traverseFast(node, (child) => {\n if (isJsxElementNamed(child, name)) found = true;\n });\n }\n return found;\n}\n\nfunction findLocalFunction(statements: t.Statement[], name: string) {\n for (const statement of statements) {\n const declaration =\n statement.type === 'ExportNamedDeclaration'\n ? statement.declaration\n : statement;\n if (\n declaration?.type === 'FunctionDeclaration' &&\n declaration.id?.name === name\n ) {\n return declaration;\n }\n if (declaration?.type !== 'VariableDeclaration') continue;\n if (declaration.kind !== 'const') continue;\n for (const declarator of declaration.declarations) {\n if (\n t.isIdentifier(declarator.id, { name }) &&\n (declarator.init?.type === 'ArrowFunctionExpression' ||\n declarator.init?.type === 'FunctionExpression')\n ) {\n return declarator.init;\n }\n }\n }\n return undefined;\n}\n\nfunction findRootRoute(statements: t.Statement[]) {\n for (const statement of statements) {\n const declaration =\n statement.type === 'ExportNamedDeclaration'\n ? statement.declaration\n : statement;\n if (declaration?.type !== 'VariableDeclaration') continue;\n for (const { id, init } of declaration.declarations) {\n if (\n id.type !== 'Identifier' ||\n init?.type !== 'CallExpression' ||\n init.arguments[0]?.type !== 'ObjectExpression'\n ) {\n continue;\n }\n const { callee } = init;\n // Router context adds a call: createRootRouteWithContext<Ctx>()({...}).\n if (\n (callee.type === 'Identifier' && callee.name === 'createRootRoute') ||\n (callee.type === 'CallExpression' &&\n callee.arguments.length === 0 &&\n callee.callee.type === 'Identifier' &&\n callee.callee.name === 'createRootRouteWithContext')\n ) {\n return { routeName: id.name, options: init.arguments[0] };\n }\n }\n }\n return undefined;\n}\n\ntype LocalFunction = NonNullable<ReturnType<typeof findLocalFunction>>;\n\n/**\n * The local function that renders the document: the route component itself\n * when it renders `<html>`, or the one local component it returns with only\n * the route's slot as its child. A followed document must render nowhere\n * else: another render, such as an errorComponent, has no loader data.\n */\nfunction findDocument(\n statements: t.Statement[],\n component: LocalFunction,\n isShell: boolean\n): LocalFunction | undefined {\n if (rendersElement([component.body], 'html')) return component;\n const { body } = component;\n const returned =\n body.type !== 'BlockStatement'\n ? body\n : body.body.length === 1 && body.body[0].type === 'ReturnStatement'\n ? body.body[0].argument\n : undefined;\n if (\n returned?.type !== 'JSXElement' ||\n returned.openingElement.name.type !== 'JSXIdentifier'\n ) {\n return undefined;\n }\n const children = returned.children.filter(\n (child) => child.type !== 'JSXText' || child.value.trim() !== ''\n );\n if (\n children.length !== 1 ||\n !(isShell\n ? isChildrenSlot(children[0])\n : isJsxElementNamed(children[0], 'Outlet'))\n ) {\n return undefined;\n }\n const { name } = returned.openingElement.name;\n // Its declaration and the route component's element are the only uses.\n let uses = 0;\n for (const statement of statements) {\n t.traverseFast(statement, (node) => {\n if (isJsxElementNamed(node, name) || t.isIdentifier(node, { name })) {\n uses++;\n }\n });\n }\n if (uses !== 2) return undefined;\n const document = findLocalFunction(statements, name);\n return document && rendersElement([document.body], 'html')\n ? document\n : undefined;\n}\n\n/**\n * The root route, the local function its shellComponent or component names,\n * and the local function that renders its document.\n */\nexport function findRootComponent(statements: t.Statement[]) {\n const rootRoute = findRootRoute(statements);\n if (!rootRoute) return undefined;\n const { properties } = rootRoute.options;\n const componentProperty =\n properties.find((p) => getPropertyName(p) === 'shellComponent') ??\n properties.find((p) => getPropertyName(p) === 'component');\n const component =\n componentProperty?.type === 'ObjectProperty' &&\n componentProperty.value.type === 'Identifier'\n ? findLocalFunction(statements, componentProperty.value.name)\n : undefined;\n const isShell =\n componentProperty !== undefined &&\n getPropertyName(componentProperty) === 'shellComponent';\n const document = component && findDocument(statements, component, isShell);\n return { rootRoute, componentProperty, component, isShell, document };\n}\n\n/**\n * Configures the create-start root route: `createRootRoute({...})` (or its\n * router-context form) without a loader, whose shellComponent renders\n * `{children}` (or whose component renders `<Outlet />`) once in the `<body>`\n * of a local `<html>` document, either directly or through one local document\n * component that renders its `{children}` there. Returns undefined for any\n * other shape.\n */\nexport function configureRootRoute({\n content,\n statements,\n}: SourceFile): string | undefined {\n if (!statements) return undefined;\n // Generated bindings must not shadow or collide with the app's own.\n if (/\\b(?:getLocale|getTranslationsSnapshot)\\b/.test(content)) {\n return undefined;\n }\n const found = findRootComponent(statements);\n if (!found) return undefined;\n const { rootRoute, componentProperty, component, isShell, document } = found;\n const { properties } = rootRoute.options;\n if (\n properties.some((property) => {\n const name = getPropertyName(property);\n // A spread or computed key could be any of the options below.\n // A throwing beforeLoad or validateSearch skips the loader, so the\n // shell would render without the locale and translations it reads.\n return (\n name === undefined ||\n name === 'loader' ||\n name === 'beforeLoad' ||\n name === 'validateSearch'\n );\n })\n ) {\n return undefined;\n }\n if (\n componentProperty?.type !== 'ObjectProperty' ||\n !component ||\n document?.body.type !== 'BlockStatement' ||\n [component, document].some((fn) =>\n /\\b(?:locale|translations)\\b/.test(content.slice(fn.start!, fn.end!))\n )\n ) {\n return undefined;\n }\n // A followed document receives the route's slot as its children.\n const slotIsChildren = isShell || document !== component;\n const htmlElements: t.JSXElement[] = [];\n t.traverseFast(document.body, (node) => {\n if (isJsxElementNamed(node, 'html')) htmlElements.push(node);\n });\n if (htmlElements.length !== 1) return undefined;\n const [html] = htmlElements;\n const bodies = html.children.filter((child) =>\n isJsxElementNamed(child, 'body')\n );\n if (bodies.length !== 1) return undefined;\n // Headers, footers and app providers around the slot render GT too, so the\n // provider wraps everything the body renders before <Scripts />.\n const bodyContent = bodies[0].children.filter(\n (child) => child.type !== 'JSXText' || child.value.trim() !== ''\n );\n const scriptsIndex = bodyContent.findIndex((child) =>\n isJsxElementNamed(child, 'Scripts')\n );\n const wrapped =\n scriptsIndex === -1 ? bodyContent : bodyContent.slice(0, scriptsIndex);\n let slots = 0;\n let multilineLiteral = false;\n for (const child of wrapped) {\n t.traverseFast(child, (node) => {\n if (\n slotIsChildren\n ? isChildrenSlot(node)\n : isJsxElementNamed(node, 'Outlet')\n ) {\n slots++;\n }\n if (\n (node.type === 'TemplateLiteral' || node.type === 'StringLiteral') &&\n node.loc!.start.line !== node.loc!.end.line\n ) {\n multilineLiteral = true;\n }\n });\n }\n if (slots !== 1) return undefined;\n const { attributes } = html.openingElement;\n if (attributes.some((attribute) => attribute.type === 'JSXSpreadAttribute')) {\n return undefined;\n }\n const lang = attributes.find(\n (attribute): attribute is t.JSXAttribute =>\n attribute.type === 'JSXAttribute' &&\n t.isJSXIdentifier(attribute.name, { name: 'lang' })\n );\n // A computed lang is the app's own locale logic.\n if (lang && lang.value?.type !== 'StringLiteral') return undefined;\n const propertyIndent = getOwnLineIndent(content, componentProperty.start!);\n if (propertyIndent === undefined) return undefined;\n\n const { quote, semi, eol, indent } = getCodeStyle(content, statements);\n const first = wrapped[0];\n const last = wrapped.at(-1)!;\n const wrappedText = content.slice(first.start!, last.end!);\n const wrappedIndent = getOwnLineIndent(content, first.start!);\n // Reindenting would change the value of a literal that spans lines, such\n // as a template, a backslash-continued string or a JSX attribute string.\n const nestedText = multilineLiteral\n ? wrappedText\n : wrappedText.replace(/\\n(?=[ \\t]*\\S)/g, `\\n${indent}`);\n const provider = '<GTProvider locale={locale} translations={translations}>';\n const firstStatement = document.body.body[0];\n const statementIndent =\n (firstStatement && getOwnLineIndent(content, firstStatement.start!)) ??\n getLineIndent(content, document.start!) + indent;\n return applyEdits(content, [\n getImportEdit(\n statements,\n [\n `import { GTProvider, getLocale, getTranslationsSnapshot } from ${quote}${Libraries.GT_TANSTACK_START}${quote}${semi}`,\n ],\n eol\n ),\n {\n start: componentProperty.start!,\n text: [\n 'loader: async () => {',\n `${propertyIndent}${indent}const locale = getLocale()${semi}`,\n `${propertyIndent}${indent}return { locale, translations: await getTranslationsSnapshot(locale) }${semi}`,\n `${propertyIndent}},`,\n propertyIndent,\n ].join(eol),\n },\n {\n start: document.body.start! + 1,\n text: `${eol}${statementIndent}const { locale, translations } = ${rootRoute.routeName}.useLoaderData()${semi}`,\n },\n lang\n ? { start: lang.start!, end: lang.end!, text: 'lang={locale}' }\n : { start: html.openingElement.name.end!, text: ' lang={locale}' },\n {\n start: first.start!,\n end: last.end!,\n text:\n wrappedIndent === undefined\n ? `${provider}${wrappedText}</GTProvider>`\n : [\n provider,\n `${wrappedIndent}${indent}${nestedText}`,\n `${wrappedIndent}</GTProvider>`,\n ].join(eol),\n },\n ]);\n}\n\nexport function getRootFix(rootPath: string): string {\n return `In ${rootPath}, add loader: async () => { const locale = getLocale(); return { locale, translations: await getTranslationsSnapshot(locale) }; } to the root route options, read const { locale, translations } = Route.useLoaderData() in the document, set <html lang={locale}>, and wrap everything its <body> renders before <Scripts /> in <GTProvider locale={locale} translations={translations}>, importing GTProvider, getLocale and getTranslationsSnapshot from '${Libraries.GT_TANSTACK_START}' (see ${DOCS_URL})`;\n}\n"],"mappings":";;;;;AAYA,SAAS,kBAAkB,MAAc,MAAoC;AAC3E,QAC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AO,kBAAkB;GACzB,MAAM;IACJ;IACA,GAAG,iBAAiB,OAAO,4BAA4B;IACvD,GAAG,iBAAiB,OAAO,wEAAwE;IACnG,GAAG,eAAe;IAClB;IACD,CAAC,KAAK,IAAI;GACZ;EACD;GACE,OAAO,SAAS,KAAK,QAAS;GAC9B,MAAM,GAAG,MAAM,gBAAgB,mCAAmC,UAAU,UAAU,kBAAkB;GACzG;EACD,OACI;GAAE,OAAO,KAAK;GAAQ,KAAK,KAAK;GAAM,MAAM;GAAiB,GAC7D;GAAE,OAAO,KAAK,eAAe,KAAK;GAAM,MAAM;GAAkB;EACpE;GACE,OAAO,MAAM;GACb,KAAK,KAAK;GACV,MACE,kBAAkB,KAAA,IACd,GAAG,WAAW,YAAY,iBAC1B;IACE;IACA,GAAG,gBAAgB,SAAS;IAC5B,GAAG,cAAc;IAClB,CAAC,KAAK,IAAI;GAClB;EACF,CAAC;;AAGJ,SAAgB,WAAW,UAA0B;AACnD,QAAO,MAAM,SAAS,udAAoe,SAAS"}
|
|
1
|
+
{"version":3,"file":"root.js","names":[],"sources":["../../../../src/setup/buildTools/tanstackStart/root.ts"],"sourcesContent":["// src/routes/__root.tsx: recognizing and configuring the root route.\nimport * as t from '@babel/types';\nimport { Libraries } from '../../../types/libraries.js';\nimport {\n applyEdits,\n getCodeStyle,\n getImportEdit,\n getLineIndent,\n getOwnLineIndent,\n} from '../shared/edits.js';\nimport {\n isChildrenSlot,\n isJsxElementNamed,\n rendersElement,\n} from '../shared/jsx.js';\nimport { getPropertyName, type SourceFile } from '../shared/source.js';\nimport { DOCS_URL } from './source.js';\n\nfunction findLocalFunction(statements: t.Statement[], name: string) {\n for (const statement of statements) {\n const declaration =\n statement.type === 'ExportNamedDeclaration'\n ? statement.declaration\n : statement;\n if (\n declaration?.type === 'FunctionDeclaration' &&\n declaration.id?.name === name\n ) {\n return declaration;\n }\n if (declaration?.type !== 'VariableDeclaration') continue;\n if (declaration.kind !== 'const') continue;\n for (const declarator of declaration.declarations) {\n if (\n t.isIdentifier(declarator.id, { name }) &&\n (declarator.init?.type === 'ArrowFunctionExpression' ||\n declarator.init?.type === 'FunctionExpression')\n ) {\n return declarator.init;\n }\n }\n }\n return undefined;\n}\n\nfunction findRootRoute(statements: t.Statement[]) {\n for (const statement of statements) {\n const declaration =\n statement.type === 'ExportNamedDeclaration'\n ? statement.declaration\n : statement;\n if (declaration?.type !== 'VariableDeclaration') continue;\n for (const { id, init } of declaration.declarations) {\n if (\n id.type !== 'Identifier' ||\n init?.type !== 'CallExpression' ||\n init.arguments[0]?.type !== 'ObjectExpression'\n ) {\n continue;\n }\n const { callee } = init;\n // Router context adds a call: createRootRouteWithContext<Ctx>()({...}).\n if (\n (callee.type === 'Identifier' && callee.name === 'createRootRoute') ||\n (callee.type === 'CallExpression' &&\n callee.arguments.length === 0 &&\n callee.callee.type === 'Identifier' &&\n callee.callee.name === 'createRootRouteWithContext')\n ) {\n return { routeName: id.name, options: init.arguments[0] };\n }\n }\n }\n return undefined;\n}\n\ntype LocalFunction = NonNullable<ReturnType<typeof findLocalFunction>>;\n\n/**\n * The local function that renders the document: the route component itself\n * when it renders `<html>`, or the one local component it returns with only\n * the route's slot as its child. A followed document must render nowhere\n * else: another render, such as an errorComponent, has no loader data.\n */\nfunction findDocument(\n statements: t.Statement[],\n component: LocalFunction,\n isShell: boolean\n): LocalFunction | undefined {\n if (rendersElement([component.body], 'html')) return component;\n const { body } = component;\n const returned =\n body.type !== 'BlockStatement'\n ? body\n : body.body.length === 1 && body.body[0].type === 'ReturnStatement'\n ? body.body[0].argument\n : undefined;\n if (\n returned?.type !== 'JSXElement' ||\n returned.openingElement.name.type !== 'JSXIdentifier'\n ) {\n return undefined;\n }\n const children = returned.children.filter(\n (child) => child.type !== 'JSXText' || child.value.trim() !== ''\n );\n if (\n children.length !== 1 ||\n !(isShell\n ? isChildrenSlot(children[0])\n : isJsxElementNamed(children[0], 'Outlet'))\n ) {\n return undefined;\n }\n const { name } = returned.openingElement.name;\n // Its declaration and the route component's element are the only uses.\n let uses = 0;\n for (const statement of statements) {\n t.traverseFast(statement, (node) => {\n if (isJsxElementNamed(node, name) || t.isIdentifier(node, { name })) {\n uses++;\n }\n });\n }\n if (uses !== 2) return undefined;\n const document = findLocalFunction(statements, name);\n return document && rendersElement([document.body], 'html')\n ? document\n : undefined;\n}\n\n/**\n * The root route, the local function its shellComponent or component names,\n * and the local function that renders its document.\n */\nexport function findRootComponent(statements: t.Statement[]) {\n const rootRoute = findRootRoute(statements);\n if (!rootRoute) return undefined;\n const { properties } = rootRoute.options;\n const componentProperty =\n properties.find((p) => getPropertyName(p) === 'shellComponent') ??\n properties.find((p) => getPropertyName(p) === 'component');\n const component =\n componentProperty?.type === 'ObjectProperty' &&\n componentProperty.value.type === 'Identifier'\n ? findLocalFunction(statements, componentProperty.value.name)\n : undefined;\n const isShell =\n componentProperty !== undefined &&\n getPropertyName(componentProperty) === 'shellComponent';\n const document = component && findDocument(statements, component, isShell);\n return { rootRoute, componentProperty, component, isShell, document };\n}\n\n/**\n * Configures the create-start root route: `createRootRoute({...})` (or its\n * router-context form) without a loader, whose shellComponent renders\n * `{children}` (or whose component renders `<Outlet />`) once in the `<body>`\n * of a local `<html>` document, either directly or through one local document\n * component that renders its `{children}` there. Returns undefined for any\n * other shape.\n */\nexport function configureRootRoute({\n content,\n statements,\n}: SourceFile): string | undefined {\n if (!statements) return undefined;\n // Generated bindings must not shadow or collide with the app's own.\n if (/\\b(?:getLocale|getTranslationsSnapshot)\\b/.test(content)) {\n return undefined;\n }\n const found = findRootComponent(statements);\n if (!found) return undefined;\n const { rootRoute, componentProperty, component, isShell, document } = found;\n const { properties } = rootRoute.options;\n if (\n properties.some((property) => {\n const name = getPropertyName(property);\n // A spread or computed key could be any of the options below.\n // A throwing beforeLoad or validateSearch skips the loader, so the\n // shell would render without the locale and translations it reads.\n return (\n name === undefined ||\n name === 'loader' ||\n name === 'beforeLoad' ||\n name === 'validateSearch'\n );\n })\n ) {\n return undefined;\n }\n if (\n componentProperty?.type !== 'ObjectProperty' ||\n !component ||\n document?.body.type !== 'BlockStatement' ||\n [component, document].some((fn) =>\n /\\b(?:locale|translations)\\b/.test(content.slice(fn.start!, fn.end!))\n )\n ) {\n return undefined;\n }\n // A followed document receives the route's slot as its children.\n const slotIsChildren = isShell || document !== component;\n const htmlElements: t.JSXElement[] = [];\n t.traverseFast(document.body, (node) => {\n if (isJsxElementNamed(node, 'html')) htmlElements.push(node);\n });\n if (htmlElements.length !== 1) return undefined;\n const [html] = htmlElements;\n const bodies = html.children.filter((child) =>\n isJsxElementNamed(child, 'body')\n );\n if (bodies.length !== 1) return undefined;\n // Headers, footers and app providers around the slot render GT too, so the\n // provider wraps everything the body renders before <Scripts />.\n const bodyContent = bodies[0].children.filter(\n (child) => child.type !== 'JSXText' || child.value.trim() !== ''\n );\n const scriptsIndex = bodyContent.findIndex((child) =>\n isJsxElementNamed(child, 'Scripts')\n );\n const wrapped =\n scriptsIndex === -1 ? bodyContent : bodyContent.slice(0, scriptsIndex);\n let slots = 0;\n let multilineLiteral = false;\n for (const child of wrapped) {\n t.traverseFast(child, (node) => {\n if (\n slotIsChildren\n ? isChildrenSlot(node)\n : isJsxElementNamed(node, 'Outlet')\n ) {\n slots++;\n }\n if (\n (node.type === 'TemplateLiteral' || node.type === 'StringLiteral') &&\n node.loc!.start.line !== node.loc!.end.line\n ) {\n multilineLiteral = true;\n }\n });\n }\n if (slots !== 1) return undefined;\n const { attributes } = html.openingElement;\n if (attributes.some((attribute) => attribute.type === 'JSXSpreadAttribute')) {\n return undefined;\n }\n const lang = attributes.find(\n (attribute): attribute is t.JSXAttribute =>\n attribute.type === 'JSXAttribute' &&\n t.isJSXIdentifier(attribute.name, { name: 'lang' })\n );\n // A computed lang is the app's own locale logic.\n if (lang && lang.value?.type !== 'StringLiteral') return undefined;\n const propertyIndent = getOwnLineIndent(content, componentProperty.start!);\n if (propertyIndent === undefined) return undefined;\n\n const { quote, semi, eol, indent } = getCodeStyle(content, statements);\n const first = wrapped[0];\n const last = wrapped.at(-1)!;\n const wrappedText = content.slice(first.start!, last.end!);\n const wrappedIndent = getOwnLineIndent(content, first.start!);\n // Reindenting would change the value of a literal that spans lines, such\n // as a template, a backslash-continued string or a JSX attribute string.\n const nestedText = multilineLiteral\n ? wrappedText\n : wrappedText.replace(/\\n(?=[ \\t]*\\S)/g, `\\n${indent}`);\n const provider = '<GTProvider locale={locale} translations={translations}>';\n const firstStatement = document.body.body[0];\n const statementIndent =\n (firstStatement && getOwnLineIndent(content, firstStatement.start!)) ??\n getLineIndent(content, document.start!) + indent;\n return applyEdits(content, [\n getImportEdit(\n statements,\n [\n `import { GTProvider, getLocale, getTranslationsSnapshot } from ${quote}${Libraries.GT_TANSTACK_START}${quote}${semi}`,\n ],\n eol\n ),\n {\n start: componentProperty.start!,\n text: [\n 'loader: async () => {',\n `${propertyIndent}${indent}const locale = getLocale()${semi}`,\n `${propertyIndent}${indent}return { locale, translations: await getTranslationsSnapshot(locale) }${semi}`,\n `${propertyIndent}},`,\n propertyIndent,\n ].join(eol),\n },\n {\n start: document.body.start! + 1,\n text: `${eol}${statementIndent}const { locale, translations } = ${rootRoute.routeName}.useLoaderData()${semi}`,\n },\n lang\n ? { start: lang.start!, end: lang.end!, text: 'lang={locale}' }\n : { start: html.openingElement.name.end!, text: ' lang={locale}' },\n {\n start: first.start!,\n end: last.end!,\n text:\n wrappedIndent === undefined\n ? `${provider}${wrappedText}</GTProvider>`\n : [\n provider,\n `${wrappedIndent}${indent}${nestedText}`,\n `${wrappedIndent}</GTProvider>`,\n ].join(eol),\n },\n ]);\n}\n\nexport function getRootFix(rootPath: string): string {\n return `In ${rootPath}, add loader: async () => { const locale = getLocale(); return { locale, translations: await getTranslationsSnapshot(locale) }; } to the root route options, read const { locale, translations } = Route.useLoaderData() in the document, set <html lang={locale}>, and wrap everything its <body> renders before <Scripts /> in <GTProvider locale={locale} translations={translations}>, importing GTProvider, getLocale and getTranslationsSnapshot from '${Libraries.GT_TANSTACK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K;GAAM,MAAM;GAAiB,GAC7D;GAAE,OAAO,KAAK,eAAe,KAAK;GAAM,MAAM;GAAkB;EACpE;GACE,OAAO,MAAM;GACb,KAAK,KAAK;GACV,MACE,kBAAkB,KAAA,IACd,GAAG,WAAW,YAAY,iBAC1B;IACE;IACA,GAAG,gBAAgB,SAAS;IAC5B,GAAG,cAAc;IAClB,CAAC,KAAK,IAAI;GAClB;EACF,CAAC;;AAGJ,SAAgB,WAAW,UAA0B;AACnD,QAAO,MAAM,SAAS,udAAoe,SAAS"}
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import * as t from '@babel/types';
|
|
2
2
|
import { type ViteLoaderExport } from '../../setupViteSPA.js';
|
|
3
3
|
import type { BuildToolContext, ManualAction } from '../index.js';
|
|
4
|
-
import type { CodeStyle } from '
|
|
5
|
-
import { type SourceFile } from '
|
|
4
|
+
import type { CodeStyle } from '../shared/edits.js';
|
|
5
|
+
import { type SourceFile } from '../shared/source.js';
|
|
6
6
|
/** The module-scope `initializeGT(...)` call, which must run before requests. */
|
|
7
7
|
export declare function findInitializeCall(file: SourceFile): t.CallExpression | undefined;
|
|
8
8
|
/**
|
|
@@ -1,12 +1,13 @@
|
|
|
1
1
|
import "../../../types/libraries.js";
|
|
2
2
|
import { toRelativeImport } from "../../setupViteSPA.js";
|
|
3
|
-
import {
|
|
3
|
+
import { getLocalImport, getPropertyName } from "../shared/source.js";
|
|
4
|
+
import { DOCS_URL } from "./source.js";
|
|
4
5
|
import path from "node:path";
|
|
5
6
|
import * as t from "@babel/types";
|
|
6
7
|
//#region src/setup/buildTools/tanstackStart/router.ts
|
|
7
8
|
/** The module-scope `initializeGT(...)` call, which must run before requests. */
|
|
8
9
|
function findInitializeCall(file) {
|
|
9
|
-
const local = getLocalImport(file, "initializeGT");
|
|
10
|
+
const local = getLocalImport(file, "initializeGT", "gt-tanstack-start");
|
|
10
11
|
if (!local) return void 0;
|
|
11
12
|
for (const statement of file.statements ?? []) if (statement.type === "ExpressionStatement" && statement.expression.type === "CallExpression" && t.isIdentifier(statement.expression.callee, { name: local })) return statement.expression;
|
|
12
13
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"router.js","names":[],"sources":["../../../../src/setup/buildTools/tanstackStart/router.ts"],"sourcesContent":["// src/router.tsx: the initializeGT call and its translation loader.\nimport * as t from '@babel/types';\nimport path from 'node:path';\nimport { Libraries } from '../../../types/libraries.js';\nimport { toRelativeImport, type ViteLoaderExport } from '../../setupViteSPA.js';\nimport type { BuildToolContext, ManualAction } from '../index.js';\nimport type { CodeStyle } from '
|
|
1
|
+
{"version":3,"file":"router.js","names":[],"sources":["../../../../src/setup/buildTools/tanstackStart/router.ts"],"sourcesContent":["// src/router.tsx: the initializeGT call and its translation loader.\nimport * as t from '@babel/types';\nimport path from 'node:path';\nimport { Libraries } from '../../../types/libraries.js';\nimport { toRelativeImport, type ViteLoaderExport } from '../../setupViteSPA.js';\nimport type { BuildToolContext, ManualAction } from '../index.js';\nimport type { CodeStyle } from '../shared/edits.js';\nimport {\n getLocalImport,\n getPropertyName,\n type SourceFile,\n} from '../shared/source.js';\nimport { DOCS_URL } from './source.js';\n\n/** The module-scope `initializeGT(...)` call, which must run before requests. */\nexport function findInitializeCall(\n file: SourceFile\n): t.CallExpression | undefined {\n const local = getLocalImport(\n file,\n 'initializeGT',\n Libraries.GT_TANSTACK_START\n );\n if (!local) return undefined;\n for (const statement of file.statements ?? []) {\n if (\n statement.type === 'ExpressionStatement' &&\n statement.expression.type === 'CallExpression' &&\n t.isIdentifier(statement.expression.callee, { name: local })\n ) {\n return statement.expression;\n }\n }\n return undefined;\n}\n\n/**\n * Whether the initializeGT options pass a loader: false for the config alone,\n * undefined when the options hide it (other spreads, variables, computed keys).\n */\nexport function passesLoader(\n router: SourceFile,\n options: t.Node | undefined,\n { appDirectory, configFilepath }: BuildToolContext\n): boolean | undefined {\n const configPath = path.resolve(appDirectory, configFilepath);\n const routerDirectory = path.dirname(path.join(appDirectory, router.path));\n const configBinding = router.statements\n ?.filter((statement) => statement.type === 'ImportDeclaration')\n .find(\n (statement) =>\n path.resolve(routerDirectory, statement.source.value) === configPath\n )\n ?.specifiers.find(\n (specifier) => specifier.type === 'ImportDefaultSpecifier'\n )?.local.name;\n const isConfig = (node: t.Node) =>\n node.type === 'Identifier' && node.name === configBinding;\n if (!options) return undefined;\n if (isConfig(options)) return false;\n if (options.type !== 'ObjectExpression') return undefined;\n let loader = false;\n for (const property of options.properties) {\n if (property.type === 'SpreadElement') {\n if (!isConfig(property.argument)) return undefined;\n continue;\n }\n const name = getPropertyName(property);\n if (name === undefined) return undefined;\n if (name === 'loadTranslations') loader = true;\n }\n return loader;\n}\n\nexport function getRouterLines(\n router: SourceFile,\n { appDirectory, configFilepath }: BuildToolContext,\n loaderExport: ViteLoaderExport,\n { quote, semi }: Pick<CodeStyle, 'quote' | 'semi'>\n): string[] {\n const configImport = toRelativeImport(\n path.dirname(path.join(appDirectory, router.path)),\n path.resolve(appDirectory, configFilepath)\n );\n const importFrom = (bindings: string, source: string) =>\n `import ${bindings} from ${quote}${source}${quote}${semi}`;\n return [\n importFrom('{ initializeGT }', Libraries.GT_TANSTACK_START),\n importFrom('gtConfig', configImport),\n ...(loaderExport\n ? [\n importFrom(\n loaderExport === 'default'\n ? 'loadTranslations'\n : '{ loadTranslations }',\n './loadTranslations'\n ),\n ]\n : []),\n '',\n `initializeGT(${loaderExport ? '{ ...gtConfig, loadTranslations }' : 'gtConfig'})${semi}`,\n ];\n}\n\n/** The initializeGT change for a router whose storage no longer matches. */\nexport function getStorageAction(\n router: SourceFile,\n ctx: BuildToolContext,\n loaderExport: ViteLoaderExport,\n loaderPassed: boolean\n): ManualAction {\n const lines = getRouterLines(router, ctx, loaderExport, {\n quote: \"'\",\n semi: '',\n });\n const call = lines.at(-1)!;\n const loaderImport = loaderExport\n ? lines.find((line) => line.endsWith(\"'./loadTranslations'\"))\n : undefined;\n return {\n whatHappened: `${router.path} initializes GT for ${loaderPassed ? 'local translation files' : 'CDN translations'}, but translations are now ${ctx.translationsDir ? `stored in ${ctx.translationsDir}` : 'loaded from the CDN'}`,\n fix: `Change the initializeGT call in ${router.path} to ${call}${loaderImport ? ` and add ${loaderImport}` : ' and remove the loadTranslations import'} (see ${DOCS_URL})`,\n };\n}\n"],"mappings":";;;;;;;;AAeA,SAAgB,mBACd,MAC8B;CAC9B,MAAM,QAAQ,eACZ,MACA,gBAAA,oBAED;AACD,KAAI,CAAC,MAAO,QAAO,KAAA;AACnB,MAAK,MAAM,aAAa,KAAK,cAAc,EAAE,CAC3C,KACE,UAAU,SAAS,yBACnB,UAAU,WAAW,SAAS,oBAC9B,EAAE,aAAa,UAAU,WAAW,QAAQ,EAAE,MAAM,OAAO,CAAC,CAE5D,QAAO,UAAU;;;;;;AAUvB,SAAgB,aACd,QACA,SACA,EAAE,cAAc,kBACK;CACrB,MAAM,aAAa,KAAK,QAAQ,cAAc,eAAe;CAC7D,MAAM,kBAAkB,KAAK,QAAQ,KAAK,KAAK,cAAc,OAAO,KAAK,CAAC;CAC1E,MAAM,gBAAgB,OAAO,YACzB,QAAQ,cAAc,UAAU,SAAS,oBAAoB,CAC9D,MACE,cACC,KAAK,QAAQ,iBAAiB,UAAU,OAAO,MAAM,KAAK,WAC7D,EACC,WAAW,MACV,cAAc,UAAU,SAAS,yBACnC,EAAE,MAAM;CACX,MAAM,YAAY,SAChB,KAAK,SAAS,gBAAgB,KAAK,SAAS;AAC9C,KAAI,CAAC,QAAS,QAAO,KAAA;AACrB,KAAI,SAAS,QAAQ,CAAE,QAAO;AAC9B,KAAI,QAAQ,SAAS,mBAAoB,QAAO,KAAA;CAChD,IAAI,SAAS;AACb,MAAK,MAAM,YAAY,QAAQ,YAAY;AACzC,MAAI,SAAS,SAAS,iBAAiB;AACrC,OAAI,CAAC,SAAS,SAAS,SAAS,CAAE,QAAO,KAAA;AACzC;;EAEF,MAAM,OAAO,gBAAgB,SAAS;AACtC,MAAI,SAAS,KAAA,EAAW,QAAO,KAAA;AAC/B,MAAI,SAAS,mBAAoB,UAAS;;AAE5C,QAAO;;AAGT,SAAgB,eACd,QACA,EAAE,cAAc,kBAChB,cACA,EAAE,OAAO,QACC;CACV,MAAM,eAAe,iBACnB,KAAK,QAAQ,KAAK,KAAK,cAAc,OAAO,KAAK,CAAC,EAClD,KAAK,QAAQ,cAAc,eAAe,CAC3C;CACD,MAAM,cAAc,UAAkB,WACpC,UAAU,SAAS,QAAQ,QAAQ,SAAS,QAAQ;AACtD,QAAO;EACL,WAAW,oBAAA,oBAAgD;EAC3D,WAAW,YAAY,aAAa;EACpC,GAAI,eACA,CACE,WACE,iBAAiB,YACb,qBACA,wBACJ,qBACD,CACF,GACD,EAAE;EACN;EACA,gBAAgB,eAAe,sCAAsC,WAAW,GAAG;EACpF;;;AAIH,SAAgB,iBACd,QACA,KACA,cACA,cACc;CACd,MAAM,QAAQ,eAAe,QAAQ,KAAK,cAAc;EACtD,OAAO;EACP,MAAM;EACP,CAAC;CACF,MAAM,OAAO,MAAM,GAAG,GAAG;CACzB,MAAM,eAAe,eACjB,MAAM,MAAM,SAAS,KAAK,SAAS,uBAAuB,CAAC,GAC3D,KAAA;AACJ,QAAO;EACL,cAAc,GAAG,OAAO,KAAK,sBAAsB,eAAe,4BAA4B,mBAAmB,6BAA6B,IAAI,kBAAkB,aAAa,IAAI,oBAAoB;EACzM,KAAK,mCAAmC,OAAO,KAAK,MAAM,OAAO,eAAe,YAAY,iBAAiB,0CAA0C,QAAQ,SAAS;EACzK"}
|
|
@@ -1,19 +1,7 @@
|
|
|
1
|
-
import * as t from '@babel/types';
|
|
2
1
|
export declare const DOCS_URL = "https://generaltranslation.com/docs/react/tanstack-start/setup";
|
|
3
|
-
export type SourceFile = {
|
|
4
|
-
/** Relative to the app, with forward slashes. */
|
|
5
|
-
path: string;
|
|
6
|
-
content: string;
|
|
7
|
-
/** Undefined when the file cannot be parsed. */
|
|
8
|
-
statements?: t.Statement[];
|
|
9
|
-
};
|
|
10
|
-
export declare function readSourceFile(appDirectory: string, basename: string): Promise<SourceFile | undefined>;
|
|
11
2
|
/** Reads the Start entries without writing, so a missing one stops setup. */
|
|
12
3
|
export declare function inspectTanStackStart(appDirectory: string): Promise<{
|
|
13
|
-
router: SourceFile;
|
|
14
|
-
root: SourceFile;
|
|
15
|
-
start: SourceFile | undefined;
|
|
4
|
+
router: import("../shared/source.js").SourceFile;
|
|
5
|
+
root: import("../shared/source.js").SourceFile;
|
|
6
|
+
start: import("../shared/source.js").SourceFile | undefined;
|
|
16
7
|
}>;
|
|
17
|
-
/** The local name `name` is imported as from `source` (gt-tanstack-start). */
|
|
18
|
-
export declare function getLocalImport(file: SourceFile, name: string, source?: string): string | undefined;
|
|
19
|
-
export declare function getPropertyName(property: t.ObjectExpression['properties'][number]): string | undefined;
|
|
@@ -1,30 +1,7 @@
|
|
|
1
|
-
import "
|
|
2
|
-
import { parseModule } from "../../setupViteSPA.js";
|
|
1
|
+
import { readSourceFile } from "../shared/source.js";
|
|
3
2
|
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
3
|
//#region src/setup/buildTools/tanstackStart/source.ts
|
|
8
4
|
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
5
|
function getMissingFileError(file) {
|
|
29
6
|
return new Error(createDiagnosticMessage({
|
|
30
7
|
source: "gt",
|
|
@@ -48,19 +25,7 @@ async function inspectTanStackStart(appDirectory) {
|
|
|
48
25
|
start: await readSourceFile(appDirectory, "src/start")
|
|
49
26
|
};
|
|
50
27
|
}
|
|
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
28
|
//#endregion
|
|
64
|
-
export { DOCS_URL,
|
|
29
|
+
export { DOCS_URL, inspectTanStackStart };
|
|
65
30
|
|
|
66
31
|
//# sourceMappingURL=source.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"source.js","names":[],"sources":["../../../../src/setup/buildTools/tanstackStart/source.ts"],"sourcesContent":["// Reads the Start entries
|
|
1
|
+
{"version":3,"file":"source.js","names":[],"sources":["../../../../src/setup/buildTools/tanstackStart/source.ts"],"sourcesContent":["// Reads the Start entries setup configures.\nimport { createDiagnosticMessage } from 'generaltranslation/internal';\nimport { readSourceFile } from '../shared/source.js';\n\nexport const DOCS_URL =\n 'https://generaltranslation.com/docs/react/tanstack-start/setup';\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"],"mappings":";;;AAIA,MAAa,WACX;AAEF,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"}
|
|
@@ -30,18 +30,19 @@ export declare function inspectViteSPA(appDirectory: string): Promise<{
|
|
|
30
30
|
}>;
|
|
31
31
|
export type ViteLoaderResult = 'created' | 'updated' | 'unchanged' | 'custom' | 'missing';
|
|
32
32
|
/**
|
|
33
|
-
* Points the generated
|
|
34
|
-
* empty locale stubs. Only a template
|
|
35
|
-
* refreshed; other existing loaders are left
|
|
36
|
-
* is only created with `create`.
|
|
33
|
+
* Points the generated loadTranslations.ts in sourceDirectory (src by
|
|
34
|
+
* default) at translationsDir and adds empty locale stubs. Only a template
|
|
35
|
+
* matching the previous config is refreshed; other existing loaders are left
|
|
36
|
+
* unchanged. An absent loader is only created with `create`.
|
|
37
37
|
*/
|
|
38
|
-
export declare function writeViteLoader({ appDirectory, defaultLocale, locales, translationsDir, previousTranslationsDir, create, }: Omit<SetupViteSPAOptions, 'configFilepath' | 'translationsDir'> & {
|
|
38
|
+
export declare function writeViteLoader({ appDirectory, defaultLocale, locales, translationsDir, previousTranslationsDir, create, sourceDirectory, }: Omit<SetupViteSPAOptions, 'configFilepath' | 'translationsDir'> & {
|
|
39
39
|
translationsDir: string;
|
|
40
40
|
create: boolean;
|
|
41
|
+
sourceDirectory?: string;
|
|
41
42
|
}): Promise<ViteLoaderResult>;
|
|
42
43
|
export type ViteLoaderExport = 'default' | 'loadTranslations' | undefined;
|
|
43
44
|
/** 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>;
|
|
45
|
+
export declare function getViteLoaderExport(appDirectory: string, loader: ViteLoaderResult, sourceDirectory?: string): Promise<ViteLoaderExport>;
|
|
45
46
|
export declare function setupViteSPA({ appDirectory, configFilepath, defaultLocale, locales, translationsDir, previousTranslationsDir, }: SetupViteSPAOptions): Promise<{
|
|
46
47
|
loader?: ViteLoaderResult;
|
|
47
48
|
manualAction?: string;
|
|
@@ -7,6 +7,7 @@ import { parse } from "@babel/parser";
|
|
|
7
7
|
//#region src/setup/setupViteSPA.ts
|
|
8
8
|
const defaultBootstrapFilename = "gt-entry.ts";
|
|
9
9
|
const alternateBootstrapFilename = "gt-bootstrap.ts";
|
|
10
|
+
const defaultSourceDirectory = "src";
|
|
10
11
|
function getBootstrapConflictError(filename) {
|
|
11
12
|
return createDiagnosticMessage({
|
|
12
13
|
source: "gt",
|
|
@@ -70,7 +71,7 @@ function getModuleEntry(indexHtml) {
|
|
|
70
71
|
*/
|
|
71
72
|
async function inspectViteSPA(appDirectory) {
|
|
72
73
|
const indexHtmlPath = path.join(appDirectory, "index.html");
|
|
73
|
-
const sourceDirectory = path.join(appDirectory,
|
|
74
|
+
const sourceDirectory = path.join(appDirectory, defaultSourceDirectory);
|
|
74
75
|
if (!fs.existsSync(indexHtmlPath)) throw new Error(createDiagnosticMessage({
|
|
75
76
|
source: "gt",
|
|
76
77
|
severity: "Error",
|
|
@@ -119,19 +120,19 @@ async function inspectViteSPA(appDirectory) {
|
|
|
119
120
|
};
|
|
120
121
|
}
|
|
121
122
|
/**
|
|
122
|
-
* Points the generated
|
|
123
|
-
* empty locale stubs. Only a template
|
|
124
|
-
* refreshed; other existing loaders are left
|
|
125
|
-
* is only created with `create`.
|
|
123
|
+
* Points the generated loadTranslations.ts in sourceDirectory (src by
|
|
124
|
+
* default) at translationsDir and adds empty locale stubs. Only a template
|
|
125
|
+
* matching the previous config is refreshed; other existing loaders are left
|
|
126
|
+
* unchanged. An absent loader is only created with `create`.
|
|
126
127
|
*/
|
|
127
|
-
async function writeViteLoader({ appDirectory, defaultLocale, locales, translationsDir, previousTranslationsDir, create }) {
|
|
128
|
-
const
|
|
128
|
+
async function writeViteLoader({ appDirectory, defaultLocale, locales, translationsDir, previousTranslationsDir, create, sourceDirectory = defaultSourceDirectory }) {
|
|
129
|
+
const loaderDirectory = path.join(appDirectory, sourceDirectory);
|
|
129
130
|
const translationsPath = path.resolve(appDirectory, translationsDir);
|
|
130
|
-
const loaderPath = path.join(
|
|
131
|
+
const loaderPath = path.join(loaderDirectory, "loadTranslations.ts");
|
|
131
132
|
const existingLoader = fs.existsSync(loaderPath) ? await fs.promises.readFile(loaderPath, "utf8") : void 0;
|
|
132
133
|
if (existingLoader === void 0 && !create) return "missing";
|
|
133
|
-
const content = getLoaderContent(toRelativeImport(
|
|
134
|
-
const previousContent = previousTranslationsDir === void 0 ? void 0 : getLoaderContent(toRelativeImport(
|
|
134
|
+
const content = getLoaderContent(toRelativeImport(loaderDirectory, translationsPath));
|
|
135
|
+
const previousContent = previousTranslationsDir === void 0 ? void 0 : getLoaderContent(toRelativeImport(loaderDirectory, path.resolve(appDirectory, previousTranslationsDir)));
|
|
135
136
|
const normalizedLoader = existingLoader?.replace(/\r\n/g, "\n").trimEnd();
|
|
136
137
|
const custom = existingLoader !== void 0 && normalizedLoader !== content.trimEnd() && normalizedLoader !== previousContent?.trimEnd();
|
|
137
138
|
await fs.promises.mkdir(translationsPath, { recursive: true });
|
|
@@ -146,8 +147,8 @@ async function writeViteLoader({ appDirectory, defaultLocale, locales, translati
|
|
|
146
147
|
return existingLoader === void 0 ? "created" : "updated";
|
|
147
148
|
}
|
|
148
149
|
/** 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,
|
|
150
|
+
async function getViteLoaderExport(appDirectory, loader, sourceDirectory = defaultSourceDirectory) {
|
|
151
|
+
return loader === "custom" ? getLoaderExport(await fs.promises.readFile(path.join(appDirectory, sourceDirectory, "loadTranslations.ts"), "utf8")) : "default";
|
|
151
152
|
}
|
|
152
153
|
function getLoaderExport(content) {
|
|
153
154
|
const statements = parseModule(content, "loadTranslations.ts");
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"setupViteSPA.js","names":[],"sources":["../../src/setup/setupViteSPA.ts"],"sourcesContent":["import { parse } from '@babel/parser';\nimport { createDiagnosticMessage } from 'generaltranslation/diagnostics';\nimport fs from 'node:fs';\nimport path from 'node:path';\nimport { logger } from '../console/logger.js';\nimport { Libraries } from '../types/libraries.js';\n\ntype SetupViteSPAOptions = {\n appDirectory: string;\n configFilepath: string;\n defaultLocale: string;\n locales: string[];\n translationsDir?: string;\n previousTranslationsDir?: string;\n};\n\nconst defaultBootstrapFilename = 'gt-entry.ts';\nconst alternateBootstrapFilename = 'gt-bootstrap.ts';\n\nfunction getBootstrapConflictError(filename: string): string {\n return createDiagnosticMessage({\n source: 'gt',\n severity: 'Error',\n whatHappened: 'The Vite bootstrap file already exists',\n why: `GT will not overwrite an existing src/${filename} file`,\n fix: 'Move or rename that file and rerun `npx gt@latest`',\n });\n}\n\nfunction getLoaderContent(translationsImport: string): string {\n return `export default async function loadTranslations(locale: string) {\n const translations = await import(\\`${translationsImport}/\\${locale}.json\\`);\n return translations.default;\n}\n`;\n}\n\n/**\n * Top-level statements, or undefined for syntax this inspector cannot parse\n * but Vite may accept, such as decorators.\n */\nexport function parseModule(content: string, filename: string) {\n try {\n return parse(content, {\n sourceType: 'module',\n // JSX would reject `<T>x` assertions, which .ts files may use.\n plugins: /\\.[cm]?ts$/i.test(filename)\n ? ['typescript']\n : ['typescript', 'jsx'],\n }).program.body;\n } catch {\n return undefined;\n }\n}\n\nexport function toRelativeImport(\n fromDirectory: string,\n toPath: string\n): string {\n const relativePath = path\n .relative(fromDirectory, toPath)\n .split(path.sep)\n .join(path.posix.sep);\n return relativePath.startsWith('.') ? relativePath : `./${relativePath}`;\n}\n\nfunction getEntryPath(appDirectory: string, source: string): string {\n const sourcePath = source.replace(/[?#].*$/, '');\n return sourcePath.startsWith('/')\n ? path.resolve(appDirectory, `.${sourcePath}`)\n : path.resolve(appDirectory, sourcePath);\n}\n\nfunction getBootstrapEntry(bootstrap: string): string | undefined {\n return bootstrap.match(/await\\s+import\\(\\s*(['\"])([^'\"]+)\\1\\s*\\)/)?.[2];\n}\n\nfunction getModuleEntry(indexHtml: string): {\n script: string;\n source: string;\n} {\n const moduleScripts = indexHtml.match(\n /<script\\b[^>]*\\btype=(['\"])module\\1[^>]*>\\s*<\\/script>/gi\n );\n for (const script of moduleScripts ?? []) {\n const source = script.match(/\\bsrc=(['\"])([^'\"]+)\\1/i)?.[2];\n if (source) return { script, source };\n }\n\n throw new Error(\n createDiagnosticMessage({\n source: 'gt',\n severity: 'Error',\n whatHappened: 'No Vite module entry was found in index.html',\n fix: 'Add a module script for the app entry and rerun `npx gt@latest`',\n })\n );\n}\n\n/**\n * Reads the Vite entry and bootstrap without writing, so setup can report an\n * unsupported layout before changing any file.\n */\nexport async function inspectViteSPA(appDirectory: string) {\n const indexHtmlPath = path.join(appDirectory, 'index.html');\n const sourceDirectory = path.join(appDirectory, 'src');\n if (!fs.existsSync(indexHtmlPath)) {\n throw new Error(\n createDiagnosticMessage({\n source: 'gt',\n severity: 'Error',\n whatHappened: 'This is not a Vite single-page app',\n why: 'index.html was not found',\n reassurance: 'Nothing was changed',\n fix: 'Rerun `npx gt@latest init` with `--framework` set to your framework, or set up GT manually',\n })\n );\n }\n const indexHtml = await fs.promises.readFile(indexHtmlPath, 'utf8');\n const { script, source } = getModuleEntry(indexHtml);\n const declaredEntryPath = getEntryPath(appDirectory, source);\n const declaredEntryImport = toRelativeImport(\n sourceDirectory,\n declaredEntryPath\n ).replace(/\\.(?:[cm]?[jt]sx?)$/i, '');\n const configuredBootstrap = source.match(\n /^\\/?src\\/(gt-entry\\.ts|gt-bootstrap\\.ts)(?:[?#].*)?$/\n )?.[1];\n let customBootstrap: string | undefined;\n if (!configuredBootstrap && fs.existsSync(declaredEntryPath)) {\n const entry = await fs.promises.readFile(declaredEntryPath, 'utf8');\n const mentionsInitializer = entry.includes('initializeGTSPA');\n // Unparseable entries fall back to the text check: a false positive only\n // asks for manual review, while a miss would initialize GT twice.\n const importsInitializer =\n parseModule(entry, declaredEntryPath)?.some(\n (statement) =>\n statement.type === 'ImportDeclaration' &&\n statement.source.value === Libraries.GT_REACT &&\n statement.importKind !== 'type' &&\n statement.specifiers.some(\n (specifier) =>\n (specifier.type === 'ImportNamespaceSpecifier' &&\n mentionsInitializer) ||\n (specifier.type === 'ImportSpecifier' &&\n specifier.importKind !== 'type' &&\n specifier.imported.type === 'Identifier' &&\n specifier.imported.name === 'initializeGTSPA')\n )\n ) ?? mentionsInitializer;\n if (importsInitializer) {\n customBootstrap = path.relative(appDirectory, declaredEntryPath);\n }\n }\n const isAlreadyConfigured = configuredBootstrap !== undefined;\n const bootstrapFilename =\n configuredBootstrap ??\n (declaredEntryImport === './gt-entry'\n ? alternateBootstrapFilename\n : defaultBootstrapFilename);\n const bootstrapPath = path.join(sourceDirectory, bootstrapFilename);\n let existingBootstrap: string | undefined;\n\n if (!customBootstrap && fs.existsSync(bootstrapPath)) {\n existingBootstrap = await fs.promises.readFile(bootstrapPath, 'utf8');\n if (!existingBootstrap.includes('initializeGTSPA')) {\n throw new Error(getBootstrapConflictError(bootstrapFilename));\n }\n }\n\n const entryImport = isAlreadyConfigured\n ? existingBootstrap && getBootstrapEntry(existingBootstrap)\n : declaredEntryImport;\n if (!entryImport) {\n throw new Error(\n createDiagnosticMessage({\n source: 'gt',\n severity: 'Error',\n whatHappened: 'The existing Vite bootstrap has no app entry import',\n fix: 'Restore the app entry import and rerun `npx gt@latest`',\n })\n );\n }\n return {\n indexHtmlPath,\n sourceDirectory,\n indexHtml,\n script,\n source,\n isAlreadyConfigured,\n customBootstrap,\n bootstrapFilename,\n bootstrapPath,\n entryImport,\n };\n}\n\nexport type ViteLoaderResult =\n | 'created'\n | 'updated'\n | 'unchanged'\n | 'custom'\n | 'missing';\n\n/**\n * Points the generated src/loadTranslations.ts at translationsDir and adds\n * empty locale stubs. Only a template matching the previous config is\n * refreshed; other existing loaders are left unchanged. An absent loader\n * is only created with `create`.\n */\nexport async function writeViteLoader({\n appDirectory,\n defaultLocale,\n locales,\n translationsDir,\n previousTranslationsDir,\n create,\n}: Omit<SetupViteSPAOptions, 'configFilepath' | 'translationsDir'> & {\n translationsDir: string;\n create: boolean;\n}): Promise<ViteLoaderResult> {\n const sourceDirectory = path.join(appDirectory, 'src');\n const translationsPath = path.resolve(appDirectory, translationsDir);\n const loaderPath = path.join(sourceDirectory, 'loadTranslations.ts');\n const existingLoader = fs.existsSync(loaderPath)\n ? await fs.promises.readFile(loaderPath, 'utf8')\n : undefined;\n if (existingLoader === undefined && !create) return 'missing';\n const content = getLoaderContent(\n toRelativeImport(sourceDirectory, translationsPath)\n );\n const previousContent =\n previousTranslationsDir === undefined\n ? undefined\n : getLoaderContent(\n toRelativeImport(\n sourceDirectory,\n path.resolve(appDirectory, previousTranslationsDir)\n )\n );\n const normalizedLoader = existingLoader?.replace(/\\r\\n/g, '\\n').trimEnd();\n const custom =\n existingLoader !== undefined &&\n normalizedLoader !== content.trimEnd() &&\n normalizedLoader !== previousContent?.trimEnd();\n\n // Stubs first, so a directory failure leaves no loader pointing at it.\n await fs.promises.mkdir(translationsPath, { recursive: true });\n for (const locale of new Set(locales)) {\n if (locale === defaultLocale) continue;\n const stubPath = path.join(translationsPath, `${locale}.json`);\n if (!fs.existsSync(stubPath)) {\n await fs.promises.writeFile(stubPath, '{}\\n');\n }\n }\n if (custom) return 'custom';\n if (existingLoader === content) return 'unchanged';\n await fs.promises.writeFile(loaderPath, content);\n return existingLoader === undefined ? 'created' : 'updated';\n}\n\nexport type ViteLoaderExport = 'default' | 'loadTranslations' | undefined;\n\n/** The generated loader's export, or a custom loader's own if it has one. */\nexport async function getViteLoaderExport(\n appDirectory: string,\n loader: ViteLoaderResult\n): Promise<ViteLoaderExport> {\n return loader === 'custom'\n ? getLoaderExport(\n await fs.promises.readFile(\n path.join(appDirectory, 'src', 'loadTranslations.ts'),\n 'utf8'\n )\n )\n : 'default';\n}\n\nfunction getLoaderExport(content: string): ViteLoaderExport {\n const statements = parseModule(content, 'loadTranslations.ts');\n if (!statements) return undefined;\n const names = new Set<string>();\n for (const statement of statements) {\n // @babel/types omits the interface form the parser emits, which is erased\n // at compile time and leaves no runtime default export.\n if (\n statement.type === 'ExportDefaultDeclaration' &&\n (statement.declaration.type as string) !== 'TSInterfaceDeclaration'\n )\n names.add('default');\n if (\n statement.type !== 'ExportNamedDeclaration' ||\n statement.exportKind === 'type'\n )\n continue;\n for (const specifier of statement.specifiers) {\n if (\n specifier.type === 'ExportSpecifier' &&\n specifier.exportKind !== 'type'\n ) {\n names.add(\n specifier.exported.type === 'Identifier'\n ? specifier.exported.name\n : specifier.exported.value\n );\n }\n }\n const declaration = statement.declaration;\n if (\n declaration?.type === 'FunctionDeclaration' &&\n !declaration.declare &&\n declaration.id\n ) {\n names.add(declaration.id.name);\n }\n if (declaration?.type === 'VariableDeclaration' && !declaration.declare) {\n for (const variable of declaration.declarations) {\n if (variable.id.type === 'Identifier') names.add(variable.id.name);\n }\n }\n }\n if (names.has('default')) return 'default';\n if (names.has('loadTranslations')) return 'loadTranslations';\n return undefined;\n}\n\nexport async function setupViteSPA({\n appDirectory,\n configFilepath,\n defaultLocale,\n locales,\n translationsDir,\n previousTranslationsDir,\n}: SetupViteSPAOptions): Promise<{\n loader?: ViteLoaderResult;\n manualAction?: string;\n}> {\n const {\n indexHtmlPath,\n sourceDirectory,\n indexHtml,\n script,\n source,\n isAlreadyConfigured,\n customBootstrap,\n bootstrapFilename,\n bootstrapPath,\n entryImport,\n } = await inspectViteSPA(appDirectory);\n\n // An app-owned initializer may have custom imports and options. Nesting a\n // generated initializer around it would initialize GT twice.\n if (customBootstrap) {\n return {\n manualAction: `Verify the existing GT bootstrap ${customBootstrap} uses ${configFilepath}${translationsDir ? ` and loads translations from ${translationsDir}` : ' with CDN loading'}`,\n };\n }\n\n await fs.promises.mkdir(sourceDirectory, { recursive: true });\n\n let loadTranslationsImport = '';\n let loadTranslationsOption = 'gtConfig';\n let loader: ViteLoaderResult | undefined;\n if (translationsDir) {\n loader = await writeViteLoader({\n appDirectory,\n defaultLocale,\n locales,\n translationsDir,\n previousTranslationsDir,\n create: true,\n });\n const loaderExport = await getViteLoaderExport(appDirectory, loader);\n if (!loaderExport) {\n return {\n loader,\n manualAction: `Update your custom src/loadTranslations.ts to load translations from ${translationsDir} and export a default or named loadTranslations function, then rerun gt init`,\n };\n }\n loadTranslationsImport =\n loaderExport === 'default'\n ? \"import loadTranslations from './loadTranslations';\\n\"\n : \"import { loadTranslations } from './loadTranslations';\\n\";\n loadTranslationsOption = '{ ...gtConfig, loadTranslations }';\n }\n\n const configImport = toRelativeImport(\n sourceDirectory,\n path.resolve(appDirectory, configFilepath)\n );\n await fs.promises.writeFile(\n bootstrapPath,\n `import { initializeGTSPA } from '${Libraries.GT_REACT}';\nimport gtConfig from '${configImport}';\n${loadTranslationsImport}\nawait initializeGTSPA(${loadTranslationsOption});\n\nawait import('${entryImport}');\n`\n );\n\n if (!isAlreadyConfigured) {\n const updatedScript = script.replace(source, `/src/${bootstrapFilename}`);\n await fs.promises.writeFile(\n indexHtmlPath,\n indexHtml.replace(script, updatedScript)\n );\n }\n\n logger.success('Configured initializeGTSPA for this Vite application.');\n return {\n loader,\n ...(loader === 'custom' && {\n manualAction: `Verify your preserved custom src/loadTranslations.ts loads translations from ${translationsDir}`,\n }),\n };\n}\n"],"mappings":";;;;;;;AAgBA,MAAM,2BAA2B;AACjC,MAAM,6BAA6B;AAEnC,SAAS,0BAA0B,UAA0B;AAC3D,QAAO,wBAAwB;EAC7B,QAAQ;EACR,UAAU;EACV,cAAc;EACd,KAAK,yCAAyC,SAAS;EACvD,KAAK;EACN,CAAC;;AAGJ,SAAS,iBAAiB,oBAAoC;AAC5D,QAAO;wCAC+B,mBAAmB;;;;;;;;;AAU3D,SAAgB,YAAY,SAAiB,UAAkB;AAC7D,KAAI;AACF,SAAO,MAAM,SAAS;GACpB,YAAY;GAEZ,SAAS,cAAc,KAAK,SAAS,GACjC,CAAC,aAAa,GACd,CAAC,cAAc,MAAM;GAC1B,CAAC,CAAC,QAAQ;SACL;AACN;;;AAIJ,SAAgB,iBACd,eACA,QACQ;CACR,MAAM,eAAe,KAClB,SAAS,eAAe,OAAO,CAC/B,MAAM,KAAK,IAAI,CACf,KAAK,KAAK,MAAM,IAAI;AACvB,QAAO,aAAa,WAAW,IAAI,GAAG,eAAe,KAAK;;AAG5D,SAAS,aAAa,cAAsB,QAAwB;CAClE,MAAM,aAAa,OAAO,QAAQ,WAAW,GAAG;AAChD,QAAO,WAAW,WAAW,IAAI,GAC7B,KAAK,QAAQ,cAAc,IAAI,aAAa,GAC5C,KAAK,QAAQ,cAAc,WAAW;;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AI,WAAW,YAAY,EACzB,cAAc,gFAAgF,mBAC/F;EACF"}
|
|
1
|
+
{"version":3,"file":"setupViteSPA.js","names":[],"sources":["../../src/setup/setupViteSPA.ts"],"sourcesContent":["import { parse } from '@babel/parser';\nimport { createDiagnosticMessage } from 'generaltranslation/diagnostics';\nimport fs from 'node:fs';\nimport path from 'node:path';\nimport { logger } from '../console/logger.js';\nimport { Libraries } from '../types/libraries.js';\n\ntype SetupViteSPAOptions = {\n appDirectory: string;\n configFilepath: string;\n defaultLocale: string;\n locales: string[];\n translationsDir?: string;\n previousTranslationsDir?: string;\n};\n\nconst defaultBootstrapFilename = 'gt-entry.ts';\nconst alternateBootstrapFilename = 'gt-bootstrap.ts';\nconst defaultSourceDirectory = 'src';\n\nfunction getBootstrapConflictError(filename: string): string {\n return createDiagnosticMessage({\n source: 'gt',\n severity: 'Error',\n whatHappened: 'The Vite bootstrap file already exists',\n why: `GT will not overwrite an existing src/${filename} file`,\n fix: 'Move or rename that file and rerun `npx gt@latest`',\n });\n}\n\nfunction getLoaderContent(translationsImport: string): string {\n return `export default async function loadTranslations(locale: string) {\n const translations = await import(\\`${translationsImport}/\\${locale}.json\\`);\n return translations.default;\n}\n`;\n}\n\n/**\n * Top-level statements, or undefined for syntax this inspector cannot parse\n * but Vite may accept, such as decorators.\n */\nexport function parseModule(content: string, filename: string) {\n try {\n return parse(content, {\n sourceType: 'module',\n // JSX would reject `<T>x` assertions, which .ts files may use.\n plugins: /\\.[cm]?ts$/i.test(filename)\n ? ['typescript']\n : ['typescript', 'jsx'],\n }).program.body;\n } catch {\n return undefined;\n }\n}\n\nexport function toRelativeImport(\n fromDirectory: string,\n toPath: string\n): string {\n const relativePath = path\n .relative(fromDirectory, toPath)\n .split(path.sep)\n .join(path.posix.sep);\n return relativePath.startsWith('.') ? relativePath : `./${relativePath}`;\n}\n\nfunction getEntryPath(appDirectory: string, source: string): string {\n const sourcePath = source.replace(/[?#].*$/, '');\n return sourcePath.startsWith('/')\n ? path.resolve(appDirectory, `.${sourcePath}`)\n : path.resolve(appDirectory, sourcePath);\n}\n\nfunction getBootstrapEntry(bootstrap: string): string | undefined {\n return bootstrap.match(/await\\s+import\\(\\s*(['\"])([^'\"]+)\\1\\s*\\)/)?.[2];\n}\n\nfunction getModuleEntry(indexHtml: string): {\n script: string;\n source: string;\n} {\n const moduleScripts = indexHtml.match(\n /<script\\b[^>]*\\btype=(['\"])module\\1[^>]*>\\s*<\\/script>/gi\n );\n for (const script of moduleScripts ?? []) {\n const source = script.match(/\\bsrc=(['\"])([^'\"]+)\\1/i)?.[2];\n if (source) return { script, source };\n }\n\n throw new Error(\n createDiagnosticMessage({\n source: 'gt',\n severity: 'Error',\n whatHappened: 'No Vite module entry was found in index.html',\n fix: 'Add a module script for the app entry and rerun `npx gt@latest`',\n })\n );\n}\n\n/**\n * Reads the Vite entry and bootstrap without writing, so setup can report an\n * unsupported layout before changing any file.\n */\nexport async function inspectViteSPA(appDirectory: string) {\n const indexHtmlPath = path.join(appDirectory, 'index.html');\n const sourceDirectory = path.join(appDirectory, defaultSourceDirectory);\n if (!fs.existsSync(indexHtmlPath)) {\n throw new Error(\n createDiagnosticMessage({\n source: 'gt',\n severity: 'Error',\n whatHappened: 'This is not a Vite single-page app',\n why: 'index.html was not found',\n reassurance: 'Nothing was changed',\n fix: 'Rerun `npx gt@latest init` with `--framework` set to your framework, or set up GT manually',\n })\n );\n }\n const indexHtml = await fs.promises.readFile(indexHtmlPath, 'utf8');\n const { script, source } = getModuleEntry(indexHtml);\n const declaredEntryPath = getEntryPath(appDirectory, source);\n const declaredEntryImport = toRelativeImport(\n sourceDirectory,\n declaredEntryPath\n ).replace(/\\.(?:[cm]?[jt]sx?)$/i, '');\n const configuredBootstrap = source.match(\n /^\\/?src\\/(gt-entry\\.ts|gt-bootstrap\\.ts)(?:[?#].*)?$/\n )?.[1];\n let customBootstrap: string | undefined;\n if (!configuredBootstrap && fs.existsSync(declaredEntryPath)) {\n const entry = await fs.promises.readFile(declaredEntryPath, 'utf8');\n const mentionsInitializer = entry.includes('initializeGTSPA');\n // Unparseable entries fall back to the text check: a false positive only\n // asks for manual review, while a miss would initialize GT twice.\n const importsInitializer =\n parseModule(entry, declaredEntryPath)?.some(\n (statement) =>\n statement.type === 'ImportDeclaration' &&\n statement.source.value === Libraries.GT_REACT &&\n statement.importKind !== 'type' &&\n statement.specifiers.some(\n (specifier) =>\n (specifier.type === 'ImportNamespaceSpecifier' &&\n mentionsInitializer) ||\n (specifier.type === 'ImportSpecifier' &&\n specifier.importKind !== 'type' &&\n specifier.imported.type === 'Identifier' &&\n specifier.imported.name === 'initializeGTSPA')\n )\n ) ?? mentionsInitializer;\n if (importsInitializer) {\n customBootstrap = path.relative(appDirectory, declaredEntryPath);\n }\n }\n const isAlreadyConfigured = configuredBootstrap !== undefined;\n const bootstrapFilename =\n configuredBootstrap ??\n (declaredEntryImport === './gt-entry'\n ? alternateBootstrapFilename\n : defaultBootstrapFilename);\n const bootstrapPath = path.join(sourceDirectory, bootstrapFilename);\n let existingBootstrap: string | undefined;\n\n if (!customBootstrap && fs.existsSync(bootstrapPath)) {\n existingBootstrap = await fs.promises.readFile(bootstrapPath, 'utf8');\n if (!existingBootstrap.includes('initializeGTSPA')) {\n throw new Error(getBootstrapConflictError(bootstrapFilename));\n }\n }\n\n const entryImport = isAlreadyConfigured\n ? existingBootstrap && getBootstrapEntry(existingBootstrap)\n : declaredEntryImport;\n if (!entryImport) {\n throw new Error(\n createDiagnosticMessage({\n source: 'gt',\n severity: 'Error',\n whatHappened: 'The existing Vite bootstrap has no app entry import',\n fix: 'Restore the app entry import and rerun `npx gt@latest`',\n })\n );\n }\n return {\n indexHtmlPath,\n sourceDirectory,\n indexHtml,\n script,\n source,\n isAlreadyConfigured,\n customBootstrap,\n bootstrapFilename,\n bootstrapPath,\n entryImport,\n };\n}\n\nexport type ViteLoaderResult =\n | 'created'\n | 'updated'\n | 'unchanged'\n | 'custom'\n | 'missing';\n\n/**\n * Points the generated loadTranslations.ts in sourceDirectory (src by\n * default) at translationsDir and adds empty locale stubs. Only a template\n * matching the previous config is refreshed; other existing loaders are left\n * unchanged. An absent loader is only created with `create`.\n */\nexport async function writeViteLoader({\n appDirectory,\n defaultLocale,\n locales,\n translationsDir,\n previousTranslationsDir,\n create,\n sourceDirectory = defaultSourceDirectory,\n}: Omit<SetupViteSPAOptions, 'configFilepath' | 'translationsDir'> & {\n translationsDir: string;\n create: boolean;\n sourceDirectory?: string;\n}): Promise<ViteLoaderResult> {\n const loaderDirectory = path.join(appDirectory, sourceDirectory);\n const translationsPath = path.resolve(appDirectory, translationsDir);\n const loaderPath = path.join(loaderDirectory, 'loadTranslations.ts');\n const existingLoader = fs.existsSync(loaderPath)\n ? await fs.promises.readFile(loaderPath, 'utf8')\n : undefined;\n if (existingLoader === undefined && !create) return 'missing';\n const content = getLoaderContent(\n toRelativeImport(loaderDirectory, translationsPath)\n );\n const previousContent =\n previousTranslationsDir === undefined\n ? undefined\n : getLoaderContent(\n toRelativeImport(\n loaderDirectory,\n path.resolve(appDirectory, previousTranslationsDir)\n )\n );\n const normalizedLoader = existingLoader?.replace(/\\r\\n/g, '\\n').trimEnd();\n const custom =\n existingLoader !== undefined &&\n normalizedLoader !== content.trimEnd() &&\n normalizedLoader !== previousContent?.trimEnd();\n\n // Stubs first, so a directory failure leaves no loader pointing at it.\n await fs.promises.mkdir(translationsPath, { recursive: true });\n for (const locale of new Set(locales)) {\n if (locale === defaultLocale) continue;\n const stubPath = path.join(translationsPath, `${locale}.json`);\n if (!fs.existsSync(stubPath)) {\n await fs.promises.writeFile(stubPath, '{}\\n');\n }\n }\n if (custom) return 'custom';\n if (existingLoader === content) return 'unchanged';\n await fs.promises.writeFile(loaderPath, content);\n return existingLoader === undefined ? 'created' : 'updated';\n}\n\nexport type ViteLoaderExport = 'default' | 'loadTranslations' | undefined;\n\n/** The generated loader's export, or a custom loader's own if it has one. */\nexport async function getViteLoaderExport(\n appDirectory: string,\n loader: ViteLoaderResult,\n sourceDirectory = defaultSourceDirectory\n): Promise<ViteLoaderExport> {\n return loader === 'custom'\n ? getLoaderExport(\n await fs.promises.readFile(\n path.join(appDirectory, sourceDirectory, 'loadTranslations.ts'),\n 'utf8'\n )\n )\n : 'default';\n}\n\nfunction getLoaderExport(content: string): ViteLoaderExport {\n const statements = parseModule(content, 'loadTranslations.ts');\n if (!statements) return undefined;\n const names = new Set<string>();\n for (const statement of statements) {\n // @babel/types omits the interface form the parser emits, which is erased\n // at compile time and leaves no runtime default export.\n if (\n statement.type === 'ExportDefaultDeclaration' &&\n (statement.declaration.type as string) !== 'TSInterfaceDeclaration'\n )\n names.add('default');\n if (\n statement.type !== 'ExportNamedDeclaration' ||\n statement.exportKind === 'type'\n )\n continue;\n for (const specifier of statement.specifiers) {\n if (\n specifier.type === 'ExportSpecifier' &&\n specifier.exportKind !== 'type'\n ) {\n names.add(\n specifier.exported.type === 'Identifier'\n ? specifier.exported.name\n : specifier.exported.value\n );\n }\n }\n const declaration = statement.declaration;\n if (\n declaration?.type === 'FunctionDeclaration' &&\n !declaration.declare &&\n declaration.id\n ) {\n names.add(declaration.id.name);\n }\n if (declaration?.type === 'VariableDeclaration' && !declaration.declare) {\n for (const variable of declaration.declarations) {\n if (variable.id.type === 'Identifier') names.add(variable.id.name);\n }\n }\n }\n if (names.has('default')) return 'default';\n if (names.has('loadTranslations')) return 'loadTranslations';\n return undefined;\n}\n\nexport async function setupViteSPA({\n appDirectory,\n configFilepath,\n defaultLocale,\n locales,\n translationsDir,\n previousTranslationsDir,\n}: SetupViteSPAOptions): Promise<{\n loader?: ViteLoaderResult;\n manualAction?: string;\n}> {\n const {\n indexHtmlPath,\n sourceDirectory,\n indexHtml,\n script,\n source,\n isAlreadyConfigured,\n customBootstrap,\n bootstrapFilename,\n bootstrapPath,\n entryImport,\n } = await inspectViteSPA(appDirectory);\n\n // An app-owned initializer may have custom imports and options. Nesting a\n // generated initializer around it would initialize GT twice.\n if (customBootstrap) {\n return {\n manualAction: `Verify the existing GT bootstrap ${customBootstrap} uses ${configFilepath}${translationsDir ? ` and loads translations from ${translationsDir}` : ' with CDN loading'}`,\n };\n }\n\n await fs.promises.mkdir(sourceDirectory, { recursive: true });\n\n let loadTranslationsImport = '';\n let loadTranslationsOption = 'gtConfig';\n let loader: ViteLoaderResult | undefined;\n if (translationsDir) {\n loader = await writeViteLoader({\n appDirectory,\n defaultLocale,\n locales,\n translationsDir,\n previousTranslationsDir,\n create: true,\n });\n const loaderExport = await getViteLoaderExport(appDirectory, loader);\n if (!loaderExport) {\n return {\n loader,\n manualAction: `Update your custom src/loadTranslations.ts to load translations from ${translationsDir} and export a default or named loadTranslations function, then rerun gt init`,\n };\n }\n loadTranslationsImport =\n loaderExport === 'default'\n ? \"import loadTranslations from './loadTranslations';\\n\"\n : \"import { loadTranslations } from './loadTranslations';\\n\";\n loadTranslationsOption = '{ ...gtConfig, loadTranslations }';\n }\n\n const configImport = toRelativeImport(\n sourceDirectory,\n path.resolve(appDirectory, configFilepath)\n );\n await fs.promises.writeFile(\n bootstrapPath,\n `import { initializeGTSPA } from '${Libraries.GT_REACT}';\nimport gtConfig from '${configImport}';\n${loadTranslationsImport}\nawait initializeGTSPA(${loadTranslationsOption});\n\nawait import('${entryImport}');\n`\n );\n\n if (!isAlreadyConfigured) {\n const updatedScript = script.replace(source, `/src/${bootstrapFilename}`);\n await fs.promises.writeFile(\n indexHtmlPath,\n indexHtml.replace(script, updatedScript)\n );\n }\n\n logger.success('Configured initializeGTSPA for this Vite application.');\n return {\n loader,\n ...(loader === 'custom' && {\n manualAction: `Verify your preserved custom src/loadTranslations.ts loads translations from ${translationsDir}`,\n }),\n };\n}\n"],"mappings":";;;;;;;AAgBA,MAAM,2BAA2B;AACjC,MAAM,6BAA6B;AACnC,MAAM,yBAAyB;AAE/B,SAAS,0BAA0B,UAA0B;AAC3D,QAAO,wBAAwB;EAC7B,QAAQ;EACR,UAAU;EACV,cAAc;EACd,KAAK,yCAAyC,SAAS;EACvD,KAAK;EACN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BAAyB;CAC7B,IAAI,yBAAyB;CAC7B,IAAI;AACJ,KAAI,iBAAiB;AACnB,WAAS,MAAM,gBAAgB;GAC7B;GACA;GACA;GACA;GACA;GACA,QAAQ;GACT,CAAC;EACF,MAAM,eAAe,MAAM,oBAAoB,cAAc,OAAO;AACpE,MAAI,CAAC,aACH,QAAO;GACL;GACA,cAAc,wEAAwE,gBAAgB;GACvG;AAEH,2BACE,iBAAiB,YACb,yDACA;AACN,2BAAyB;;CAG3B,MAAM,eAAe,iBACnB,iBACA,KAAK,QAAQ,cAAc,eAAe,CAC3C;AACD,OAAM,GAAG,SAAS,UAChB,eACA;wBACoB,aAAa;EACnC,uBAAuB;wBACD,uBAAuB;;gBAE/B,YAAY;EAEzB;AAED,KAAI,CAAC,qBAAqB;EACxB,MAAM,gBAAgB,OAAO,QAAQ,QAAQ,QAAQ,oBAAoB;AACzE,QAAM,GAAG,SAAS,UAChB,eACA,UAAU,QAAQ,QAAQ,cAAc,CACzC;;AAGH,QAAO,QAAQ,wDAAwD;AACvE,QAAO;EACL;EACA,GAAI,WAAW,YAAY,EACzB,cAAc,gFAAgF,mBAC/F;EACF"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "gt",
|
|
3
|
-
"version": "2.25.
|
|
3
|
+
"version": "2.25.2",
|
|
4
4
|
"main": "dist/index.js",
|
|
5
5
|
"bin": "bin/main.js",
|
|
6
6
|
"files": [
|
|
@@ -117,10 +117,10 @@
|
|
|
117
117
|
"yaml": "^2.8.0",
|
|
118
118
|
"@generaltranslation/format": "0.1.9",
|
|
119
119
|
"@generaltranslation/icu": "0.1.2",
|
|
120
|
-
"@generaltranslation/python-extractor": "0.2.
|
|
121
|
-
"@generaltranslation/supported-locales": "2.1.
|
|
122
|
-
"@generaltranslation/vue-extractor": "0.1.
|
|
123
|
-
"generaltranslation": "9.5.
|
|
120
|
+
"@generaltranslation/python-extractor": "0.2.60",
|
|
121
|
+
"@generaltranslation/supported-locales": "2.1.41",
|
|
122
|
+
"@generaltranslation/vue-extractor": "0.1.19",
|
|
123
|
+
"generaltranslation": "9.5.5",
|
|
124
124
|
"gt-remark": "1.0.12"
|
|
125
125
|
},
|
|
126
126
|
"devDependencies": {
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export {};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"edits.js","names":[],"sources":["../../../../src/setup/buildTools/tanstackStart/edits.ts"],"sourcesContent":["// Offset-based source edits that follow the file's own code style.\nimport * as t from '@babel/types';\n\ntype Edit = { start: number; end?: number; text: string };\n\nexport type CodeStyle = {\n quote: string;\n semi: string;\n eol: string;\n indent: string;\n};\n\nfunction getImports(statements: t.Statement[]): t.ImportDeclaration[] {\n return statements.filter(\n (statement): statement is t.ImportDeclaration =>\n statement.type === 'ImportDeclaration'\n );\n}\n\n/** Generated lines follow the file's last import, so they read as its own. */\nexport function getCodeStyle(\n content: string,\n statements: t.Statement[]\n): CodeStyle {\n const lastImport = getImports(statements).at(-1);\n return {\n quote: lastImport ? content[lastImport.source.start!] : \"'\",\n semi:\n lastImport &&\n !content.slice(lastImport.start!, lastImport.end!).endsWith(';')\n ? ''\n : ';',\n eol: content.includes('\\r\\n') ? '\\r\\n' : '\\n',\n // Skips JSDoc continuation lines, whose ` * ` is not an indent unit.\n indent: /^([ \\t]+)[^\\s*]/m.exec(content)?.[1] ?? ' ',\n };\n}\n\nfunction getLineStart(content: string, position: number): number {\n return content.lastIndexOf('\\n', position - 1) + 1;\n}\n\nexport function getLineIndent(content: string, position: number): string {\n return /^[ \\t]*/.exec(content.slice(getLineStart(content, position)))![0];\n}\n\n/** The indent before position, or undefined when code precedes it. */\nexport function getOwnLineIndent(\n content: string,\n position: number\n): string | undefined {\n const prefix = content.slice(getLineStart(content, position), position);\n return /^[ \\t]*$/.test(prefix) ? prefix : undefined;\n}\n\n/** Inserts at original offsets, last first, so earlier offsets stay valid. */\nexport function applyEdits(content: string, edits: Edit[]): string {\n return [...edits]\n .sort((a, b) => b.start - a.start)\n .reduce(\n (result, { start, end, text }) =>\n result.slice(0, start) + text + result.slice(end ?? start),\n content\n );\n}\n\nexport function getImportEdit(\n statements: t.Statement[],\n lines: string[],\n eol: string\n): Edit {\n const lastImport = getImports(statements).at(-1);\n if (!lastImport) return { start: 0, text: lines.join(eol) + eol + eol };\n // A same-line comment such as `// eslint-disable-line` stays on its import.\n const lineComment = lastImport.trailingComments\n ?.filter((comment) => comment.loc!.start.line === lastImport.loc!.end.line)\n .at(-1);\n return {\n start: lineComment?.end ?? lastImport.end!,\n text: eol + lines.join(eol),\n };\n}\n"],"mappings":";AAYA,SAAS,WAAW,YAAkD;AACpE,QAAO,WAAW,QACf,cACC,UAAU,SAAS,oBACtB;;;AAIH,SAAgB,aACd,SACA,YACW;CACX,MAAM,aAAa,WAAW,WAAW,CAAC,GAAG,GAAG;AAChD,QAAO;EACL,OAAO,aAAa,QAAQ,WAAW,OAAO,SAAU;EACxD,MACE,cACA,CAAC,QAAQ,MAAM,WAAW,OAAQ,WAAW,IAAK,CAAC,SAAS,IAAI,GAC5D,KACA;EACN,KAAK,QAAQ,SAAS,OAAO,GAAG,SAAS;EAEzC,QAAQ,mBAAmB,KAAK,QAAQ,GAAG,MAAM;EAClD;;AAGH,SAAS,aAAa,SAAiB,UAA0B;AAC/D,QAAO,QAAQ,YAAY,MAAM,WAAW,EAAE,GAAG;;AAGnD,SAAgB,cAAc,SAAiB,UAA0B;AACvE,QAAO,UAAU,KAAK,QAAQ,MAAM,aAAa,SAAS,SAAS,CAAC,CAAC,CAAE;;;AAIzE,SAAgB,iBACd,SACA,UACoB;CACpB,MAAM,SAAS,QAAQ,MAAM,aAAa,SAAS,SAAS,EAAE,SAAS;AACvE,QAAO,WAAW,KAAK,OAAO,GAAG,SAAS,KAAA;;;AAI5C,SAAgB,WAAW,SAAiB,OAAuB;AACjE,QAAO,CAAC,GAAG,MAAM,CACd,MAAM,GAAG,MAAM,EAA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