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
package/dist/auth/oauth.js
CHANGED
|
@@ -18,7 +18,20 @@ const TOKEN_REFRESH_BUFFER_MS = 3e4;
|
|
|
18
18
|
function oauthFailure(whatHappened, fix, details) {
|
|
19
19
|
return new UserAuthError("oauth", whatHappened, fix, details);
|
|
20
20
|
}
|
|
21
|
+
/**
|
|
22
|
+
* An abort or a timeout, raw from a signal check or wrapped by the client
|
|
23
|
+
* library, which rethrows a DOMException from its own operations as a
|
|
24
|
+
* ClientError coded OAUTH_ABORT or OAUTH_TIMEOUT.
|
|
25
|
+
*/
|
|
26
|
+
function isCancellation(error) {
|
|
27
|
+
if (error instanceof oidc.ClientError) return error.code === "OAUTH_ABORT" || error.code === "OAUTH_TIMEOUT";
|
|
28
|
+
return error instanceof Error && ["AbortError", "TimeoutError"].includes(error.name);
|
|
29
|
+
}
|
|
30
|
+
function cancelledFailure() {
|
|
31
|
+
return oauthFailure("Sign in was cancelled or timed out", "Run `gt login` again");
|
|
32
|
+
}
|
|
21
33
|
function oauthError(error, fallback) {
|
|
34
|
+
if (isCancellation(error)) return cancelledFailure();
|
|
22
35
|
if (error instanceof oidc.AuthorizationResponseError || error instanceof oidc.ResponseBodyError) return oauthFailure({
|
|
23
36
|
access_denied: "Sign in was denied in the browser",
|
|
24
37
|
expired_token: "The sign-in code expired before it was approved",
|
|
@@ -28,7 +41,6 @@ function oauthError(error, fallback) {
|
|
|
28
41
|
unauthorized_client: "This authorization server does not recognize the gt CLI"
|
|
29
42
|
}[error.error] ?? fallback, ["invalid_client", "unauthorized_client"].includes(error.error) ? "Check GT_AUTH_URL or update the server" : "Run `gt login` again", error.error === "invalid_scope" ? error.error_description : void 0);
|
|
30
43
|
if (error instanceof oidc.ClientError) return oauthFailure(`${fallback}${error.cause instanceof Response ? ` (HTTP ${error.cause.status})` : ""}`, "Check the authorization server and try again", error.code);
|
|
31
|
-
if (error instanceof Error && ["AbortError", "TimeoutError"].includes(error.name)) return oauthFailure("Sign in was cancelled or timed out", "Run `gt login` again");
|
|
32
44
|
return oauthFailure(fallback, "Check the authorization server and try again");
|
|
33
45
|
}
|
|
34
46
|
function assertEndpoint(url, issuer) {
|
|
@@ -122,6 +134,31 @@ async function loginWithDeviceCode(options) {
|
|
|
122
134
|
await writeOAuthTokens(tokens, authBaseUrl);
|
|
123
135
|
return tokens;
|
|
124
136
|
}
|
|
137
|
+
/** How long the callback page waits to learn the account's name. */
|
|
138
|
+
const ACCOUNT_LOOKUP_TIMEOUT_MS = 3e3;
|
|
139
|
+
/**
|
|
140
|
+
* The email, else the profile name, from the userinfo endpoint, within the
|
|
141
|
+
* lookup budget; undefined when the endpoint fails, stalls, or returns
|
|
142
|
+
* claims that are not strings. Never throws. When the budget expires the
|
|
143
|
+
* request itself is aborted through `cancel`, which the configuration's
|
|
144
|
+
* fetch honors, so a stalled endpoint holds no socket open after the page
|
|
145
|
+
* has been served and the command can exit.
|
|
146
|
+
*/
|
|
147
|
+
async function lookupAccountName(config, accessToken, subject, cancel) {
|
|
148
|
+
let timer;
|
|
149
|
+
const budget = new Promise((resolve) => {
|
|
150
|
+
timer = setTimeout(() => {
|
|
151
|
+
cancel.abort();
|
|
152
|
+
resolve(void 0);
|
|
153
|
+
}, ACCOUNT_LOOKUP_TIMEOUT_MS);
|
|
154
|
+
});
|
|
155
|
+
const lookup = oidc.fetchUserInfo(config, accessToken, subject).then((user) => typeof user.email === "string" ? user.email : typeof user.name === "string" ? user.name : void 0).catch(() => void 0);
|
|
156
|
+
try {
|
|
157
|
+
return await Promise.race([lookup, budget]);
|
|
158
|
+
} finally {
|
|
159
|
+
clearTimeout(timer);
|
|
160
|
+
}
|
|
161
|
+
}
|
|
125
162
|
/** Browser S256/loopback, or device login for SSH, --no-browser and bind failure. */
|
|
126
163
|
async function login(options = {}) {
|
|
127
164
|
if (options.noBrowser || process.env.SSH_CONNECTION || process.env.SSH_CLIENT || process.env.SSH_TTY) return loginWithDeviceCode({
|
|
@@ -130,10 +167,12 @@ async function login(options = {}) {
|
|
|
130
167
|
});
|
|
131
168
|
const authBaseUrl = options.authBaseUrl ?? getAuthBaseUrl();
|
|
132
169
|
const resource = loginResource(options);
|
|
170
|
+
const cancelLookup = new AbortController();
|
|
171
|
+
const signal = options.signal ? AbortSignal.any([options.signal, cancelLookup.signal]) : cancelLookup.signal;
|
|
133
172
|
const config = await configuration({
|
|
134
173
|
...options,
|
|
135
174
|
authBaseUrl
|
|
136
|
-
}).catch((error) => {
|
|
175
|
+
}, signal).catch((error) => {
|
|
137
176
|
throw oauthError(error, "Could not discover the authorization server");
|
|
138
177
|
});
|
|
139
178
|
const loopback = await startLoopbackServer().catch(() => void 0);
|
|
@@ -150,6 +189,7 @@ async function login(options = {}) {
|
|
|
150
189
|
code_challenge_method: "S256"
|
|
151
190
|
});
|
|
152
191
|
assertEndpoint(authorizationUrl, new URL(authBaseUrl));
|
|
192
|
+
const denials = /* @__PURE__ */ new WeakSet();
|
|
153
193
|
const callback = loopback.waitForCallback(async (callbackUrl) => {
|
|
154
194
|
const tokens = {
|
|
155
195
|
...parseTokens(await oidc.authorizationCodeGrant(config, callbackUrl, {
|
|
@@ -157,17 +197,27 @@ async function login(options = {}) {
|
|
|
157
197
|
expectedState: state,
|
|
158
198
|
idTokenExpected: true
|
|
159
199
|
}, { resource }).catch((error) => {
|
|
160
|
-
|
|
200
|
+
const failure = oauthError(error, "Failed to authenticate via web browser");
|
|
201
|
+
if (error instanceof oidc.AuthorizationResponseError && error.error === "access_denied") denials.add(failure);
|
|
202
|
+
throw failure;
|
|
161
203
|
})),
|
|
162
204
|
resource
|
|
163
205
|
};
|
|
206
|
+
const account = await lookupAccountName(config, tokens.accessToken, tokens.subject, cancelLookup);
|
|
207
|
+
if (options.signal?.aborted) throw cancelledFailure();
|
|
164
208
|
await writeOAuthTokens(tokens, authBaseUrl);
|
|
165
|
-
return
|
|
166
|
-
|
|
209
|
+
return {
|
|
210
|
+
tokens,
|
|
211
|
+
account
|
|
212
|
+
};
|
|
213
|
+
}, options.timeoutMs, {
|
|
214
|
+
describe: (outcome) => ({ account: outcome.account }),
|
|
215
|
+
failure: (error) => error instanceof Error && denials.has(error) ? "denied" : "failed"
|
|
216
|
+
});
|
|
167
217
|
callback.catch(() => void 0);
|
|
168
218
|
options.onAuthorizationUrl?.(authorizationUrl.href);
|
|
169
219
|
(options.openBrowser ?? open)(authorizationUrl.href).catch(() => void 0);
|
|
170
|
-
return await callback;
|
|
220
|
+
return (await callback).tokens;
|
|
171
221
|
} finally {
|
|
172
222
|
loopback.close();
|
|
173
223
|
}
|
|
@@ -257,6 +307,6 @@ async function whoAmI(options = {}) {
|
|
|
257
307
|
}
|
|
258
308
|
}
|
|
259
309
|
//#endregion
|
|
260
|
-
export { createUserTokenProvider, hasLogin, login, logout, whoAmI };
|
|
310
|
+
export { ACCOUNT_LOOKUP_TIMEOUT_MS, createUserTokenProvider, hasLogin, login, logout, whoAmI };
|
|
261
311
|
|
|
262
312
|
//# sourceMappingURL=oauth.js.map
|
package/dist/auth/oauth.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"oauth.js","names":["createDiagnosticMessage"],"sources":["../../src/auth/oauth.ts"],"sourcesContent":["import open from 'open';\nimport * as oidc from 'openid-client';\nimport type { UserTokenProvider } from 'generaltranslation/api';\nimport { createDiagnosticMessage } from 'generaltranslation/diagnostics';\nimport { defaultBaseUrl } from 'generaltranslation/internal';\nimport { GT_DASHBOARD_URL } from '../utils/constants.js';\nimport { logger } from '../console/logger.js';\nimport {\n deleteOAuthTokens,\n readOAuthTokens,\n writeOAuthTokens,\n} from './credentialStore.js';\nimport type { OAuthTokens } from './credentialStore.js';\nimport { UserAuthError, loginRequiredError } from './errors.js';\nimport { startLoopbackServer } from './loopback.js';\n\n/** Public native client seeded by the authorization server; never a secret. */\nconst OAUTH_CLIENT_ID = 'gt-cli';\n/** Explicit on both grants: identity, refresh and the user's dashboard permissions.\n * Must match the seeded gt-cli client; the device endpoint does not default scope.\n */\nconst OAUTH_SCOPE = 'openid profile offline_access gt:*';\n// Refresh before expiry so an in-flight request does not carry an expired token.\nconst TOKEN_REFRESH_BUFFER_MS = 30_000;\n\nexport type DeviceCode = {\n userCode: string;\n verificationUri: string;\n verificationUriComplete?: string;\n};\nexport type UserInfo = { email?: string; name?: string; sub: string };\ntype OAuthRequestOptions = { authBaseUrl?: string; fetch?: typeof fetch };\nexport type UserTokenProviderOptions = OAuthRequestOptions & {\n /** API the requests go to; must match the resource the login was issued for. */\n baseUrl: string;\n};\nexport type LoginOptions = OAuthRequestOptions & {\n /** API the token is issued for; GT_API_URL overrides, then the public API. */\n baseUrl?: string;\n noBrowser?: boolean;\n onDeviceCode?: (deviceCode: DeviceCode) => void;\n signal?: AbortSignal;\n onAuthorizationUrl?: (url: string) => void;\n openBrowser?: (url: string) => Promise<unknown>;\n timeoutMs?: number;\n};\n\nfunction oauthFailure(\n whatHappened: string,\n fix?: string,\n details?: string\n): UserAuthError {\n return new UserAuthError('oauth', whatHappened, fix, details);\n}\n\nfunction oauthError(error: unknown, fallback: string): UserAuthError {\n if (\n error instanceof oidc.AuthorizationResponseError ||\n error instanceof oidc.ResponseBodyError\n ) {\n const descriptions: Record<string, string> = {\n access_denied: 'Sign in was denied in the browser',\n expired_token: 'The sign-in code expired before it was approved',\n invalid_scope: 'The authorization server rejected the requested scopes',\n invalid_grant: 'Your login or sign-in code expired or was already used',\n invalid_client: 'This authorization server does not recognize the gt CLI',\n unauthorized_client:\n 'This authorization server does not recognize the gt CLI',\n };\n return oauthFailure(\n descriptions[error.error] ?? fallback,\n ['invalid_client', 'unauthorized_client'].includes(error.error)\n ? 'Check GT_AUTH_URL or update the server'\n : 'Run `gt login` again',\n // Scope descriptions are useful configuration diagnostics, not token data.\n error.error === 'invalid_scope' ? error.error_description : undefined\n );\n }\n if (error instanceof oidc.ClientError) {\n const status =\n error.cause instanceof Response ? ` (HTTP ${error.cause.status})` : '';\n return oauthFailure(\n `${fallback}${status}`,\n 'Check the authorization server and try again',\n error.code\n );\n }\n if (\n error instanceof Error &&\n ['AbortError', 'TimeoutError'].includes(error.name)\n ) {\n return oauthFailure(\n 'Sign in was cancelled or timed out',\n 'Run `gt login` again'\n );\n }\n // Do not expose transport causes, callback URLs or token responses.\n return oauthFailure(fallback, 'Check the authorization server and try again');\n}\n\nfunction assertEndpoint(url: URL, issuer: URL): void {\n if (\n url.username ||\n url.password ||\n url.hash ||\n (url.protocol !== 'https:' &&\n !(issuer.protocol === 'http:' && url.origin === issuer.origin))\n ) {\n throw oauthFailure(\n 'The authorization server supplied an unsafe endpoint',\n 'Use HTTPS, or same-origin local development HTTP'\n );\n }\n}\n\nasync function configuration(\n {\n authBaseUrl = getAuthBaseUrl(),\n fetch: fetchImplementation = globalThis.fetch,\n }: OAuthRequestOptions,\n signal?: AbortSignal\n): Promise<oidc.Configuration> {\n const issuer = new URL(authBaseUrl);\n const local =\n issuer.hostname === 'localhost' ||\n issuer.hostname.endsWith('.localhost') ||\n issuer.hostname === '127.0.0.1' ||\n issuer.hostname === '[::1]';\n if (\n issuer.username ||\n issuer.password ||\n issuer.search ||\n issuer.hash ||\n (issuer.protocol !== 'https:' && !(issuer.protocol === 'http:' && local))\n ) {\n throw oauthFailure(\n 'GT_AUTH_URL is not a trusted issuer URL',\n 'Use HTTPS, or a local development HTTP issuer without credentials, query or fragment'\n );\n }\n return oidc.discovery(issuer, OAUTH_CLIENT_ID, undefined, oidc.None(), {\n execute:\n issuer.protocol === 'http:'\n ? [oidc.enableNonRepudiationChecks, oidc.allowInsecureRequests]\n : [oidc.enableNonRepudiationChecks],\n [oidc.customFetch]: (url, init) => {\n assertEndpoint(new URL(url), issuer);\n return fetchImplementation(url, {\n ...init,\n // Include operation cancellation in JWKS fetches as well as token requests.\n signal: signal\n ? AbortSignal.any([signal, ...(init.signal ? [init.signal] : [])])\n : init.signal,\n body:\n init.body instanceof Uint8Array\n ? new Uint8Array(init.body)\n : init.body,\n });\n },\n });\n}\n\nfunction parseTokens(\n result: oidc.TokenEndpointResponse & oidc.TokenEndpointResponseHelpers,\n previous?: OAuthTokens\n): Omit<OAuthTokens, 'resource'> {\n const subject = result.claims()?.sub ?? previous?.subject;\n if (!subject || (previous && subject !== previous.subject)) {\n throw oauthFailure(\n 'The authorization server did not confirm the expected account identity',\n 'Run `gt login` again'\n );\n }\n if (\n result.token_type !== 'bearer' ||\n typeof result.expires_in !== 'number' ||\n !Number.isFinite(result.expires_in) ||\n result.expires_in <= 0\n ) {\n throw oauthFailure(\n 'The authorization server returned an unsupported token type or lifetime'\n );\n }\n return {\n accessToken: result.access_token,\n expiresAt: Date.now() + result.expires_in * 1000,\n refreshToken: result.refresh_token ?? previous?.refreshToken ?? '',\n scope: result.scope ?? previous?.scope ?? OAUTH_SCOPE,\n tokenType: result.token_type,\n subject,\n };\n}\n\nfunction getAuthBaseUrl(): string {\n return (process.env.GT_AUTH_URL ?? `${GT_DASHBOARD_URL}/api/auth`).replace(\n /\\/$/,\n ''\n );\n}\n\n/** Resource indicators are the API origin serialized as a URL href (trailing slash). */\nfunction toApiResource(baseUrl: string): string {\n return new URL(baseUrl).href;\n}\n\nfunction loginResource(options: LoginOptions): string {\n return toApiResource(\n process.env.GT_API_URL ?? options.baseUrl ?? defaultBaseUrl\n );\n}\n\nasync function loginWithDeviceCode(\n options: LoginOptions\n): Promise<OAuthTokens> {\n if (options.noBrowser && !options.onDeviceCode) {\n throw oauthFailure(\n 'Device login needs a way to display the verification code',\n 'Provide onDeviceCode when using noBrowser'\n );\n }\n const authBaseUrl = options.authBaseUrl ?? getAuthBaseUrl();\n const resource = loginResource(options);\n const lifetime = new AbortController();\n const signal = options.signal\n ? AbortSignal.any([options.signal, lifetime.signal])\n : lifetime.signal;\n let timer: ReturnType<typeof setTimeout> | undefined;\n let result: oidc.TokenEndpointResponse & oidc.TokenEndpointResponseHelpers;\n try {\n signal.throwIfAborted();\n const config = await configuration({ ...options, authBaseUrl }, signal);\n const started = Date.now();\n const response = await oidc.initiateDeviceAuthorization(config, {\n scope: OAUTH_SCOPE,\n resource,\n });\n const deadline = started + response.expires_in * 1000;\n const checkLifetime = () => {\n if (Date.now() >= deadline)\n lifetime.abort(new DOMException('Device code expired', 'TimeoutError'));\n signal.throwIfAborted();\n };\n checkLifetime();\n timer = setTimeout(\n () =>\n lifetime.abort(new DOMException('Device code expired', 'TimeoutError')),\n deadline - Date.now()\n );\n assertEndpoint(new URL(response.verification_uri), new URL(authBaseUrl));\n if (response.verification_uri_complete)\n assertEndpoint(\n new URL(response.verification_uri_complete),\n new URL(authBaseUrl)\n );\n options.onDeviceCode?.({\n userCode: response.user_code,\n verificationUri: response.verification_uri,\n verificationUriComplete: response.verification_uri_complete,\n });\n checkLifetime();\n if (!options.noBrowser) {\n void (options.openBrowser ?? open)(\n response.verification_uri_complete ?? response.verification_uri\n ).catch(() => undefined);\n }\n result = await oidc.pollDeviceAuthorizationGrant(\n config,\n response,\n { resource },\n { signal }\n );\n checkLifetime();\n } catch (error) {\n throw oauthError(error, 'Could not complete device sign in');\n } finally {\n clearTimeout(timer);\n }\n const tokens = { ...parseTokens(result), resource };\n await writeOAuthTokens(tokens, authBaseUrl);\n return tokens;\n}\n\n/** Browser S256/loopback, or device login for SSH, --no-browser and bind failure. */\nexport async function login(options: LoginOptions = {}): Promise<OAuthTokens> {\n if (\n options.noBrowser ||\n process.env.SSH_CONNECTION ||\n process.env.SSH_CLIENT ||\n process.env.SSH_TTY\n ) {\n return loginWithDeviceCode({ ...options, noBrowser: true });\n }\n const authBaseUrl = options.authBaseUrl ?? getAuthBaseUrl();\n const resource = loginResource(options);\n const config = await configuration({ ...options, authBaseUrl }).catch(\n (error: unknown) => {\n throw oauthError(error, 'Could not discover the authorization server');\n }\n );\n const loopback = await startLoopbackServer().catch(() => undefined);\n if (!loopback) return loginWithDeviceCode(options);\n try {\n const codeVerifier = oidc.randomPKCECodeVerifier();\n const state = oidc.randomState();\n const authorizationUrl = oidc.buildAuthorizationUrl(config, {\n redirect_uri: loopback.redirectUri,\n scope: OAUTH_SCOPE,\n resource,\n state,\n code_challenge: await oidc.calculatePKCECodeChallenge(codeVerifier),\n code_challenge_method: 'S256',\n });\n assertEndpoint(authorizationUrl, new URL(authBaseUrl));\n const callback = loopback.waitForCallback(async (callbackUrl) => {\n const result = await oidc\n .authorizationCodeGrant(\n config,\n callbackUrl,\n {\n pkceCodeVerifier: codeVerifier,\n expectedState: state,\n idTokenExpected: true,\n },\n { resource }\n )\n .catch((error: unknown) => {\n throw oauthError(error, 'Failed to authenticate via web browser');\n });\n const tokens = { ...parseTokens(result), resource };\n await writeOAuthTokens(tokens, authBaseUrl);\n return tokens;\n }, options.timeoutMs);\n // Printing/launching may fail before we await the listener.\n callback.catch(() => undefined);\n options.onAuthorizationUrl?.(authorizationUrl.href);\n void (options.openBrowser ?? open)(authorizationUrl.href).catch(\n () => undefined\n );\n return await callback;\n } finally {\n loopback.close();\n }\n}\n\nconst pendingRefreshes = new Map<string, Promise<OAuthTokens>>();\nfunction refreshTokens(options: OAuthRequestOptions): Promise<OAuthTokens> {\n const authBaseUrl = options.authBaseUrl ?? getAuthBaseUrl();\n const pending = pendingRefreshes.get(authBaseUrl);\n if (pending) return pending;\n const refresh = exchangeRefreshToken({ ...options, authBaseUrl }).finally(\n () => pendingRefreshes.delete(authBaseUrl)\n );\n pendingRefreshes.set(authBaseUrl, refresh);\n return refresh;\n}\n\nasync function exchangeRefreshToken(\n options: OAuthRequestOptions & { authBaseUrl: string }\n): Promise<OAuthTokens> {\n const current = await readOAuthTokens(options.authBaseUrl);\n if (!current?.refreshToken) throw loginRequiredError();\n const result = await (async () =>\n oidc.refreshTokenGrant(\n await configuration(options),\n current.refreshToken\n ))().catch((error: unknown) => {\n throw oauthError(error, 'Could not refresh your login');\n });\n // The grant reuses the bound resource, so the refreshed token keeps its audience.\n const tokens = {\n ...parseTokens(result, current),\n resource: current.resource,\n };\n await writeOAuthTokens(tokens, options.authBaseUrl);\n return tokens;\n}\n\nasync function validTokens(\n options: OAuthRequestOptions\n): Promise<OAuthTokens | undefined> {\n const tokens = await readOAuthTokens(options.authBaseUrl ?? getAuthBaseUrl());\n if (!tokens || tokens.expiresAt > Date.now() + TOKEN_REFRESH_BUFFER_MS)\n return tokens;\n return refreshTokens(options);\n}\n\n/** Whether a stored login exists for this API; does not refresh or contact the server. */\nexport async function hasLogin(\n options: UserTokenProviderOptions\n): Promise<boolean> {\n const tokens = await readOAuthTokens(options.authBaseUrl ?? getAuthBaseUrl());\n return tokens?.resource === toApiResource(options.baseUrl);\n}\n\n/** Construction is deliberately free of auth/storage/discovery I/O. */\nexport function createUserTokenProvider(\n options: UserTokenProviderOptions\n): UserTokenProvider {\n // Check the audience before any refresh so a stale mismatched login is\n // never rotated on behalf of the wrong API.\n const storedTokens = async (): Promise<OAuthTokens> => {\n const tokens = await readOAuthTokens(\n options.authBaseUrl ?? getAuthBaseUrl()\n );\n if (!tokens) throw loginRequiredError();\n const resource = toApiResource(options.baseUrl);\n if (tokens.resource !== resource) {\n throw new UserAuthError(\n 'resource_mismatch',\n `You are signed in to ${tokens.resource}, but this project uses ${resource}`,\n 'Run `gt login` in this project to sign in to its API'\n );\n }\n return tokens;\n };\n return {\n getAccessToken: async () => {\n const tokens = await storedTokens();\n if (tokens.expiresAt > Date.now() + TOKEN_REFRESH_BUFFER_MS)\n return tokens.accessToken;\n return (await refreshTokens(options)).accessToken;\n },\n refreshAccessToken: async () => {\n await storedTokens();\n return (await refreshTokens(options)).accessToken;\n },\n };\n}\n\nexport async function logout(options: OAuthRequestOptions = {}): Promise<void> {\n const authBaseUrl = options.authBaseUrl ?? getAuthBaseUrl();\n try {\n const tokens = await readOAuthTokens(authBaseUrl);\n if (tokens?.refreshToken)\n await oidc.tokenRevocation(\n await configuration(options),\n tokens.refreshToken,\n { token_type_hint: 'refresh_token' }\n );\n } catch {\n logger.warn(\n createDiagnosticMessage({\n source: 'gt',\n severity: 'Warning',\n whatHappened:\n 'Signed out locally, but remote session revocation could not be confirmed',\n fix: 'Revoke the session in the dashboard if needed',\n })\n );\n } finally {\n await deleteOAuthTokens(authBaseUrl);\n }\n}\n\nexport async function whoAmI(\n options: OAuthRequestOptions = {}\n): Promise<UserInfo> {\n const tokens = await validTokens(options);\n if (!tokens) throw loginRequiredError();\n try {\n const result = await oidc.fetchUserInfo(\n await configuration(options),\n tokens.accessToken,\n tokens.subject\n );\n return { sub: result.sub, email: result.email, name: result.name };\n } catch (error) {\n throw oauthError(error, 'Could not validate your account identity');\n }\n}\n"],"mappings":";;;;;;;;;;;AAiBA,MAAM,kBAAkB;;;;AAIxB,MAAM,cAAc;AAEpB,MAAM,0BAA0B;AAwBhC,SAAS,aACP,cACA,KACA,SACe;AACf,QAAO,IAAI,cAAc,SAAS,cAAc,KAAK,QAAQ;;AAG/D,SAAS,WAAW,OAAgB,UAAiC;AACnE,KACE,iBAAiB,KAAK,8BACtB,iBAAiB,KAAK,kBAWtB,QAAO,aACL;EATA,eAAe;EACf,eAAe;EACf,eAAe;EACf,eAAe;EACf,gBAAgB;EAChB,qBACE;EAGU,CAAC,MAAM,UAAU,UAC7B,CAAC,kBAAkB,sBAAsB,CAAC,SAAS,MAAM,MAAM,GAC3D,2CACA,wBAEJ,MAAM,UAAU,kBAAkB,MAAM,oBAAoB,KAAA,EAC7D;AAEH,KAAI,iBAAiB,KAAK,YAGxB,QAAO,aACL,GAAG,WAFH,MAAM,iBAAiB,WAAW,UAAU,MAAM,MAAM,OAAO,KAAK,MAGpE,gDACA,MAAM,KACP;AAEH,KACE,iBAAiB,SACjB,CAAC,cAAc,eAAe,CAAC,SAAS,MAAM,KAAK,CAEnD,QAAO,aACL,sCACA,u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AAQ;GACR,UAAU;GACV,cACE;GACF,KAAK;GACN,CAAC,CACH;WACO;AACR,QAAM,kBAAkB,YAAY;;;AAIxC,eAAsB,OACpB,UAA+B,EAAE,EACd;CACnB,MAAM,SAAS,MAAM,YAAY,QAAQ;AACzC,KAAI,CAAC,OAAQ,OAAM,oBAAoB;AACvC,KAAI;EACF,MAAM,SAAS,MAAM,KAAK,cACxB,MAAM,cAAc,QAAQ,EAC5B,OAAO,aACP,OAAO,QACR;AACD,SAAO;GAAE,KAAK,OAAO;GAAK,OAAO,OAAO;GAAO,MAAM,OAAO;GAAM;UAC3D,OAAO;AACd,QAAM,WAAW,OAAO,2CAA2C"}
|
|
1
|
+
{"version":3,"file":"oauth.js","names":["createDiagnosticMessage"],"sources":["../../src/auth/oauth.ts"],"sourcesContent":["import open from 'open';\nimport * as oidc from 'openid-client';\nimport type { UserTokenProvider } from 'generaltranslation/api';\nimport { createDiagnosticMessage } from 'generaltranslation/diagnostics';\nimport { defaultBaseUrl } from 'generaltranslation/internal';\nimport { GT_DASHBOARD_URL } from '../utils/constants.js';\nimport { logger } from '../console/logger.js';\nimport {\n deleteOAuthTokens,\n readOAuthTokens,\n writeOAuthTokens,\n} from './credentialStore.js';\nimport type { OAuthTokens } from './credentialStore.js';\nimport { UserAuthError, loginRequiredError } from './errors.js';\nimport { startLoopbackServer } from './loopback.js';\n\n/** Public native client seeded by the authorization server; never a secret. */\nconst OAUTH_CLIENT_ID = 'gt-cli';\n/** Explicit on both grants: identity, refresh and the user's dashboard permissions.\n * Must match the seeded gt-cli client; the device endpoint does not default scope.\n */\nconst OAUTH_SCOPE = 'openid profile offline_access gt:*';\n// Refresh before expiry so an in-flight request does not carry an expired token.\nconst TOKEN_REFRESH_BUFFER_MS = 30_000;\n\nexport type DeviceCode = {\n userCode: string;\n verificationUri: string;\n verificationUriComplete?: string;\n};\nexport type UserInfo = { email?: string; name?: string; sub: string };\ntype OAuthRequestOptions = { authBaseUrl?: string; fetch?: typeof fetch };\nexport type UserTokenProviderOptions = OAuthRequestOptions & {\n /** API the requests go to; must match the resource the login was issued for. */\n baseUrl: string;\n};\nexport type LoginOptions = OAuthRequestOptions & {\n /** API the token is issued for; GT_API_URL overrides, then the public API. */\n baseUrl?: string;\n noBrowser?: boolean;\n onDeviceCode?: (deviceCode: DeviceCode) => void;\n signal?: AbortSignal;\n onAuthorizationUrl?: (url: string) => void;\n openBrowser?: (url: string) => Promise<unknown>;\n timeoutMs?: number;\n};\n\nfunction oauthFailure(\n whatHappened: string,\n fix?: string,\n details?: string\n): UserAuthError {\n return new UserAuthError('oauth', whatHappened, fix, details);\n}\n\n/**\n * An abort or a timeout, raw from a signal check or wrapped by the client\n * library, which rethrows a DOMException from its own operations as a\n * ClientError coded OAUTH_ABORT or OAUTH_TIMEOUT.\n */\nfunction isCancellation(error: unknown): boolean {\n if (error instanceof oidc.ClientError)\n return error.code === 'OAUTH_ABORT' || error.code === 'OAUTH_TIMEOUT';\n return (\n error instanceof Error &&\n ['AbortError', 'TimeoutError'].includes(error.name)\n );\n}\n\nfunction cancelledFailure(): UserAuthError {\n return oauthFailure(\n 'Sign in was cancelled or timed out',\n 'Run `gt login` again'\n );\n}\n\nfunction oauthError(error: unknown, fallback: string): UserAuthError {\n if (isCancellation(error)) return cancelledFailure();\n if (\n error instanceof oidc.AuthorizationResponseError ||\n error instanceof oidc.ResponseBodyError\n ) {\n const descriptions: Record<string, string> = {\n access_denied: 'Sign in was denied in the browser',\n expired_token: 'The sign-in code expired before it was approved',\n invalid_scope: 'The authorization server rejected the requested scopes',\n invalid_grant: 'Your login or sign-in code expired or was already used',\n invalid_client: 'This authorization server does not recognize the gt CLI',\n unauthorized_client:\n 'This authorization server does not recognize the gt CLI',\n };\n return oauthFailure(\n descriptions[error.error] ?? fallback,\n ['invalid_client', 'unauthorized_client'].includes(error.error)\n ? 'Check GT_AUTH_URL or update the server'\n : 'Run `gt login` again',\n // Scope descriptions are useful configuration diagnostics, not token data.\n error.error === 'invalid_scope' ? error.error_description : undefined\n );\n }\n if (error instanceof oidc.ClientError) {\n const status =\n error.cause instanceof Response ? ` (HTTP ${error.cause.status})` : '';\n return oauthFailure(\n `${fallback}${status}`,\n 'Check the authorization server and try again',\n error.code\n );\n }\n // Do not expose transport causes, callback URLs or token responses.\n return oauthFailure(fallback, 'Check the authorization server and try again');\n}\n\nfunction assertEndpoint(url: URL, issuer: URL): void {\n if (\n url.username ||\n url.password ||\n url.hash ||\n (url.protocol !== 'https:' &&\n !(issuer.protocol === 'http:' && url.origin === issuer.origin))\n ) {\n throw oauthFailure(\n 'The authorization server supplied an unsafe endpoint',\n 'Use HTTPS, or same-origin local development HTTP'\n );\n }\n}\n\nasync function configuration(\n {\n authBaseUrl = getAuthBaseUrl(),\n fetch: fetchImplementation = globalThis.fetch,\n }: OAuthRequestOptions,\n signal?: AbortSignal\n): Promise<oidc.Configuration> {\n const issuer = new URL(authBaseUrl);\n const local =\n issuer.hostname === 'localhost' ||\n issuer.hostname.endsWith('.localhost') ||\n issuer.hostname === '127.0.0.1' ||\n issuer.hostname === '[::1]';\n if (\n issuer.username ||\n issuer.password ||\n issuer.search ||\n issuer.hash ||\n (issuer.protocol !== 'https:' && !(issuer.protocol === 'http:' && local))\n ) {\n throw oauthFailure(\n 'GT_AUTH_URL is not a trusted issuer URL',\n 'Use HTTPS, or a local development HTTP issuer without credentials, query or fragment'\n );\n }\n return oidc.discovery(issuer, OAUTH_CLIENT_ID, undefined, oidc.None(), {\n execute:\n issuer.protocol === 'http:'\n ? [oidc.enableNonRepudiationChecks, oidc.allowInsecureRequests]\n : [oidc.enableNonRepudiationChecks],\n [oidc.customFetch]: (url, init) => {\n assertEndpoint(new URL(url), issuer);\n return fetchImplementation(url, {\n ...init,\n // Include operation cancellation in JWKS fetches as well as token requests.\n signal: signal\n ? AbortSignal.any([signal, ...(init.signal ? [init.signal] : [])])\n : init.signal,\n body:\n init.body instanceof Uint8Array\n ? new Uint8Array(init.body)\n : init.body,\n });\n },\n });\n}\n\nfunction parseTokens(\n result: oidc.TokenEndpointResponse & oidc.TokenEndpointResponseHelpers,\n previous?: OAuthTokens\n): Omit<OAuthTokens, 'resource'> {\n const subject = result.claims()?.sub ?? previous?.subject;\n if (!subject || (previous && subject !== previous.subject)) {\n throw oauthFailure(\n 'The authorization server did not confirm the expected account identity',\n 'Run `gt login` again'\n );\n }\n if (\n result.token_type !== 'bearer' ||\n typeof result.expires_in !== 'number' ||\n !Number.isFinite(result.expires_in) ||\n result.expires_in <= 0\n ) {\n throw oauthFailure(\n 'The authorization server returned an unsupported token type or lifetime'\n );\n }\n return {\n accessToken: result.access_token,\n expiresAt: Date.now() + result.expires_in * 1000,\n refreshToken: result.refresh_token ?? previous?.refreshToken ?? '',\n scope: result.scope ?? previous?.scope ?? OAUTH_SCOPE,\n tokenType: result.token_type,\n subject,\n };\n}\n\nfunction getAuthBaseUrl(): string {\n return (process.env.GT_AUTH_URL ?? `${GT_DASHBOARD_URL}/api/auth`).replace(\n /\\/$/,\n ''\n );\n}\n\n/** Resource indicators are the API origin serialized as a URL href (trailing slash). */\nfunction toApiResource(baseUrl: string): string {\n return new URL(baseUrl).href;\n}\n\nfunction loginResource(options: LoginOptions): string {\n return toApiResource(\n process.env.GT_API_URL ?? options.baseUrl ?? defaultBaseUrl\n );\n}\n\nasync function loginWithDeviceCode(\n options: LoginOptions\n): Promise<OAuthTokens> {\n if (options.noBrowser && !options.onDeviceCode) {\n throw oauthFailure(\n 'Device login needs a way to display the verification code',\n 'Provide onDeviceCode when using noBrowser'\n );\n }\n const authBaseUrl = options.authBaseUrl ?? getAuthBaseUrl();\n const resource = loginResource(options);\n const lifetime = new AbortController();\n const signal = options.signal\n ? AbortSignal.any([options.signal, lifetime.signal])\n : lifetime.signal;\n let timer: ReturnType<typeof setTimeout> | undefined;\n let result: oidc.TokenEndpointResponse & oidc.TokenEndpointResponseHelpers;\n try {\n signal.throwIfAborted();\n const config = await configuration({ ...options, authBaseUrl }, signal);\n const started = Date.now();\n const response = await oidc.initiateDeviceAuthorization(config, {\n scope: OAUTH_SCOPE,\n resource,\n });\n const deadline = started + response.expires_in * 1000;\n const checkLifetime = () => {\n if (Date.now() >= deadline)\n lifetime.abort(new DOMException('Device code expired', 'TimeoutError'));\n signal.throwIfAborted();\n };\n checkLifetime();\n timer = setTimeout(\n () =>\n lifetime.abort(new DOMException('Device code expired', 'TimeoutError')),\n deadline - Date.now()\n );\n assertEndpoint(new URL(response.verification_uri), new URL(authBaseUrl));\n if (response.verification_uri_complete)\n assertEndpoint(\n new URL(response.verification_uri_complete),\n new URL(authBaseUrl)\n );\n options.onDeviceCode?.({\n userCode: response.user_code,\n verificationUri: response.verification_uri,\n verificationUriComplete: response.verification_uri_complete,\n });\n checkLifetime();\n if (!options.noBrowser) {\n void (options.openBrowser ?? open)(\n response.verification_uri_complete ?? response.verification_uri\n ).catch(() => undefined);\n }\n result = await oidc.pollDeviceAuthorizationGrant(\n config,\n response,\n { resource },\n { signal }\n );\n checkLifetime();\n } catch (error) {\n throw oauthError(error, 'Could not complete device sign in');\n } finally {\n clearTimeout(timer);\n }\n const tokens = { ...parseTokens(result), resource };\n await writeOAuthTokens(tokens, authBaseUrl);\n return tokens;\n}\n\n/** How long the callback page waits to learn the account's name. */\nexport const ACCOUNT_LOOKUP_TIMEOUT_MS = 3000;\n\n/**\n * The email, else the profile name, from the userinfo endpoint, within the\n * lookup budget; undefined when the endpoint fails, stalls, or returns\n * claims that are not strings. Never throws. When the budget expires the\n * request itself is aborted through `cancel`, which the configuration's\n * fetch honors, so a stalled endpoint holds no socket open after the page\n * has been served and the command can exit.\n */\nasync function lookupAccountName(\n config: oidc.Configuration,\n accessToken: string,\n subject: string,\n cancel: AbortController\n): Promise<string | undefined> {\n let timer: NodeJS.Timeout | undefined;\n const budget = new Promise<undefined>((resolve) => {\n timer = setTimeout(() => {\n cancel.abort();\n resolve(undefined);\n }, ACCOUNT_LOOKUP_TIMEOUT_MS);\n });\n const lookup = oidc\n .fetchUserInfo(config, accessToken, subject)\n .then((user) =>\n typeof user.email === 'string'\n ? user.email\n : typeof user.name === 'string'\n ? user.name\n : undefined\n )\n .catch(() => undefined);\n try {\n return await Promise.race([lookup, budget]);\n } finally {\n clearTimeout(timer);\n }\n}\n\n/** Browser S256/loopback, or device login for SSH, --no-browser and bind failure. */\nexport async function login(options: LoginOptions = {}): Promise<OAuthTokens> {\n if (\n options.noBrowser ||\n process.env.SSH_CONNECTION ||\n process.env.SSH_CLIENT ||\n process.env.SSH_TTY\n ) {\n return loginWithDeviceCode({ ...options, noBrowser: true });\n }\n const authBaseUrl = options.authBaseUrl ?? getAuthBaseUrl();\n const resource = loginResource(options);\n // Fired only by the account lookup's budget, after the exchange; nothing\n // else is in flight on this configuration then.\n const cancelLookup = new AbortController();\n // The caller's signal stops the configuration's requests too, so an\n // aborted login ends the exchange instead of finishing and storing it.\n const signal = options.signal\n ? AbortSignal.any([options.signal, cancelLookup.signal])\n : cancelLookup.signal;\n const config = await configuration({ ...options, authBaseUrl }, signal).catch(\n (error: unknown) => {\n throw oauthError(error, 'Could not discover the authorization server');\n }\n );\n const loopback = await startLoopbackServer().catch(() => undefined);\n if (!loopback) return loginWithDeviceCode(options);\n try {\n const codeVerifier = oidc.randomPKCECodeVerifier();\n const state = oidc.randomState();\n const authorizationUrl = oidc.buildAuthorizationUrl(config, {\n redirect_uri: loopback.redirectUri,\n scope: OAUTH_SCOPE,\n resource,\n state,\n code_challenge: await oidc.calculatePKCECodeChallenge(codeVerifier),\n code_challenge_method: 'S256',\n });\n assertEndpoint(authorizationUrl, new URL(authBaseUrl));\n // The errors the page shows as a denial: the exchange read a validated\n // access_denied response, so the page and the terminal agree.\n const denials = new WeakSet<object>();\n const callback = loopback.waitForCallback(\n async (callbackUrl) => {\n const result = await oidc\n .authorizationCodeGrant(\n config,\n callbackUrl,\n {\n pkceCodeVerifier: codeVerifier,\n expectedState: state,\n idTokenExpected: true,\n },\n { resource }\n )\n .catch((error: unknown) => {\n const failure = oauthError(\n error,\n 'Failed to authenticate via web browser'\n );\n if (\n error instanceof oidc.AuthorizationResponseError &&\n error.error === 'access_denied'\n )\n denials.add(failure);\n throw failure;\n });\n const tokens = { ...parseTokens(result), resource };\n // The browser page names the account: the email when the userinfo\n // carries one, else the profile name. The lookup is best effort: a\n // failure, a malformed claim or a slow endpoint only leaves the name\n // off the page.\n const account = await lookupAccountName(\n config,\n tokens.accessToken,\n tokens.subject,\n cancelLookup\n );\n // The lookup swallows the caller's abort with its other errors. A\n // login cancelled by now stores nothing, so the login it would have\n // replaced stays as it was.\n if (options.signal?.aborted) throw cancelledFailure();\n await writeOAuthTokens(tokens, authBaseUrl);\n return { tokens, account };\n },\n options.timeoutMs,\n {\n describe: (outcome) => ({ account: outcome.account }),\n failure: (error) =>\n error instanceof Error && denials.has(error) ? 'denied' : 'failed',\n }\n );\n // Printing/launching may fail before we await the listener.\n callback.catch(() => undefined);\n options.onAuthorizationUrl?.(authorizationUrl.href);\n void (options.openBrowser ?? open)(authorizationUrl.href).catch(\n () => undefined\n );\n return (await callback).tokens;\n } finally {\n loopback.close();\n }\n}\n\nconst pendingRefreshes = new Map<string, Promise<OAuthTokens>>();\nfunction refreshTokens(options: OAuthRequestOptions): Promise<OAuthTokens> {\n const authBaseUrl = options.authBaseUrl ?? getAuthBaseUrl();\n const pending = pendingRefreshes.get(authBaseUrl);\n if (pending) return pending;\n const refresh = exchangeRefreshToken({ ...options, authBaseUrl }).finally(\n () => pendingRefreshes.delete(authBaseUrl)\n );\n pendingRefreshes.set(authBaseUrl, refresh);\n return refresh;\n}\n\nasync function exchangeRefreshToken(\n options: OAuthRequestOptions & { authBaseUrl: string }\n): Promise<OAuthTokens> {\n const current = await readOAuthTokens(options.authBaseUrl);\n if (!current?.refreshToken) throw loginRequiredError();\n const result = await (async () =>\n oidc.refreshTokenGrant(\n await configuration(options),\n current.refreshToken\n ))().catch((error: unknown) => {\n throw oauthError(error, 'Could not refresh your login');\n });\n // The grant reuses the bound resource, so the refreshed token keeps its audience.\n const tokens = {\n ...parseTokens(result, current),\n resource: current.resource,\n };\n await writeOAuthTokens(tokens, options.authBaseUrl);\n return tokens;\n}\n\nasync function validTokens(\n options: OAuthRequestOptions\n): Promise<OAuthTokens | undefined> {\n const tokens = await readOAuthTokens(options.authBaseUrl ?? getAuthBaseUrl());\n if (!tokens || tokens.expiresAt > Date.now() + TOKEN_REFRESH_BUFFER_MS)\n return tokens;\n return refreshTokens(options);\n}\n\n/** Whether a stored login exists for this API; does not refresh or contact the server. */\nexport async function hasLogin(\n options: UserTokenProviderOptions\n): Promise<boolean> {\n const tokens = await readOAuthTokens(options.authBaseUrl ?? getAuthBaseUrl());\n return tokens?.resource === toApiResource(options.baseUrl);\n}\n\n/** Construction is deliberately free of auth/storage/discovery I/O. */\nexport function createUserTokenProvider(\n options: UserTokenProviderOptions\n): UserTokenProvider {\n // Check the audience before any refresh so a stale mismatched login is\n // never rotated on behalf of the wrong API.\n const storedTokens = async (): Promise<OAuthTokens> => {\n const tokens = await readOAuthTokens(\n options.authBaseUrl ?? getAuthBaseUrl()\n );\n if (!tokens) throw loginRequiredError();\n const resource = toApiResource(options.baseUrl);\n if (tokens.resource !== resource) {\n throw new UserAuthError(\n 'resource_mismatch',\n `You are signed in to ${tokens.resource}, but this project uses ${resource}`,\n 'Run `gt login` in this project to sign in to its API'\n );\n }\n return tokens;\n };\n return {\n getAccessToken: async () => {\n const tokens = await storedTokens();\n if (tokens.expiresAt > Date.now() + TOKEN_REFRESH_BUFFER_MS)\n return tokens.accessToken;\n return (await refreshTokens(options)).accessToken;\n },\n refreshAccessToken: async () => {\n await storedTokens();\n return (await refreshTokens(options)).accessToken;\n },\n };\n}\n\nexport async function logout(options: OAuthRequestOptions = {}): Promise<void> {\n const authBaseUrl = options.authBaseUrl ?? getAuthBaseUrl();\n try {\n const tokens = await readOAuthTokens(authBaseUrl);\n if (tokens?.refreshToken)\n await oidc.tokenRevocation(\n await configuration(options),\n tokens.refreshToken,\n { token_type_hint: 'refresh_token' }\n );\n } catch {\n logger.warn(\n createDiagnosticMessage({\n source: 'gt',\n severity: 'Warning',\n whatHappened:\n 'Signed out locally, but remote session revocation could not be confirmed',\n fix: 'Revoke the session in the dashboard if needed',\n })\n );\n } finally {\n await deleteOAuthTokens(authBaseUrl);\n }\n}\n\nexport async function whoAmI(\n options: OAuthRequestOptions = {}\n): Promise<UserInfo> {\n const tokens = await validTokens(options);\n if (!tokens) throw loginRequiredError();\n try {\n const result = await oidc.fetchUserInfo(\n await configuration(options),\n tokens.accessToken,\n tokens.subject\n );\n return { sub: result.sub, email: result.email, name: result.name };\n } catch (error) {\n throw oauthError(error, 'Could not validate your account identity');\n }\n}\n"],"mappings":";;;;;;;;;;;AAiBA,MAAM,kBAAkB;;;;AAIxB,MAAM,cAAc;AAEpB,MAAM,0BAA0B;AAwBhC,SAAS,aACP,cACA,KACA,SACe;AACf,QAAO,IAAI,cAAc,SAAS,cAAc,KAAK,QAAQ;;;;;;;AAQ/D,SAAS,eAAe,OAAyB;AAC/C,KAAI,iBAAiB,KAAK,YACxB,QAAO,MAAM,SAAS,iBAAiB,MAAM,SAAS;AACxD,QACE,iBAAiB,SACjB,CAAC,cAAc,eAAe,CAAC,SAAS,MAAM,KAAK;;AAIvD,SAAS,mBAAkC;AACzC,QAAO,aACL,sCACA,uBACD;;AAGH,SAAS,WAAW,OAAgB,UAAiC;AACnE,KAAI,eAAe,MAAM,CAAE,QAAO,kBAAkB;AACpD,KACE,iBAAiB,KAAK,8BACtB,iBAAiB,KAAK,kBAWtB,QAAO,aACL;EATA,eAAe;EACf,eAAe;EACf,eAAe;EACf,eAAe;EACf,gBAAgB;EAChB,qBACE;EAGU,CAAC,MAAM,UAAU,UAC7B,CAAC,kBAAkB,sBAAsB,CAAC,SAAS,MAAM,MAAM,GAC3D,2CACA,wBAEJ,MAAM,UAAU,kBAAkB,MAAM,oBAAoB,KAAA,EAC7D;AAEH,KAAI,iBAAiB,KAAK,YAGxB,QAAO,aACL,GAAG,WAFH,MAAM,iBAAiB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AoB;AACvC,KAAI;EACF,MAAM,SAAS,MAAM,KAAK,cACxB,MAAM,cAAc,QAAQ,EAC5B,OAAO,aACP,OAAO,QACR;AACD,SAAO;GAAE,KAAK,OAAO;GAAK,OAAO,OAAO;GAAO,MAAM,OAAO;GAAM;UAC3D,OAAO;AACd,QAAM,WAAW,OAAO,2CAA2C"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export declare const PACKAGE_VERSION = "2.25.
|
|
1
|
+
export declare const PACKAGE_VERSION = "2.25.2";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"version.js","names":[],"sources":["../../src/generated/version.ts"],"sourcesContent":["// This file is auto-generated. Do not edit manually.\nexport const PACKAGE_VERSION = '2.25.
|
|
1
|
+
{"version":3,"file":"version.js","names":[],"sources":["../../src/generated/version.ts"],"sourcesContent":["// This file is auto-generated. Do not edit manually.\nexport const PACKAGE_VERSION = '2.25.2';\n"],"mappings":";AACA,MAAa,kBAAkB"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"edits.js","names":[],"sources":["../../../../src/setup/buildTools/shared/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,EAAE,QAAQ,EAAE,MAAM,CACjC,QACE,QAAQ,EAAE,OAAO,KAAK,WACrB,OAAO,MAAM,GAAG,MAAM,GAAG,OAAO,OAAO,MAAM,OAAO,MAAM,EAC5D,QACD;;AAGL,SAAgB,cACd,YACA,OACA,KACM;CACN,MAAM,aAAa,WAAW,WAAW,CAAC,GAAG,GAAG;AAChD,KAAI,CAAC,WAAY,QAAO;EAAE,OAAO;EAAG,MAAM,MAAM,KAAK,IAAI,GAAG,MAAM;EAAK;AAKvE,QAAO;EACL,QAJkB,WAAW,kBAC3B,QAAQ,YAAY,QAAQ,IAAK,MAAM,SAAS,WAAW,IAAK,IAAI,KAAK,CAC1E,GAAG,GAAG,GAEa,OAAO,WAAW;EACtC,MAAM,MAAM,MAAM,KAAK,IAAI;EAC5B"}
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import * as t from '@babel/types';
|
|
2
|
+
export declare function isJsxElementNamed(node: t.Node, name: string): node is t.JSXElement;
|
|
3
|
+
export declare function isChildrenSlot(node: t.Node): boolean;
|
|
4
|
+
export declare function rendersElement(nodes: (t.Node | undefined)[], name: string): boolean;
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import * as t from "@babel/types";
|
|
2
|
+
//#region src/setup/buildTools/shared/jsx.ts
|
|
3
|
+
function isJsxElementNamed(node, name) {
|
|
4
|
+
return node.type === "JSXElement" && t.isJSXIdentifier(node.openingElement.name, { name });
|
|
5
|
+
}
|
|
6
|
+
function isChildrenSlot(node) {
|
|
7
|
+
return node.type === "JSXExpressionContainer" && node.expression.type === "Identifier" && node.expression.name === "children";
|
|
8
|
+
}
|
|
9
|
+
function rendersElement(nodes, name) {
|
|
10
|
+
let found = false;
|
|
11
|
+
for (const node of nodes) t.traverseFast(node, (child) => {
|
|
12
|
+
if (isJsxElementNamed(child, name)) found = true;
|
|
13
|
+
});
|
|
14
|
+
return found;
|
|
15
|
+
}
|
|
16
|
+
//#endregion
|
|
17
|
+
export { isChildrenSlot, isJsxElementNamed, rendersElement };
|
|
18
|
+
|
|
19
|
+
//# sourceMappingURL=jsx.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"jsx.js","names":[],"sources":["../../../../src/setup/buildTools/shared/jsx.ts"],"sourcesContent":["// JSX lookups shared by framework setups.\nimport * as t from '@babel/types';\n\nexport function isJsxElementNamed(\n node: t.Node,\n name: string\n): node is t.JSXElement {\n return (\n node.type === 'JSXElement' &&\n t.isJSXIdentifier(node.openingElement.name, { name })\n );\n}\n\nexport function 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"],"mappings":";;AAGA,SAAgB,kBACd,MACA,MACsB;AACtB,QACE,KAAK,SAAS,gBACd,EAAE,gBAAgB,KAAK,eAAe,MAAM,EAAE,MAAM,CAAC;;AAIzD,SAAgB,eAAe,MAAuB;AACpD,QACE,KAAK,SAAS,4BACd,KAAK,WAAW,SAAS,gBACzB,KAAK,WAAW,SAAS;;AAI7B,SAAgB,eACd,OACA,MACS;CACT,IAAI,QAAQ;AACZ,MAAK,MAAM,QAAQ,MACjB,GAAE,aAAa,OAAO,UAAU;AAC9B,MAAI,kBAAkB,OAAO,KAAK,CAAE,SAAQ;GAC5C;AAEJ,QAAO"}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import * as t from '@babel/types';
|
|
2
|
+
export type SourceFile = {
|
|
3
|
+
/** Relative to the app, with forward slashes. */
|
|
4
|
+
path: string;
|
|
5
|
+
content: string;
|
|
6
|
+
/** Undefined when the file cannot be parsed. */
|
|
7
|
+
statements?: t.Statement[];
|
|
8
|
+
};
|
|
9
|
+
export declare function readSourceFile(appDirectory: string, basename: string): Promise<SourceFile | undefined>;
|
|
10
|
+
/** The local name `name` is imported as from `source`. */
|
|
11
|
+
export declare function getLocalImport(file: SourceFile, name: string, source: string): string | undefined;
|
|
12
|
+
export declare function getPropertyName(property: t.ObjectExpression['properties'][number]): string | undefined;
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import { parseModule } from "../../setupViteSPA.js";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import fs from "node:fs";
|
|
4
|
+
import * as t from "@babel/types";
|
|
5
|
+
//#region src/setup/buildTools/shared/source.ts
|
|
6
|
+
const SOURCE_EXTENSIONS = [
|
|
7
|
+
".tsx",
|
|
8
|
+
".ts",
|
|
9
|
+
".jsx",
|
|
10
|
+
".js"
|
|
11
|
+
];
|
|
12
|
+
async function readSourceFile(appDirectory, basename) {
|
|
13
|
+
for (const extension of SOURCE_EXTENSIONS) {
|
|
14
|
+
const relativePath = `${basename}${extension}`;
|
|
15
|
+
const absolutePath = path.join(appDirectory, relativePath);
|
|
16
|
+
if (!fs.existsSync(absolutePath)) continue;
|
|
17
|
+
const content = await fs.promises.readFile(absolutePath, "utf8");
|
|
18
|
+
return {
|
|
19
|
+
path: relativePath,
|
|
20
|
+
content,
|
|
21
|
+
statements: parseModule(content, relativePath)
|
|
22
|
+
};
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
/** The local name `name` is imported as from `source`. */
|
|
26
|
+
function getLocalImport(file, name, source) {
|
|
27
|
+
for (const statement of file.statements ?? []) {
|
|
28
|
+
if (statement.type !== "ImportDeclaration" || statement.source.value !== source || statement.importKind === "type") continue;
|
|
29
|
+
for (const specifier of statement.specifiers) if (specifier.type === "ImportSpecifier" && specifier.importKind !== "type" && t.isIdentifier(specifier.imported, { name })) return specifier.local.name;
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
function getPropertyName(property) {
|
|
33
|
+
if (property.type === "SpreadElement" || property.computed) return void 0;
|
|
34
|
+
if (property.key.type === "Identifier") return property.key.name;
|
|
35
|
+
if (property.key.type === "StringLiteral") return property.key.value;
|
|
36
|
+
}
|
|
37
|
+
//#endregion
|
|
38
|
+
export { getLocalImport, getPropertyName, readSourceFile };
|
|
39
|
+
|
|
40
|
+
//# sourceMappingURL=source.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"source.js","names":[],"sources":["../../../../src/setup/buildTools/shared/source.ts"],"sourcesContent":["// Source-file reading and AST lookups shared by framework setups.\nimport * as t from '@babel/types';\nimport fs from 'node:fs';\nimport path from 'node:path';\nimport { parseModule } from '../../setupViteSPA.js';\n\n// Frameworks resolve 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\n/** The local name `name` is imported as from `source`. */\nexport function getLocalImport(\n file: SourceFile,\n name: string,\n source: string\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":";;;;;AAOA,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;;;;AAML,SAAgB,eACd,MACA,MACA,QACoB;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"}
|
|
@@ -1,10 +1,12 @@
|
|
|
1
1
|
import { DEFAULT_VITE_TRANSLATIONS_DIR } from "../../../utils/constants.js";
|
|
2
2
|
import { getViteLoaderExport, parseModule, writeViteLoader } from "../../setupViteSPA.js";
|
|
3
3
|
import { VITE_LOADER_FILE, viteSetup } from "../vite.js";
|
|
4
|
-
import { applyEdits, getCodeStyle, getImportEdit } from "
|
|
5
|
-
import {
|
|
4
|
+
import { applyEdits, getCodeStyle, getImportEdit } from "../shared/edits.js";
|
|
5
|
+
import { rendersElement } from "../shared/jsx.js";
|
|
6
|
+
import { readSourceFile } from "../shared/source.js";
|
|
7
|
+
import { DOCS_URL, inspectTanStackStart } from "./source.js";
|
|
6
8
|
import { START_CONTENT, getMiddlewareAction, registersMiddleware } from "./middleware.js";
|
|
7
|
-
import { configureRootRoute, findRootComponent, getRootFix
|
|
9
|
+
import { configureRootRoute, findRootComponent, getRootFix } from "./root.js";
|
|
8
10
|
import { findInitializeCall, getRouterLines, getStorageAction, passesLoader } from "./router.js";
|
|
9
11
|
import path from "node:path";
|
|
10
12
|
import fs from "node:fs";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../../../../src/setup/buildTools/tanstackStart/index.ts"],"sourcesContent":["// TanStack Start setup: configures src/router.tsx, src/start.ts and\n// src/routes/__root.tsx in dependency order, or reports manual steps.\nimport fs from 'node:fs';\nimport path from 'node:path';\nimport { DEFAULT_VITE_TRANSLATIONS_DIR } from '../../../utils/constants.js';\nimport {\n getViteLoaderExport,\n parseModule,\n writeViteLoader,\n type ViteLoaderExport,\n type ViteLoaderResult,\n} from '../../setupViteSPA.js';\nimport type {\n BuildToolContext,\n BuildToolSetup,\n ManualAction,\n} from '../index.js';\nimport { VITE_LOADER_FILE, viteSetup } from '../vite.js';\nimport { applyEdits, getCodeStyle, getImportEdit } from './edits.js';\nimport {\n getMiddlewareAction,\n registersMiddleware,\n START_CONTENT,\n} from './middleware.js';\nimport {\n configureRootRoute,\n findRootComponent,\n getRootFix,\n rendersElement,\n} from './root.js';\nimport {\n findInitializeCall,\n getRouterLines,\n getStorageAction,\n passesLoader,\n} from './router.js';\nimport {\n DOCS_URL,\n inspectTanStackStart,\n readSourceFile,\n type SourceFile,\n} from './source.js';\n\nasync function writeLoader(\n ctx: BuildToolContext & { translationsDir: string }\n): Promise<{ loader: ViteLoaderResult; steps: string[] }> {\n const loader = await writeViteLoader({ ...ctx, create: true });\n const changed = loader === 'created' || loader === 'updated';\n return { loader, steps: changed ? [`${loader} ${VITE_LOADER_FILE}`] : [] };\n}\n\nexport const tanstackStartSetup: BuildToolSetup = {\n framework: 'tanstack-start',\n defaultTranslationsDir: DEFAULT_VITE_TRANSLATIONS_DIR,\n initializer: 'initializeGT',\n ownsLoader: true,\n skipsGTInstall: () => false,\n devCredentialsOption: '--live-translations',\n docsUrl: DOCS_URL,\n async preflight(appDirectory) {\n await inspectTanStackStart(appDirectory);\n },\n // The loader is the same file Vite generates, but a router that loads from\n // the CDN also needs the loader passed to initializeGT.\n async syncLoader(ctx) {\n const result = await viteSetup.syncLoader(ctx);\n if (ctx.keepAppSource) return result;\n const router = await readSourceFile(ctx.appDirectory, 'src/router');\n const initializeCall = router && findInitializeCall(router);\n if (\n !initializeCall ||\n passesLoader(router, initializeCall.arguments[0], ctx) !== false\n ) {\n return result;\n }\n const { loader, steps } = await writeLoader(ctx);\n const loaderExport = await getViteLoaderExport(ctx.appDirectory, loader);\n return {\n steps: [...result.steps, ...steps],\n manualActions: loaderExport\n ? [\n ...result.manualActions,\n getStorageAction(router, ctx, loaderExport, false),\n ]\n : result.manualActions,\n };\n },\n async apply(ctx) {\n const { appDirectory, translationsDir } = ctx;\n const { router, root, start } = await inspectTanStackStart(appDirectory);\n const steps: string[] = [];\n const manualActions: ManualAction[] = [];\n const writeSource = async (file: string, content: string) => {\n await fs.promises.writeFile(path.join(appDirectory, file), content);\n };\n\n let loaderExport: ViteLoaderExport;\n if (translationsDir) {\n const { loader, steps: loaderSteps } = await writeLoader({\n ...ctx,\n translationsDir,\n });\n steps.push(...loaderSteps);\n loaderExport = await getViteLoaderExport(appDirectory, loader);\n if (loader === 'custom') {\n manualActions.push(\n loaderExport\n ? {\n whatHappened: `Your custom ${VITE_LOADER_FILE} was preserved`,\n fix: `Verify ${VITE_LOADER_FILE} loads translations from ${translationsDir}`,\n }\n : {\n whatHappened: `Your custom ${VITE_LOADER_FILE} has no runtime loadTranslations export`,\n fix: `Export a default or named loadTranslations function from ${VITE_LOADER_FILE} that loads translations from ${translationsDir}, then rerun gt init`,\n }\n );\n }\n }\n\n // An insertion that breaks the file's syntax falls back to manual setup.\n const parses = (file: SourceFile, content: string | undefined) =>\n content !== undefined && parseModule(content, file.path) !== undefined\n ? content\n : undefined;\n\n const initializeCall = findInitializeCall(router);\n let routerReady = initializeCall !== undefined;\n let configuredRouter: string | undefined;\n // Storage chosen on a rerun must match how the router loads translations.\n const wantsLoader = Boolean(translationsDir);\n const loaderPassed = passesLoader(\n router,\n initializeCall?.arguments[0],\n ctx\n );\n if (\n loaderPassed !== undefined &&\n loaderPassed !== wantsLoader &&\n (!translationsDir || loaderExport)\n ) {\n manualActions.push(\n getStorageAction(router, ctx, loaderExport, loaderPassed)\n );\n }\n // A custom loader without an export already has its own action.\n if (!routerReady && (!translationsDir || loaderExport)) {\n // Any other mention may be an app-owned initializer; a second\n // initializeGT call would override it.\n if (router.statements && !/\\binitializeGT\\b/.test(router.content)) {\n const style = getCodeStyle(router.content, router.statements);\n configuredRouter = parses(\n router,\n applyEdits(router.content, [\n getImportEdit(\n router.statements,\n getRouterLines(router, ctx, loaderExport, style),\n style.eol\n ),\n ])\n );\n }\n routerReady = configuredRouter !== undefined;\n if (!routerReady) {\n const lines = getRouterLines(router, ctx, loaderExport, {\n quote: \"'\",\n semi: ';',\n });\n manualActions.push({\n whatHappened: `${router.path} was not configured automatically`,\n fix: `Initialize GT after the imports in ${router.path}: ${lines.filter(Boolean).join(' ')}, then rerun gt init (see ${DOCS_URL})`,\n });\n }\n }\n\n const startReady = !start || registersMiddleware(start);\n if (!startReady) {\n manualActions.push(getMiddlewareAction(start!.path));\n }\n\n const rootComponent = root.statements && findRootComponent(root.statements);\n const rootConfigured = rendersElement(\n [rootComponent?.component, rootComponent?.document],\n 'GTProvider'\n );\n // A provider elsewhere may wrap the document indirectly; adding a second\n // one could nest them, so a person decides.\n const providerElsewhere =\n !rootConfigured && rendersElement(root.statements ?? [], 'GTProvider');\n const configuredRoot =\n rootConfigured || providerElsewhere\n ? undefined\n : parses(root, configureRootRoute(root));\n if (!rootConfigured && !configuredRoot) {\n manualActions.push({\n whatHappened: providerElsewhere\n ? `${root.path} renders GTProvider outside the root route's document`\n : `${root.path} does not match the create-start root route`,\n fix: getRootFix(root.path),\n });\n }\n\n // gtMiddleware and the root loader need initializeGT to have run, so\n // they are only added alongside a router that calls it; the actions\n // above ask for a rerun to finish.\n if (routerReady) {\n if (!start) {\n await writeSource('src/start.ts', START_CONTENT);\n steps.push('created src/start.ts');\n }\n if (configuredRouter) {\n await writeSource(router.path, configuredRouter);\n steps.push(`configured ${router.path}`);\n }\n // The root loader reads the request scope gtMiddleware sets up, so\n // without it every page would fail to render.\n if (configuredRoot && startReady) {\n await writeSource(root.path, configuredRoot);\n steps.push(`configured ${root.path}`);\n }\n }\n\n return { steps, manualActions };\n },\n};\n"],"mappings":";;;;;;;;;;;AA2CA,eAAe,YACb,KACwD;CACxD,MAAM,SAAS,MAAM,gBAAgB;EAAE,GAAG;EAAK,QAAQ;EAAM,CAAC;AAE9D,QAAO;EAAE;EAAQ,OADD,WAAW,aAAa,WAAW,YACjB,CAAC,GAAG,OAAO,GAAG,mBAAmB,GAAG,EAAE;EAAE;;AAG5E,MAAa,qBAAqC;CAChD,WAAW;CACX,wBAAwB;CACxB,aAAa;CACb,YAAY;CACZ,sBAAsB;CACtB,sBAAsB;C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CAAC,kBAAkB,eAAe,KAAK,cAAc,EAAE,EAAE,aAAa;EACxE,MAAM,iBACJ,kBAAkB,oBACd,KAAA,IACA,OAAO,MAAM,mBAAmB,KAAK,CAAC;AAC5C,MAAI,CAAC,kBAAkB,CAAC,eACtB,eAAc,KAAK;GACjB,cAAc,oBACV,GAAG,KAAK,KAAK,yDACb,GAAG,KAAK,KAAK;GACjB,KAAK,WAAW,KAAK,KAAK;GAC3B,CAAC;AAMJ,MAAI,aAAa;AACf,OAAI,CAAC,OAAO;AACV,UAAM,YAAY,gBAAgB,cAAc;AAChD,UAAM,KAAK,uBAAuB;;AAEpC,OAAI,kBAAkB;AACpB,UAAM,YAAY,OAAO,MAAM,iBAAiB;AAChD,UAAM,KAAK,cAAc,OAAO,OAAO;;AAIzC,OAAI,kBAAkB,YAAY;AAChC,UAAM,YAAY,KAAK,MAAM,eAAe;AAC5C,UAAM,KAAK,cAAc,KAAK,OAAO;;;AAIzC,SAAO;GAAE;GAAO;GAAe;;CAElC"}
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../../../../src/setup/buildTools/tanstackStart/index.ts"],"sourcesContent":["// TanStack Start setup: configures src/router.tsx, src/start.ts and\n// src/routes/__root.tsx in dependency order, or reports manual steps.\nimport fs from 'node:fs';\nimport path from 'node:path';\nimport { DEFAULT_VITE_TRANSLATIONS_DIR } from '../../../utils/constants.js';\nimport {\n getViteLoaderExport,\n parseModule,\n writeViteLoader,\n type ViteLoaderExport,\n type ViteLoaderResult,\n} from '../../setupViteSPA.js';\nimport type {\n BuildToolContext,\n BuildToolSetup,\n ManualAction,\n} from '../index.js';\nimport { VITE_LOADER_FILE, viteSetup } from '../vite.js';\nimport { applyEdits, getCodeStyle, getImportEdit } from '../shared/edits.js';\nimport { rendersElement } from '../shared/jsx.js';\nimport { readSourceFile, type SourceFile } from '../shared/source.js';\nimport {\n getMiddlewareAction,\n registersMiddleware,\n START_CONTENT,\n} from './middleware.js';\nimport { configureRootRoute, findRootComponent, getRootFix } from './root.js';\nimport {\n findInitializeCall,\n getRouterLines,\n getStorageAction,\n passesLoader,\n} from './router.js';\nimport { DOCS_URL, inspectTanStackStart } from './source.js';\n\nasync function writeLoader(\n ctx: BuildToolContext & { translationsDir: string }\n): Promise<{ loader: ViteLoaderResult; steps: string[] }> {\n const loader = await writeViteLoader({ ...ctx, create: true });\n const changed = loader === 'created' || loader === 'updated';\n return { loader, steps: changed ? [`${loader} ${VITE_LOADER_FILE}`] : [] };\n}\n\nexport const tanstackStartSetup: BuildToolSetup = {\n framework: 'tanstack-start',\n defaultTranslationsDir: DEFAULT_VITE_TRANSLATIONS_DIR,\n initializer: 'initializeGT',\n ownsLoader: true,\n skipsGTInstall: () => false,\n devCredentialsOption: '--live-translations',\n docsUrl: DOCS_URL,\n async preflight(appDirectory) {\n await inspectTanStackStart(appDirectory);\n },\n // The loader is the same file Vite generates, but a router that loads from\n // the CDN also needs the loader passed to initializeGT.\n async syncLoader(ctx) {\n const result = await viteSetup.syncLoader(ctx);\n if (ctx.keepAppSource) return result;\n const router = await readSourceFile(ctx.appDirectory, 'src/router');\n const initializeCall = router && findInitializeCall(router);\n if (\n !initializeCall ||\n passesLoader(router, initializeCall.arguments[0], ctx) !== false\n ) {\n return result;\n }\n const { loader, steps } = await writeLoader(ctx);\n const loaderExport = await getViteLoaderExport(ctx.appDirectory, loader);\n return {\n steps: [...result.steps, ...steps],\n manualActions: loaderExport\n ? [\n ...result.manualActions,\n getStorageAction(router, ctx, loaderExport, false),\n ]\n : result.manualActions,\n };\n },\n async apply(ctx) {\n const { appDirectory, translationsDir } = ctx;\n const { router, root, start } = await inspectTanStackStart(appDirectory);\n const steps: string[] = [];\n const manualActions: ManualAction[] = [];\n const writeSource = async (file: string, content: string) => {\n await fs.promises.writeFile(path.join(appDirectory, file), content);\n };\n\n let loaderExport: ViteLoaderExport;\n if (translationsDir) {\n const { loader, steps: loaderSteps } = await writeLoader({\n ...ctx,\n translationsDir,\n });\n steps.push(...loaderSteps);\n loaderExport = await getViteLoaderExport(appDirectory, loader);\n if (loader === 'custom') {\n manualActions.push(\n loaderExport\n ? {\n whatHappened: `Your custom ${VITE_LOADER_FILE} was preserved`,\n fix: `Verify ${VITE_LOADER_FILE} loads translations from ${translationsDir}`,\n }\n : {\n whatHappened: `Your custom ${VITE_LOADER_FILE} has no runtime loadTranslations export`,\n fix: `Export a default or named loadTranslations function from ${VITE_LOADER_FILE} that loads translations from ${translationsDir}, then rerun gt init`,\n }\n );\n }\n }\n\n // An insertion that breaks the file's syntax falls back to manual setup.\n const parses = (file: SourceFile, content: string | undefined) =>\n content !== undefined && parseModule(content, file.path) !== undefined\n ? content\n : undefined;\n\n const initializeCall = findInitializeCall(router);\n let routerReady = initializeCall !== undefined;\n let configuredRouter: string | undefined;\n // Storage chosen on a rerun must match how the router loads translations.\n const wantsLoader = Boolean(translationsDir);\n const loaderPassed = passesLoader(\n router,\n initializeCall?.arguments[0],\n ctx\n );\n if (\n loaderPassed !== undefined &&\n loaderPassed !== wantsLoader &&\n (!translationsDir || loaderExport)\n ) {\n manualActions.push(\n getStorageAction(router, ctx, loaderExport, loaderPassed)\n );\n }\n // A custom loader without an export already has its own action.\n if (!routerReady && (!translationsDir || loaderExport)) {\n // Any other mention may be an app-owned initializer; a second\n // initializeGT call would override it.\n if (router.statements && !/\\binitializeGT\\b/.test(router.content)) {\n const style = getCodeStyle(router.content, router.statements);\n configuredRouter = parses(\n router,\n applyEdits(router.content, [\n getImportEdit(\n router.statements,\n getRouterLines(router, ctx, loaderExport, style),\n style.eol\n ),\n ])\n );\n }\n routerReady = configuredRouter !== undefined;\n if (!routerReady) {\n const lines = getRouterLines(router, ctx, loaderExport, {\n quote: \"'\",\n semi: ';',\n });\n manualActions.push({\n whatHappened: `${router.path} was not configured automatically`,\n fix: `Initialize GT after the imports in ${router.path}: ${lines.filter(Boolean).join(' ')}, then rerun gt init (see ${DOCS_URL})`,\n });\n }\n }\n\n const startReady = !start || registersMiddleware(start);\n if (!startReady) {\n manualActions.push(getMiddlewareAction(start!.path));\n }\n\n const rootComponent = root.statements && findRootComponent(root.statements);\n const rootConfigured = rendersElement(\n [rootComponent?.component, rootComponent?.document],\n 'GTProvider'\n );\n // A provider elsewhere may wrap the document indirectly; adding a second\n // one could nest them, so a person decides.\n const providerElsewhere =\n !rootConfigured && rendersElement(root.statements ?? [], 'GTProvider');\n const configuredRoot =\n rootConfigured || providerElsewhere\n ? undefined\n : parses(root, configureRootRoute(root));\n if (!rootConfigured && !configuredRoot) {\n manualActions.push({\n whatHappened: providerElsewhere\n ? `${root.path} renders GTProvider outside the root route's document`\n : `${root.path} does not match the create-start root route`,\n fix: getRootFix(root.path),\n });\n }\n\n // gtMiddleware and the root loader need initializeGT to have run, so\n // they are only added alongside a router that calls it; the actions\n // above ask for a rerun to finish.\n if (routerReady) {\n if (!start) {\n await writeSource('src/start.ts', START_CONTENT);\n steps.push('created src/start.ts');\n }\n if (configuredRouter) {\n await writeSource(router.path, configuredRouter);\n steps.push(`configured ${router.path}`);\n }\n // The root loader reads the request scope gtMiddleware sets up, so\n // without it every page would fail to render.\n if (configuredRoot && startReady) {\n await writeSource(root.path, configuredRoot);\n steps.push(`configured ${root.path}`);\n }\n }\n\n return { steps, manualActions };\n },\n};\n"],"mappings":";;;;;;;;;;;;;AAmCA,eAAe,YACb,KACwD;CACxD,MAAM,SAAS,MAAM,gBAAgB;EAAE,GAAG;EAAK,QAAQ;EAAM,CAAC;AAE9D,QAAO;EAAE;EAAQ,OADD,WAAW,aAAa,WAAW,YACjB,CAAC,GAAG,OAAO,GAAG,mBAAmB,GAAG,EAAE;EAAE;;AAG5E,MAAa,qBAAqC;CAChD,WAAW;CACX,wBAAwB;CACxB,aAAa;CACb,YAAY;CACZ,sBAAsB;CACtB,sBAAsB;CACtB,SAAS;CACT,MAAM,UAAU,cAAc;AAC5B,QAAM,qBAAqB,aAAa;;CAI1C,MAAM,WAAW,KAAK;EACpB,MAAM,SAAS,MAAM,UAAU,WAAW,IAAI;AA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C,MAAI,CAAC,kBAAkB,CAAC,eACtB,eAAc,KAAK;GACjB,cAAc,oBACV,GAAG,KAAK,KAAK,yDACb,GAAG,KAAK,KAAK;GACjB,KAAK,WAAW,KAAK,KAAK;GAC3B,CAAC;AAMJ,MAAI,aAAa;AACf,OAAI,CAAC,OAAO;AACV,UAAM,YAAY,gBAAgB,cAAc;AAChD,UAAM,KAAK,uBAAuB;;AAEpC,OAAI,kBAAkB;AACpB,UAAM,YAAY,OAAO,MAAM,iBAAiB;AAChD,UAAM,KAAK,cAAc,OAAO,OAAO;;AAIzC,OAAI,kBAAkB,YAAY;AAChC,UAAM,YAAY,KAAK,MAAM,eAAe;AAC5C,UAAM,KAAK,cAAc,KAAK,OAAO;;;AAIzC,SAAO;GAAE;GAAO;GAAe;;CAElC"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { ManualAction } from '../index.js';
|
|
2
|
-
import { type SourceFile } from '
|
|
2
|
+
import { type SourceFile } from '../shared/source.js';
|
|
3
3
|
export declare const START_CONTENT = "import { createCsrfMiddleware, createStart } from '@tanstack/react-start';\nimport { gtMiddleware } from 'gt-tanstack-start';\n\nconst csrfMiddleware = createCsrfMiddleware({\n filter: ({ handlerType }) => handlerType === 'serverFn',\n});\n\nexport const startInstance = createStart(() => ({\n requestMiddleware: [csrfMiddleware, gtMiddleware],\n}));\n";
|
|
4
4
|
/**
|
|
5
5
|
* Whether the imported gtMiddleware is in the one requestMiddleware array of
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import "../../../types/libraries.js";
|
|
2
|
-
import {
|
|
2
|
+
import { getLocalImport, getPropertyName } from "../shared/source.js";
|
|
3
|
+
import { DOCS_URL } from "./source.js";
|
|
3
4
|
import * as t from "@babel/types";
|
|
4
5
|
//#region src/setup/buildTools/tanstackStart/middleware.ts
|
|
5
6
|
const START_CONTENT = `import { createCsrfMiddleware, createStart } from '@tanstack/react-start';
|
|
@@ -39,7 +40,7 @@ function getStartOptions(start) {
|
|
|
39
40
|
* the startInstance options. A spread or computed key could override it.
|
|
40
41
|
*/
|
|
41
42
|
function registersMiddleware(start) {
|
|
42
|
-
const local = getLocalImport(start, "gtMiddleware");
|
|
43
|
+
const local = getLocalImport(start, "gtMiddleware", "gt-tanstack-start");
|
|
43
44
|
const options = local ? getStartOptions(start) : void 0;
|
|
44
45
|
if (!options) return false;
|
|
45
46
|
const names = options.properties.map(getPropertyName);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"middleware.js","names":[],"sources":["../../../../src/setup/buildTools/tanstackStart/middleware.ts"],"sourcesContent":["// src/start.ts: the generated entry and gtMiddleware registration.\nimport * as t from '@babel/types';\nimport { Libraries } from '../../../types/libraries.js';\nimport type { ManualAction } from '../index.js';\nimport {\n
|
|
1
|
+
{"version":3,"file":"middleware.js","names":[],"sources":["../../../../src/setup/buildTools/tanstackStart/middleware.ts"],"sourcesContent":["// src/start.ts: the generated entry and gtMiddleware registration.\nimport * as t from '@babel/types';\nimport { Libraries } from '../../../types/libraries.js';\nimport type { ManualAction } from '../index.js';\nimport {\n getLocalImport,\n getPropertyName,\n type SourceFile,\n} from '../shared/source.js';\nimport { DOCS_URL } from './source.js';\n\nexport const START_CONTENT = `import { createCsrfMiddleware, createStart } from '@tanstack/react-start';\nimport { gtMiddleware } from '${Libraries.GT_TANSTACK_START}';\n\nconst csrfMiddleware = createCsrfMiddleware({\n filter: ({ handlerType }) => handlerType === 'serverFn',\n});\n\nexport const startInstance = createStart(() => ({\n requestMiddleware: [csrfMiddleware, gtMiddleware],\n}));\n`;\n\n/**\n * The options object returned by `export const startInstance = createStart(...)`,\n * the entry Start reads. Only a callback that returns an object literal\n * directly counts; any other shape is left for manual setup.\n */\nfunction getStartOptions(start: SourceFile): t.ObjectExpression | undefined {\n const createStart = getLocalImport(\n start,\n 'createStart',\n '@tanstack/react-start'\n );\n if (!createStart) return undefined;\n for (const statement of start.statements ?? []) {\n if (statement.type !== 'ExportNamedDeclaration') continue;\n if (statement.declaration?.type !== 'VariableDeclaration') continue;\n for (const { id, init } of statement.declaration.declarations) {\n if (\n !t.isIdentifier(id, { name: 'startInstance' }) ||\n init?.type !== 'CallExpression' ||\n !t.isIdentifier(init.callee, { name: createStart })\n ) {\n continue;\n }\n const getOptions = init.arguments[0];\n if (\n getOptions?.type !== 'ArrowFunctionExpression' &&\n getOptions?.type !== 'FunctionExpression'\n ) {\n return undefined;\n }\n const { body } = getOptions;\n const options =\n body.type !== 'BlockStatement'\n ? body\n : body.body.length === 1 && body.body[0].type === 'ReturnStatement'\n ? body.body[0].argument\n : undefined;\n return options?.type === 'ObjectExpression' ? options : undefined;\n }\n }\n return undefined;\n}\n\n/**\n * Whether the imported gtMiddleware is in the one requestMiddleware array of\n * the startInstance options. A spread or computed key could override it.\n */\nexport function registersMiddleware(start: SourceFile): boolean {\n const local = getLocalImport(\n start,\n 'gtMiddleware',\n Libraries.GT_TANSTACK_START\n );\n const options = local ? getStartOptions(start) : undefined;\n if (!options) return false;\n const names = options.properties.map(getPropertyName);\n if (\n names.includes(undefined) ||\n names.filter((name) => name === 'requestMiddleware').length !== 1\n ) {\n return false;\n }\n const middleware = options.properties[names.indexOf('requestMiddleware')];\n return (\n middleware.type === 'ObjectProperty' &&\n middleware.value.type === 'ArrayExpression' &&\n middleware.value.elements.some((element) =>\n t.isIdentifier(element, { name: local })\n )\n );\n}\n\nexport function getMiddlewareAction(startPath: string): ManualAction {\n return {\n whatHappened: `${startPath} does not use gtMiddleware`,\n fix: `Import { gtMiddleware } from '${Libraries.GT_TANSTACK_START}' in ${startPath} and add it to the requestMiddleware of createStart, keeping your existing middleware such as the CSRF middleware, then rerun gt init (see ${DOCS_URL})`,\n };\n}\n"],"mappings":";;;;;AAWA,MAAa,gBAAgB;;;;;;;;;;;;;;;;AAiB7B,SAAS,gBAAgB,OAAmD;CAC1E,MAAM,cAAc,eAClB,OACA,eACA,wBACD;AACD,KAAI,CAAC,YAAa,QAAO,KAAA;AACzB,MAAK,MAAM,aAAa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as t from '@babel/types';
|
|
2
|
-
import { type SourceFile } from '
|
|
3
|
-
export declare function rendersElement(nodes: (t.Node | undefined)[], name: string): boolean;
|
|
2
|
+
import { type SourceFile } from '../shared/source.js';
|
|
4
3
|
declare function findLocalFunction(statements: t.Statement[], name: string): t.ArrowFunctionExpression | t.FunctionDeclaration | t.FunctionExpression | undefined;
|
|
5
4
|
type LocalFunction = NonNullable<ReturnType<typeof findLocalFunction>>;
|
|
6
5
|
/**
|
|
@@ -1,21 +1,10 @@
|
|
|
1
1
|
import "../../../types/libraries.js";
|
|
2
|
-
import { applyEdits, getCodeStyle, getImportEdit, getLineIndent, getOwnLineIndent } from "
|
|
3
|
-
import {
|
|
2
|
+
import { applyEdits, getCodeStyle, getImportEdit, getLineIndent, getOwnLineIndent } from "../shared/edits.js";
|
|
3
|
+
import { isChildrenSlot, isJsxElementNamed, rendersElement } from "../shared/jsx.js";
|
|
4
|
+
import { getPropertyName } from "../shared/source.js";
|
|
5
|
+
import { DOCS_URL } from "./source.js";
|
|
4
6
|
import * as t from "@babel/types";
|
|
5
7
|
//#region src/setup/buildTools/tanstackStart/root.ts
|
|
6
|
-
function isJsxElementNamed(node, name) {
|
|
7
|
-
return node.type === "JSXElement" && t.isJSXIdentifier(node.openingElement.name, { name });
|
|
8
|
-
}
|
|
9
|
-
function isChildrenSlot(node) {
|
|
10
|
-
return node.type === "JSXExpressionContainer" && node.expression.type === "Identifier" && node.expression.name === "children";
|
|
11
|
-
}
|
|
12
|
-
function rendersElement(nodes, name) {
|
|
13
|
-
let found = false;
|
|
14
|
-
for (const node of nodes) t.traverseFast(node, (child) => {
|
|
15
|
-
if (isJsxElementNamed(child, name)) found = true;
|
|
16
|
-
});
|
|
17
|
-
return found;
|
|
18
|
-
}
|
|
19
8
|
function findLocalFunction(statements, name) {
|
|
20
9
|
for (const statement of statements) {
|
|
21
10
|
const declaration = statement.type === "ExportNamedDeclaration" ? statement.declaration : statement;
|
|
@@ -173,6 +162,6 @@ function getRootFix(rootPath) {
|
|
|
173
162
|
return `In ${rootPath}, add loader: async () => { const locale = getLocale(); return { locale, translations: await getTranslationsSnapshot(locale) }; } to the root route options, read const { locale, translations } = Route.useLoaderData() in the document, set <html lang={locale}>, and wrap everything its <body> renders before <Scripts /> in <GTProvider locale={locale} translations={translations}>, importing GTProvider, getLocale and getTranslationsSnapshot from 'gt-tanstack-start' (see ${DOCS_URL})`;
|
|
174
163
|
}
|
|
175
164
|
//#endregion
|
|
176
|
-
export { configureRootRoute, findRootComponent, getRootFix
|
|
165
|
+
export { configureRootRoute, findRootComponent, getRootFix };
|
|
177
166
|
|
|
178
167
|
//# sourceMappingURL=root.js.map
|