gt-next 6.16.35 → 6.16.37
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +23 -0
- package/dist/config-dir/I18NConfiguration.d.ts +2 -1
- package/dist/config-dir/I18NConfiguration.d.ts.map +1 -1
- package/dist/config-dir/I18NConfiguration.js +1 -1
- package/dist/config-dir/I18NConfiguration.js.map +1 -1
- package/dist/config-dir/props/defaultWithGTConfigProps.d.ts +1 -0
- package/dist/config-dir/props/defaultWithGTConfigProps.d.ts.map +1 -1
- package/dist/config-dir/props/defaultWithGTConfigProps.js +2 -1
- package/dist/config-dir/props/defaultWithGTConfigProps.js.map +1 -1
- package/dist/config-dir/props/withGTConfigProps.d.ts +1 -0
- package/dist/config-dir/props/withGTConfigProps.d.ts.map +1 -1
- package/dist/config-dir/props/withGTConfigProps.js.map +1 -1
- package/dist/config.d.ts +1 -0
- package/dist/config.d.ts.map +1 -1
- package/dist/config.js +3 -1
- package/dist/config.js.map +1 -1
- package/dist/errors/createErrors.d.ts +1 -0
- package/dist/errors/createErrors.d.ts.map +1 -1
- package/dist/errors/createErrors.js +7 -0
- package/dist/errors/createErrors.js.map +1 -1
- package/dist/index.types.d.ts +1 -0
- package/dist/index.types.d.ts.map +1 -1
- package/dist/index.types.js +1 -0
- package/dist/index.types.js.map +1 -1
- package/dist/request/getLocale.d.ts.map +1 -1
- package/dist/request/getLocale.js +2 -2
- package/dist/request/getLocale.js.map +1 -1
- package/dist/request/localeValidation.d.ts +14 -0
- package/dist/request/localeValidation.d.ts.map +1 -0
- package/dist/request/localeValidation.js +37 -0
- package/dist/request/localeValidation.js.map +1 -0
- package/dist/request/registerLocale.d.ts +1 -1
- package/dist/request/registerLocale.d.ts.map +1 -1
- package/dist/request/registerLocale.js +5 -3
- package/dist/request/registerLocale.js.map +1 -1
- package/dist/request/utils/legacyGetLocaleFunction.d.ts.map +1 -1
- package/dist/request/utils/legacyGetLocaleFunction.js +2 -2
- package/dist/request/utils/legacyGetLocaleFunction.js.map +1 -1
- package/dist/server-dir/buildtime/T.d.ts +2 -0
- package/dist/server-dir/buildtime/T.d.ts.map +1 -1
- package/dist/server-dir/buildtime/T.js +5 -1
- package/dist/server-dir/buildtime/T.js.map +1 -1
- package/dist/server-dir/buildtime/getTranslationFunction.d.ts.map +1 -1
- package/dist/server-dir/buildtime/getTranslationFunction.js +12 -5
- package/dist/server-dir/buildtime/getTranslationFunction.js.map +1 -1
- package/dist/server.d.ts +2 -1
- package/dist/server.d.ts.map +1 -1
- package/dist/server.js +2 -0
- package/dist/server.js.map +1 -1
- package/package.json +6 -6
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"createErrors.js","names":["createGtNextDiagnostic","createGtNextPluginDiagnostic","SWC_PLUGIN_SUPPORT","BABEL_PLUGIN_SUPPORT"],"sources":["../../src/errors/createErrors.ts"],"sourcesContent":["// ---- ERRORS ---- //\n\nimport { getLocaleProperties } from '@generaltranslation/format';\nimport {\n createGtNextDiagnostic,\n createGtNextPluginDiagnostic,\n formatDiagnosticErrorDetails,\n} from './diagnostics';\nimport { BABEL_PLUGIN_SUPPORT, SWC_PLUGIN_SUPPORT } from '../plugin/constants';\n\nexport const remoteTranslationsError = createGtNextDiagnostic({\n severity: 'Error',\n whatHappened: 'Remote translations could not be loaded',\n fix: 'Check your project ID, API key, and network connection, then try again',\n wayOut: 'Source content will render as a fallback',\n});\n\nexport const customLoadTranslationsError = (locale: string = '') =>\n createGtNextDiagnostic({\n severity: 'Error',\n whatHappened: `Locally stored translations could not be loaded${locale ? ` for \"${locale}\"` : ''}`,\n fix: 'If you use loadTranslations(), make sure it returns translations for the requested locale',\n });\n\nexport const customLoadDictionaryWarning = (locale: string = '') =>\n createGtNextDiagnostic({\n severity: 'Warning',\n whatHappened: `The local dictionary could not be loaded${locale ? ` for \"${locale}\"` : ''}`,\n fix: 'If you use loadDictionary(), make sure it returns a dictionary for the requested locale',\n });\n\nexport const createUnresolvedNextVersionError = (error: Error) =>\n createGtNextDiagnostic({\n severity: 'Error',\n whatHappened: 'The installed Next.js version could not be resolved',\n fix: 'Check that next is installed in this project',\n details: error.message,\n });\n\nexport const createUnresolvedReactVersionError = (error: Error) =>\n createGtNextDiagnostic({\n severity: 'Error',\n whatHappened: 'The installed React version could not be resolved',\n fix: 'Check that react is installed in this project',\n details: error.message,\n });\n\nexport const createStringTranslationError = (\n string: string,\n id?: string,\n functionName = 'tx'\n) =>\n createGtNextDiagnostic({\n severity: 'Error',\n whatHappened: `${functionName}(\"${string}\")${id ? ` with id \"${id}\"` : ''} could not find a translation`,\n wayOut: 'Source content will render as a fallback',\n fix: 'Push translations again or check your dictionary/runtime translation configuration',\n });\n\nexport const createDictionaryTranslationError = (id: string) =>\n createGtNextDiagnostic({\n severity: 'Error',\n whatHappened: `Dictionary translation entry \"${id}\" could not be found`,\n fix: 'Check that the id exists in your dictionary or push translations again',\n });\n\nexport const createRequiredPrefixError = (id: string, requiredPrefix: string) =>\n createGtNextDiagnostic({\n severity: 'Error',\n whatHappened: `<GTProvider> is scoped to prefix \"${requiredPrefix}\", but a child uses id \"${id}\"`,\n fix: 'Change the <GTProvider> id prop or move the child under the matching dictionary subtree',\n });\n\nexport const devApiKeyIncludedInProductionError = createGtNextDiagnostic({\n severity: 'Error',\n whatHappened: 'Production builds cannot use a development API key',\n fix: 'Replace it with a production API key',\n});\n\nexport const createDictionarySubsetError = (id: string, functionName: string) =>\n createGtNextDiagnostic({\n severity: 'Error',\n whatHappened: `${functionName} with id \"${id}\" could not read a valid dictionary subtree`,\n fix: 'Make sure the id maps to the correct subroute of the dictionary',\n });\n\nexport const dictionaryDisabledError = createGtNextDiagnostic({\n severity: 'Error',\n whatHappened: 'Dictionaries are not enabled',\n fix: 'Add the withGTConfig() plugin to your Next.js config before using dictionary translations',\n docsUrl: 'https://generaltranslation.com/docs',\n});\n\nexport const unresolvedCustomLoadDictionaryError = createGtNextDiagnostic({\n severity: 'Error',\n whatHappened:\n 'loadDictionary() was found during the build but could not be resolved at runtime',\n fix: 'Export a loadDictionary() function from the configured file',\n});\n\nexport const unresolvedCustomLoadTranslationsError = createGtNextDiagnostic({\n severity: 'Error',\n whatHappened:\n 'loadTranslations() was found during the build but could not be resolved at runtime',\n fix: 'Export a loadTranslations() function from the configured file',\n});\n\nexport const unresolvedLoadDictionaryBuildError = (path: string) =>\n createGtNextDiagnostic({\n severity: 'Error',\n whatHappened: `The file defining loadDictionary() could not be resolved at ${path}`,\n fix: 'Check the configured path and try again',\n });\n\nexport const unresolvedLoadTranslationsBuildError = (path: string) =>\n createGtNextDiagnostic({\n severity: 'Error',\n whatHappened: `The file defining loadTranslations() could not be resolved at ${path}`,\n fix: 'Check the configured path and try again',\n });\n\nexport const unresolvedGetLocaleBuildError = (path: string) =>\n createGtNextDiagnostic({\n severity: 'Error',\n whatHappened: `The file defining custom getLocale() could not be resolved at ${path}`,\n fix: 'Check the configured path and try again',\n });\n\nexport const conflictingConfigurationBuildError = (conflicts: string[]) =>\n `gt-next Error: Conflicting configuration${\n conflicts.length > 1 ? 's' : ''\n } detected. Resolve the following conflicts before building your app:\\n${conflicts.join(\n '\\n'\n )}`;\n\nexport const typesFileError = createGtNextDiagnostic({\n severity: 'Error',\n whatHappened: 'A types-only entry point was executed at runtime',\n fix: 'Import from the appropriate gt-next runtime entry point instead',\n});\n\nexport const gtProviderUseClientError =\n `The Next.js <GTProvider> was imported in a client component. This prevents gt-next from fetching translations on the server. ` +\n `Move <GTProvider> to a file without 'use client'. ` +\n `If you really need to put <GTProvider> on the client, import <GTClientProvider> from 'gt-next/client' instead (discouraged when using the Next.js App Router).`;\n\nexport const txUseClientError =\n `The <Tx> runtime translation component was rendered in a client component, which is not supported. ` +\n `Use <T> with variables, or render <Tx> from a server component.`;\n\nexport const missingVariablesError = (variables: string[], message: string) =>\n createGtNextDiagnostic({\n severity: 'Error',\n whatHappened: `The message \"${message}\" is missing variables: \"${variables.join('\", \"')}\"`,\n fix: 'Provide values for these variables before rendering the translation',\n });\n\nexport const createStringRenderError = (\n message: string,\n id: string | undefined,\n error?: unknown\n) =>\n createGtNextDiagnostic({\n severity: 'Error',\n whatHappened: `The string ${id ? `for id \"${id}\" ` : ''}could not be rendered`,\n fix: `Check the message syntax and variables for: \"${message}\"`,\n details: formatDiagnosticErrorDetails(error),\n });\n\nexport const invalidLocalesError = (locales: string[]) =>\n createGtNextDiagnostic({\n severity: 'Error',\n whatHappened: 'Invalid locale codes in your configuration',\n fix: 'Specify a list of valid locales or use \"customMapping\" to define aliases for the invalid locales',\n details: locales,\n });\n\nexport const invalidCanonicalLocalesError = (locales: string[]) =>\n createGtNextDiagnostic({\n severity: 'Error',\n whatHappened: 'Invalid canonical locale codes in your configuration',\n fix: 'Use valid BCP 47 locale codes before starting translation',\n details: locales,\n });\n\nexport const createInvalidIcuDictionaryEntryError = (id: string) =>\n createGtNextDiagnostic({\n severity: 'Error',\n whatHappened: `Dictionary entry \"${id}\" contains invalid ICU syntax`,\n fix: 'Fix the ICU message before rendering this translation',\n });\n\n// ---- WARNINGS ---- //\n\nexport const createInvalidIcuDictionaryEntryWarning = (id: string) =>\n createGtNextDiagnostic({\n whatHappened: `Dictionary entry \"${id}\" contains invalid ICU syntax`,\n wayOut: 'Source content will render as a fallback until the entry is fixed',\n });\n\nexport const createBadFilepathWarning = (filename: string, dir: string[]) =>\n createGtNextDiagnostic({\n whatHappened: `${filename} was found in ${dir.join(' or ')}, which is not supported`,\n fix: 'Move it to your project root so gt-next can load it',\n });\n\nexport const usingDefaultsWarning = createGtNextDiagnostic({\n whatHappened: 'The gt-next configuration could not be loaded',\n wayOut: 'Defaults will be used',\n fix: 'Check your config path if this was unexpected',\n});\n\nexport const createNoEntryFoundWarning = (id: string) =>\n createGtNextDiagnostic({\n whatHappened: `No valid dictionary entry was found for id \"${id}\"`,\n wayOut: 'Source content will render as a fallback',\n });\n\nexport const createInvalidDictionaryEntryWarning = (id: string) =>\n createGtNextDiagnostic({\n whatHappened: `Dictionary entry \"${id}\" is invalid`,\n wayOut: 'Source content will render as a fallback until the entry is fixed',\n });\n\nexport const createInvalidDictionaryTranslationEntryWarning = (id: string) =>\n createGtNextDiagnostic({\n whatHappened: `Dictionary translation entry \"${id}\" is invalid`,\n wayOut: 'Source content will render as a fallback until the entry is fixed',\n });\n\nexport const createUnsupportedLocalesWarning = (locales: string[]) =>\n `gt-next: The following locales are currently unsupported by our service: ${locales\n .map((locale) => {\n const { name } = getLocaleProperties(locale);\n return `${locale} (${name})`;\n })\n .join(', ')}`;\n\nexport const createMismatchingHashWarning = (\n expectedHash: string,\n receivedHash: string\n) =>\n createGtNextDiagnostic({\n whatHappened: 'Translation hashes do not match',\n reassurance: 'The translation will still render',\n fix: 'Update your translations to the newest version to avoid stale content',\n details: [`expected ${expectedHash}`, `received ${receivedHash}`],\n });\n\nexport const projectIdMissingWarn = createGtNextDiagnostic({\n whatHappened: 'Runtime translation needs a project ID',\n fix: 'Set GT_PROJECT_ID in your environment or pass projectId to withGTConfig()',\n docsUrl: 'https://generaltranslation.com/dashboard',\n});\n\nexport const noInitGTWarn =\n `gt-next: You are running General Translation without the withGTConfig() plugin. ` +\n `This means that you are not translating your app. To activate translation, add the withGTConfig() plugin to your app, ` +\n `and set the projectId and apiKey in your environment. ` +\n `For more information, visit https://generaltranslation.com/docs/next/tutorials/quickstart`;\n\nexport const APIKeyMissingWarn = createGtNextPluginDiagnostic({\n whatHappened: 'Runtime translation needs a development API key',\n fix: 'Find your development API key at generaltranslation.com/dashboard, or set runtimeUrl to an empty string to disable runtime translation',\n});\n\nexport const createTranslationLoadingWarning = ({\n source,\n translation,\n id,\n}: {\n source: string;\n translation: string;\n id?: string;\n}) =>\n `[DEV ONLY] Warning: gt-next created translation \"${source}\" -> \"${translation}\"` +\n (id ? ` for id \"${id}\"` : '') +\n `. ` +\n `In development, hot-reloaded translations may not be be displayed until the page is refreshed. ` +\n `In production, translations will be preloaded and there won't be a warning.`;\n\nexport const runtimeTranslationTimeoutWarning = createGtNextDiagnostic({\n whatHappened: 'Runtime translation timed out',\n});\n\nexport const dictionaryNotFoundWarning = createGtNextDiagnostic({\n whatHappened: 'No dictionary was found',\n fix: 'Add dictionary.js or [defaultLocale].json to your project, and make sure withGTConfig() is enabled',\n});\n\nexport const standardizedLocalesWarning = (locales: string[]) =>\n `gt-next: The following locales were standardized: ${locales.join(', ')}. Use the standardized codes in your config to avoid this warning.`;\n\nexport const standardizedCanonicalLocalesWarning = (locales: string[]) =>\n `gt-next: The following canonical locales were standardized: ${locales.join(', ')}. Use the standardized codes in your config to avoid this warning.`;\n\nexport const deprecatedLocaleMappingWarning = `gt-next: You are using the deprecated localeMapping configuration. Please move \"customMapping\" to your gt.config.json file.`;\n\nexport const createGTCompilerUnresolvedWarning = (type: 'babel' | 'swc') =>\n `gt-next (plugin): The GT ${type} compiler could not be resolved. Skipping compiler optimizations.`;\n\nexport const createGTCompilerUnavailableWarning = (type: 'babel' | 'swc') =>\n type === 'swc'\n ? `gt-next (plugin): The GT swc compiler is compatible with < next@${SWC_PLUGIN_SUPPORT}. Skipping compiler optimizations.`\n : `gt-next (plugin): The GT babel compiler requires react@${BABEL_PLUGIN_SUPPORT} or newer. Skipping compiler optimizations.`;\n\nexport const babelCompilerTurbopackUnavailableWarning =\n `gt-next (plugin): The GT babel compiler is not compatible with Turbopack. ` +\n `To use compiler optimizations with Turbopack, set experimentalCompilerOptions: { type: 'swc' }.`;\n\nexport const disablingCompileTimeHashWarning = `gt-next (plugin): Compile-time hash is disabled. Compiler optimizations are inactive.`;\n\nexport const createStringRenderWarning = (\n message: string,\n id: string | undefined,\n error?: unknown\n) =>\n createGtNextDiagnostic({\n whatHappened: `The string ${id ? `for id \"${id}\" ` : ''}could not be rendered`,\n wayOut: 'Source content will render as a fallback',\n fix: `Check the message syntax and variables for: \"${message}\"`,\n details: formatDiagnosticErrorDetails(error),\n });\n\nexport const swcPluginCompatibilityChangeWarning = `gt-next (plugin): As of gt-next@6.12.4, SWC plugin support is disabled for Next.js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ACX;AAKF,MAAa,oBAAoBC,2BAAAA,6BAA6B;CAC5D,cAAc;CACd,KAAK;CACN,CAAC;AAEF,MAAa,mCAAmC,EAC9C,QACA,aACA,SAMA,oDAAoD,OAAO,QAAQ,YAAY,MAC9E,KAAK,YAAY,GAAG,KAAK,MAC1B;AAIF,MAAa,mCAAmCD,2BAAAA,uBAAuB,EACrE,cAAc,iCACf,CAAC;AAEF,MAAa,4BAA4BA,2BAAAA,uBAAuB;CAC9D,cAAc;CACd,KAAK;CACN,CAAC;AAEF,MAAa,8BAA8B,YACzC,qDAAqD,QAAQ,KAAK,KAAK,CAAC;AAE1E,MAAa,uCAAuC,YAClD,+DAA+D,QAAQ,KAAK,KAAK,CAAC;AAEpF,MAAa,iCAAiC;AAE9C,MAAa,qCAAqC,SAChD,4BAA4B,KAAK;AAEnC,MAAa,sCAAsC,SACjD,SAAS,QACL,mEAAmEE,yBAAAA,mBAAmB,sCACtF,0DAA0DC,yBAAAA,qBAAqB;AAErF,MAAa,2CACX;AAGF,MAAa,kCAAkC;AAE/C,MAAa,6BACX,SACA,IACA,UAEAH,2BAAAA,uBAAuB;CACrB,cAAc,cAAc,KAAK,WAAW,GAAG,MAAM,GAAG;CACxD,QAAQ;CACR,KAAK,gDAAgD,QAAQ;CAC7D,UAAA,GAAA,4BAAA,8BAAsC,MAAM;CAC7C,CAAC;AAEJ,MAAa,sCAAsC,wGAAwGE,yBAAAA,mBAAmB"}
|
|
1
|
+
{"version":3,"file":"createErrors.js","names":["createGtNextDiagnostic","createGtNextPluginDiagnostic","SWC_PLUGIN_SUPPORT","BABEL_PLUGIN_SUPPORT"],"sources":["../../src/errors/createErrors.ts"],"sourcesContent":["// ---- ERRORS ---- //\n\nimport { getLocaleProperties } from '@generaltranslation/format';\nimport {\n createGtNextDiagnostic,\n createGtNextPluginDiagnostic,\n formatDiagnosticErrorDetails,\n} from './diagnostics';\nimport { BABEL_PLUGIN_SUPPORT, SWC_PLUGIN_SUPPORT } from '../plugin/constants';\n\nexport const remoteTranslationsError = createGtNextDiagnostic({\n severity: 'Error',\n whatHappened: 'Remote translations could not be loaded',\n fix: 'Check your project ID, API key, and network connection, then try again',\n wayOut: 'Source content will render as a fallback',\n});\n\nexport const customLoadTranslationsError = (locale: string = '') =>\n createGtNextDiagnostic({\n severity: 'Error',\n whatHappened: `Locally stored translations could not be loaded${locale ? ` for \"${locale}\"` : ''}`,\n fix: 'If you use loadTranslations(), make sure it returns translations for the requested locale',\n });\n\nexport const customLoadDictionaryWarning = (locale: string = '') =>\n createGtNextDiagnostic({\n severity: 'Warning',\n whatHappened: `The local dictionary could not be loaded${locale ? ` for \"${locale}\"` : ''}`,\n fix: 'If you use loadDictionary(), make sure it returns a dictionary for the requested locale',\n });\n\nexport const createUnresolvedNextVersionError = (error: Error) =>\n createGtNextDiagnostic({\n severity: 'Error',\n whatHappened: 'The installed Next.js version could not be resolved',\n fix: 'Check that next is installed in this project',\n details: error.message,\n });\n\nexport const createUnresolvedReactVersionError = (error: Error) =>\n createGtNextDiagnostic({\n severity: 'Error',\n whatHappened: 'The installed React version could not be resolved',\n fix: 'Check that react is installed in this project',\n details: error.message,\n });\n\nexport const createStringTranslationError = (\n string: string,\n id?: string,\n functionName = 'tx'\n) =>\n createGtNextDiagnostic({\n severity: 'Error',\n whatHappened: `${functionName}(\"${string}\")${id ? ` with id \"${id}\"` : ''} could not find a translation`,\n wayOut: 'Source content will render as a fallback',\n fix: 'Push translations again or check your dictionary/runtime translation configuration',\n });\n\nexport const createDictionaryTranslationError = (id: string) =>\n createGtNextDiagnostic({\n severity: 'Error',\n whatHappened: `Dictionary translation entry \"${id}\" could not be found`,\n fix: 'Check that the id exists in your dictionary or push translations again',\n });\n\nexport const createRequiredPrefixError = (id: string, requiredPrefix: string) =>\n createGtNextDiagnostic({\n severity: 'Error',\n whatHappened: `<GTProvider> is scoped to prefix \"${requiredPrefix}\", but a child uses id \"${id}\"`,\n fix: 'Change the <GTProvider> id prop or move the child under the matching dictionary subtree',\n });\n\nexport const devApiKeyIncludedInProductionError = createGtNextDiagnostic({\n severity: 'Error',\n whatHappened: 'Production builds cannot use a development API key',\n fix: 'Replace it with a production API key',\n});\n\nexport const createDictionarySubsetError = (id: string, functionName: string) =>\n createGtNextDiagnostic({\n severity: 'Error',\n whatHappened: `${functionName} with id \"${id}\" could not read a valid dictionary subtree`,\n fix: 'Make sure the id maps to the correct subroute of the dictionary',\n });\n\nexport const dictionaryDisabledError = createGtNextDiagnostic({\n severity: 'Error',\n whatHappened: 'Dictionaries are not enabled',\n fix: 'Add the withGTConfig() plugin to your Next.js config before using dictionary translations',\n docsUrl: 'https://generaltranslation.com/docs',\n});\n\nexport const unresolvedCustomLoadDictionaryError = createGtNextDiagnostic({\n severity: 'Error',\n whatHappened:\n 'loadDictionary() was found during the build but could not be resolved at runtime',\n fix: 'Export a loadDictionary() function from the configured file',\n});\n\nexport const unresolvedCustomLoadTranslationsError = createGtNextDiagnostic({\n severity: 'Error',\n whatHappened:\n 'loadTranslations() was found during the build but could not be resolved at runtime',\n fix: 'Export a loadTranslations() function from the configured file',\n});\n\nexport const unresolvedLoadDictionaryBuildError = (path: string) =>\n createGtNextDiagnostic({\n severity: 'Error',\n whatHappened: `The file defining loadDictionary() could not be resolved at ${path}`,\n fix: 'Check the configured path and try again',\n });\n\nexport const unresolvedLoadTranslationsBuildError = (path: string) =>\n createGtNextDiagnostic({\n severity: 'Error',\n whatHappened: `The file defining loadTranslations() could not be resolved at ${path}`,\n fix: 'Check the configured path and try again',\n });\n\nexport const unresolvedGetLocaleBuildError = (path: string) =>\n createGtNextDiagnostic({\n severity: 'Error',\n whatHappened: `The file defining custom getLocale() could not be resolved at ${path}`,\n fix: 'Check the configured path and try again',\n });\n\nexport const conflictingConfigurationBuildError = (conflicts: string[]) =>\n `gt-next Error: Conflicting configuration${\n conflicts.length > 1 ? 's' : ''\n } detected. Resolve the following conflicts before building your app:\\n${conflicts.join(\n '\\n'\n )}`;\n\nexport const typesFileError = createGtNextDiagnostic({\n severity: 'Error',\n whatHappened: 'A types-only entry point was executed at runtime',\n fix: 'Import from the appropriate gt-next runtime entry point instead',\n});\n\nexport const gtProviderUseClientError =\n `The Next.js <GTProvider> was imported in a client component. This prevents gt-next from fetching translations on the server. ` +\n `Move <GTProvider> to a file without 'use client'. ` +\n `If you really need to put <GTProvider> on the client, import <GTClientProvider> from 'gt-next/client' instead (discouraged when using the Next.js App Router).`;\n\nexport const txUseClientError =\n `The <Tx> runtime translation component was rendered in a client component, which is not supported. ` +\n `Use <T> with variables, or render <Tx> from a server component.`;\n\nexport const missingVariablesError = (variables: string[], message: string) =>\n createGtNextDiagnostic({\n severity: 'Error',\n whatHappened: `The message \"${message}\" is missing variables: \"${variables.join('\", \"')}\"`,\n fix: 'Provide values for these variables before rendering the translation',\n });\n\nexport const createStringRenderError = (\n message: string,\n id: string | undefined,\n error?: unknown\n) =>\n createGtNextDiagnostic({\n severity: 'Error',\n whatHappened: `The string ${id ? `for id \"${id}\" ` : ''}could not be rendered`,\n fix: `Check the message syntax and variables for: \"${message}\"`,\n details: formatDiagnosticErrorDetails(error),\n });\n\nexport const invalidLocalesError = (locales: string[]) =>\n createGtNextDiagnostic({\n severity: 'Error',\n whatHappened: 'Invalid locale codes in your configuration',\n fix: 'Specify a list of valid locales or use \"customMapping\" to define aliases for the invalid locales',\n details: locales,\n });\n\nexport const invalidCanonicalLocalesError = (locales: string[]) =>\n createGtNextDiagnostic({\n severity: 'Error',\n whatHappened: 'Invalid canonical locale codes in your configuration',\n fix: 'Use valid BCP 47 locale codes before starting translation',\n details: locales,\n });\n\nexport const createInvalidRequestLocaleWarning = (\n locale: string,\n defaultLocale: string\n) =>\n createGtNextDiagnostic({\n severity: 'Warning',\n whatHappened: `Locale \"${locale}\" is not valid or is not supported by this app`,\n wayOut: `The default locale \"${defaultLocale}\" will be used for this request`,\n fix: 'Use a valid BCP 47 locale code, add a custom mapping, or configure the locale in gt-next',\n });\n\nexport const createInvalidIcuDictionaryEntryError = (id: string) =>\n createGtNextDiagnostic({\n severity: 'Error',\n whatHappened: `Dictionary entry \"${id}\" contains invalid ICU syntax`,\n fix: 'Fix the ICU message before rendering this translation',\n });\n\n// ---- WARNINGS ---- //\n\nexport const createInvalidIcuDictionaryEntryWarning = (id: string) =>\n createGtNextDiagnostic({\n whatHappened: `Dictionary entry \"${id}\" contains invalid ICU syntax`,\n wayOut: 'Source content will render as a fallback until the entry is fixed',\n });\n\nexport const createBadFilepathWarning = (filename: string, dir: string[]) =>\n createGtNextDiagnostic({\n whatHappened: `${filename} was found in ${dir.join(' or ')}, which is not supported`,\n fix: 'Move it to your project root so gt-next can load it',\n });\n\nexport const usingDefaultsWarning = createGtNextDiagnostic({\n whatHappened: 'The gt-next configuration could not be loaded',\n wayOut: 'Defaults will be used',\n fix: 'Check your config path if this was unexpected',\n});\n\nexport const createNoEntryFoundWarning = (id: string) =>\n createGtNextDiagnostic({\n whatHappened: `No valid dictionary entry was found for id \"${id}\"`,\n wayOut: 'Source content will render as a fallback',\n });\n\nexport const createInvalidDictionaryEntryWarning = (id: string) =>\n createGtNextDiagnostic({\n whatHappened: `Dictionary entry \"${id}\" is invalid`,\n wayOut: 'Source content will render as a fallback until the entry is fixed',\n });\n\nexport const createInvalidDictionaryTranslationEntryWarning = (id: string) =>\n createGtNextDiagnostic({\n whatHappened: `Dictionary translation entry \"${id}\" is invalid`,\n wayOut: 'Source content will render as a fallback until the entry is fixed',\n });\n\nexport const createUnsupportedLocalesWarning = (locales: string[]) =>\n `gt-next: The following locales are currently unsupported by our service: ${locales\n .map((locale) => {\n const { name } = getLocaleProperties(locale);\n return `${locale} (${name})`;\n })\n .join(', ')}`;\n\nexport const createMismatchingHashWarning = (\n expectedHash: string,\n receivedHash: string\n) =>\n createGtNextDiagnostic({\n whatHappened: 'Translation hashes do not match',\n reassurance: 'The translation will still render',\n fix: 'Update your translations to the newest version to avoid stale content',\n details: [`expected ${expectedHash}`, `received ${receivedHash}`],\n });\n\nexport const projectIdMissingWarn = createGtNextDiagnostic({\n whatHappened: 'Runtime translation needs a project ID',\n fix: 'Set GT_PROJECT_ID in your environment or pass projectId to withGTConfig()',\n docsUrl: 'https://generaltranslation.com/dashboard',\n});\n\nexport const noInitGTWarn =\n `gt-next: You are running General Translation without the withGTConfig() plugin. ` +\n `This means that you are not translating your app. To activate translation, add the withGTConfig() plugin to your app, ` +\n `and set the projectId and apiKey in your environment. ` +\n `For more information, visit https://generaltranslation.com/docs/next/tutorials/quickstart`;\n\nexport const APIKeyMissingWarn = createGtNextPluginDiagnostic({\n whatHappened: 'Runtime translation needs a development API key',\n fix: 'Find your development API key at generaltranslation.com/dashboard, or set runtimeUrl to an empty string to disable runtime translation',\n});\n\nexport const createTranslationLoadingWarning = ({\n source,\n translation,\n id,\n}: {\n source: string;\n translation: string;\n id?: string;\n}) =>\n `[DEV ONLY] Warning: gt-next created translation \"${source}\" -> \"${translation}\"` +\n (id ? ` for id \"${id}\"` : '') +\n `. ` +\n `In development, hot-reloaded translations may not be be displayed until the page is refreshed. ` +\n `In production, translations will be preloaded and there won't be a warning.`;\n\nexport const runtimeTranslationTimeoutWarning = createGtNextDiagnostic({\n whatHappened: 'Runtime translation timed out',\n});\n\nexport const dictionaryNotFoundWarning = createGtNextDiagnostic({\n whatHappened: 'No dictionary was found',\n fix: 'Add dictionary.js or [defaultLocale].json to your project, and make sure withGTConfig() is enabled',\n});\n\nexport const standardizedLocalesWarning = (locales: string[]) =>\n `gt-next: The following locales were standardized: ${locales.join(', ')}. Use the standardized codes in your config to avoid this warning.`;\n\nexport const standardizedCanonicalLocalesWarning = (locales: string[]) =>\n `gt-next: The following canonical locales were standardized: ${locales.join(', ')}. Use the standardized codes in your config to avoid this warning.`;\n\nexport const deprecatedLocaleMappingWarning = `gt-next: You are using the deprecated localeMapping configuration. Please move \"customMapping\" to your gt.config.json file.`;\n\nexport const createGTCompilerUnresolvedWarning = (type: 'babel' | 'swc') =>\n `gt-next (plugin): The GT ${type} compiler could not be resolved. Skipping compiler optimizations.`;\n\nexport const createGTCompilerUnavailableWarning = (type: 'babel' | 'swc') =>\n type === 'swc'\n ? `gt-next (plugin): The GT swc compiler is compatible with < next@${SWC_PLUGIN_SUPPORT}. Skipping compiler optimizations.`\n : `gt-next (plugin): The GT babel compiler requires react@${BABEL_PLUGIN_SUPPORT} or newer. Skipping compiler optimizations.`;\n\nexport const babelCompilerTurbopackUnavailableWarning =\n `gt-next (plugin): The GT babel compiler is not compatible with Turbopack. ` +\n `To use compiler optimizations with Turbopack, set experimentalCompilerOptions: { type: 'swc' }.`;\n\nexport const disablingCompileTimeHashWarning = `gt-next (plugin): Compile-time hash is disabled. Compiler optimizations are inactive.`;\n\nexport const createStringRenderWarning = (\n message: string,\n id: string | undefined,\n error?: unknown\n) =>\n createGtNextDiagnostic({\n whatHappened: `The string ${id ? `for id \"${id}\" ` : ''}could not be rendered`,\n wayOut: 'Source content will render as a fallback',\n fix: `Check the message syntax and variables for: \"${message}\"`,\n details: formatDiagnosticErrorDetails(error),\n });\n\nexport const swcPluginCompatibilityChangeWarning = `gt-next (plugin): As of gt-next@6.12.4, SWC plugin support is disabled for Next.js versions prior to ${SWC_PLUGIN_SUPPORT}. Update to the latest version of Next.js.`;\n"],"mappings":";;;;;;;AAUA,MAAa,0BAA0BA,2BAAAA,uBAAuB;CAC5D,UAAU;CACV,cAAc;CACd,KAAK;CACL,QAAQ;CACT,CAAC;AAEF,MAAa,+BAA+B,SAAiB,OAC3DA,2BAAAA,uBAAuB;CACrB,UAAU;CACV,cAAc,kDAAkD,SAAS,SAAS,OAAO,KAAK;CAC9F,KAAK;CACN,CAAC;AAEJ,MAAa,+BAA+B,SAAiB,OAC3DA,2BAAAA,uBAAuB;CACrB,UAAU;CACV,cAAc,2CAA2C,SAAS,SAAS,OAAO,KAAK;CACvF,KAAK;CACN,CAAC;AAEJ,MAAa,oCAAoC,UAC/CA,2BAAAA,uBAAuB;CACrB,UAAU;CACV,cAAc;CACd,KAAK;CACL,SAAS,MAAM;CAChB,CAAC;A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YAClD,+DAA+D,QAAQ,KAAK,KAAK,CAAC;AAEpF,MAAa,iCAAiC;AAE9C,MAAa,qCAAqC,SAChD,4BAA4B,KAAK;AAEnC,MAAa,sCAAsC,SACjD,SAAS,QACL,mEAAmEE,yBAAAA,mBAAmB,sCACtF,0DAA0DC,yBAAAA,qBAAqB;AAErF,MAAa,2CACX;AAGF,MAAa,kCAAkC;AAE/C,MAAa,6BACX,SACA,IACA,UAEAH,2BAAAA,uBAAuB;CACrB,cAAc,cAAc,KAAK,WAAW,GAAG,MAAM,GAAG;CACxD,QAAQ;CACR,KAAK,gDAAgD,QAAQ;CAC7D,UAAA,GAAA,4BAAA,8BAAsC,MAAM;CAC7C,CAAC;AAEJ,MAAa,sCAAsC,wGAAwGE,yBAAAA,mBAAmB"}
|
package/dist/index.types.d.ts
CHANGED
|
@@ -257,6 +257,7 @@ export declare const LocaleSelector: typeof _LocaleSelector;
|
|
|
257
257
|
* @param {string} [options.$context] - Additional context for the translation.
|
|
258
258
|
* @param {string} [options.$id] - Optional identifier for the translation string.
|
|
259
259
|
* @param {number} [options.$maxChars] - Maximum number of characters for the translated message.
|
|
260
|
+
* @param {boolean} [options.$requiresReview] - Whether the translated message requires approval before use. Must be a boolean literal.
|
|
260
261
|
* @param {StringFormat} [options.$format] - The data format for the message (e.g., 'ICU', 'STRING'). Defaults to 'ICU'.
|
|
261
262
|
*
|
|
262
263
|
* @example
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.types.d.ts","sourceRoot":"","sources":["../src/index.types.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,UAAU,IAAI,WAAW,EAAE,MAAM,uBAAuB,CAAC;AAClE,OAAO,EAAE,CAAC,IAAI,EAAE,EAAE,MAAM,0BAA0B,CAAC;AACnD,OAAO,EACL,eAAe,IAAI,gBAAgB,EACnC,SAAS,IAAI,UAAU,EACvB,UAAU,IAAI,WAAW,EACzB,gBAAgB,IAAI,iBAAiB,EACrC,UAAU,IAAI,WAAW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V,MAAM,EACN,UAAU,EACV,UAAU,GACX,CAAC;AAEF,wCAAwC;AACxC,OAAO,EAAE,aAAa,EAAE,CAAC"}
|
package/dist/index.types.js
CHANGED
|
@@ -300,6 +300,7 @@ const LocaleSelector = () => {
|
|
|
300
300
|
* @param {string} [options.$context] - Additional context for the translation.
|
|
301
301
|
* @param {string} [options.$id] - Optional identifier for the translation string.
|
|
302
302
|
* @param {number} [options.$maxChars] - Maximum number of characters for the translated message.
|
|
303
|
+
* @param {boolean} [options.$requiresReview] - Whether the translated message requires approval before use. Must be a boolean literal.
|
|
303
304
|
* @param {StringFormat} [options.$format] - The data format for the message (e.g., 'ICU', 'STRING'). Defaults to 'ICU'.
|
|
304
305
|
*
|
|
305
306
|
* @example
|
package/dist/index.types.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.types.js","names":["typesFileError"],"sources":["../src/index.types.ts"],"sourcesContent":["import { typesFileError } from './errors/createErrors';\nimport { GTProvider as _GTProvider } from './provider/GTProvider';\nimport { T as _T } from './server-dir/buildtime/T';\nimport {\n useTranslations as _useTranslations,\n useLocale as _useLocale,\n useLocales as _useLocales,\n useDefaultLocale as _useDefaultLocale,\n useGTClass as _useGTClass,\n useLocaleProperties as _useLocaleProperties,\n Currency as _Currency,\n DateTime as _DateTime,\n RelativeTime as _RelativeTime,\n Num as _Num,\n Var as _Var,\n Branch as _Branch,\n Plural as _Plural,\n LocaleSelector as _LocaleSelector,\n RegionSelector as _RegionSelector,\n useLocaleDirection as _useLocaleDirection,\n useVersionId as _useVersionId,\n} from 'gt-react/client';\nimport type {\n DictionaryTranslationOptions,\n InlineTranslationOptions,\n RuntimeTranslationOptions,\n} from 'gt-react';\nimport type { StringFormat } from '@generaltranslation/format/types';\nimport {\n msg,\n decodeMsg,\n decodeOptions,\n declareStatic,\n derive,\n declareVar,\n decodeVars,\n _Messages,\n Static as _Static,\n Derive as _Derive,\n mFallback,\n gtFallback,\n} from 'gt-react/internal';\n\n/**\n * Provides General Translation context to its children, which can then access `useGT`, `useLocale`, and `useDefaultLocale`.\n *\n * @param {React.ReactNode} children - The children components that will use the translation context.\n * @param {string} id - ID of a nested dictionary, so that only a subset of a large dictionary needs to be sent to the client.\n * @param {string} locale - The locale to use for the translation context.\n *\n * @returns {JSX.Element} The provider component for General Translation context.\n */\nexport const GTProvider: typeof _GTProvider = () => {\n throw new Error(typesFileError);\n};\n\n/**\n * Build-time translation component that renders its children in the user's given locale.\n *\n * @example\n * ```jsx\n * // Basic usage:\n * <T id=\"welcome_message\">\n * Hello, <Var>{name}</Var>!\n * </T>\n * ```\n *\n * @example\n * ```jsx\n * // Translating a plural\n * <T id=\"item_count\">\n * <Plural n={3} singular={<>You have <Num children={n}/> item.</>}>\n * You have <Num children={n}/> items.\n * </Plural>\n * </T>\n * ```\n *\n * @param {React.ReactNode} children - The content to be translated or displayed.\n * @param {string} [id] - Optional identifier for the translation string. If not provided, a hash will be generated from the content.\n * @param {any} [context] - Additional context for translation key generation.\n *\n * @returns {JSX.Element} The rendered translation or fallback content based on the provided configuration.\n *\n * @throws {Error} If a plural translation is requested but the `n` option is not provided.\n */\nexport const T: typeof _T = () => {\n throw new Error(typesFileError);\n};\n/** @internal _gtt - The GT transformation for the component. */\nT._gtt = 'translate';\n\n/**\n * The `<Currency>` component renders a formatted currency string, allowing customization of name, default value, currency type, and formatting options.\n *\n * @example\n * ```jsx\n * <Currency\n * currency=\"USD\"\n * >\n * 1000\n * </Currency>\n * ```\n *\n * @param {any} [children] - Optional content to render inside the currency component.\n * @param {string} [currency] - The currency type (e.g., USD, EUR, etc.).\n * @param {Intl.NumberFormatOptions} [options] - Optional formatting options to customize how the currency is displayed.\n * @returns {React.JSX.Element} The formatted currency component.\n */\nexport const Currency: typeof _Currency = () => {\n throw new Error(typesFileError);\n};\n/** @internal _gtt - The GT transformation for the component. */\nCurrency._gtt = 'variable-currency';\n\n/**\n * The `<DateTime>` component renders a formatted date or time string, allowing customization of the name, default value, and formatting options.\n * It utilizes the current locale and optional format settings to display the date.\n *\n * @example\n * ```jsx\n * <DateTime>\n * {new Date()}\n * </DateTime>\n * ```\n *\n * @param {any} [children] - Optional content (typically a date) to render inside the component.\n * @param {Intl.DateTimeFormatOptions} [options={}] - Optional formatting options for the date, following `Intl.DateTimeFormatOptions` specifications.\n * @returns {Promise<React.JSX.Element>} The formatted date or time component.\n */\nexport const DateTime: typeof _DateTime = () => {\n throw new Error(typesFileError);\n};\n/** @internal _gtt - The GT transformation for the component. */\nDateTime._gtt = 'variable-datetime';\n\n/**\n * The `<RelativeTime>` component renders a localized relative time string\n * (e.g., \"2 hours ago\", \"in 3 days\") using `Intl.RelativeTimeFormat`.\n *\n * @example\n * ```jsx\n * <RelativeTime date={someDate} />\n * ```\n *\n * @param {Date} [date] - A date to compute relative time from now.\n * @param {number} [value] - Explicit numeric value. Requires `unit`.\n * @param {Intl.RelativeTimeFormatUnit} [unit] - The unit of time.\n * @param {Date} [baseDate] - Base date for computing relative time. Defaults to `new Date()` at render time. Required for hydration safety.\n * @param {Intl.RelativeTimeFormatOptions} [options={}] - Formatting options.\n * @returns {Promise<React.JSX.Element>} The formatted relative time component.\n */\nexport const RelativeTime: typeof _RelativeTime = () => {\n throw new Error(typesFileError);\n};\n/** @internal _gtt - The GT transformation for the component. */\nRelativeTime._gtt = 'variable-relative-time';\n\n/**\n * The `<Num>` component renders a formatted number string, allowing customization of the name, default value, and formatting options.\n * It formats the number according to the current locale and optionally passed formatting options.\n *\n * @example\n * ```jsx\n * <Num\n * options={{ style: \"decimal\", maximumFractionDigits: 2 }}\n * >\n * 1000\n * </Num>\n * ```\n *\n * @param {any} [children] - Optional content (typically a number) to render inside the component.\n * @param {Intl.NumberFormatOptions} [options={}] - Optional formatting options for the number, following `Intl.NumberFormatOptions` specifications.\n * @returns {React.JSX.Element} The formatted number component.\n */\nexport const Num: typeof _Num = () => {\n throw new Error(typesFileError);\n};\n/** @internal _gtt - The GT transformation for the component. */\nNum._gtt = 'variable-number';\n\n/**\n * The `<Var>` component renders a variable value, which can either be passed as `children` or a `value`.\n * If `children` is provided, it will be used; otherwise, the `value` is rendered.\n *\n * @example\n * ```jsx\n * <Var>\n * John\n * </Var>\n * ```\n *\n * @param {any} [children] - The content to render inside the component. If provided, it will take precedence over `value`.\n * @returns {React.JSX.Element} The rendered variable component with either `children` or `value`.\n */\nexport const Var: typeof _Var = () => {\n throw new Error(typesFileError);\n};\n/** @internal _gtt - The GT transformation for the component. */\nVar._gtt = 'variable-variable';\n\n/**\n * Marks JSX children as derivable by the GT compiler and CLI.\n *\n * Use `<Derive>` inside translated JSX when child content is computed from\n * source code, but should still be discovered during extraction instead of\n * treated as a runtime interpolation variable. The CLI attempts to resolve the\n * derivable children into every possible static value and includes those values\n * in the source content that gets translated.\n *\n * `<Derive>` renders its children unchanged at runtime.\n *\n * Run `gt validate` after adding or changing `<Derive>` usage to verify that\n * each derivable expression can be resolved by the CLI before translating or\n * building.\n *\n * @example\n * ```jsx\n * function getSubject() {\n * return (Math.random() > 0.5) ? \"Alice\" : \"Brian\";\n * }\n * ...\n * <T>\n * <Derive>\n * {getSubject()}\n * </Derive>\n * is going to school today.\n * </T>\n * ```\n *\n * @param {T extends React.ReactNode} children - JSX content to derive for translation extraction.\n * @returns {T} The same children, unchanged at runtime.\n */\nexport const Derive: typeof _Derive = () => {\n throw new Error(typesFileError);\n};\n/** @internal _gtt - The GT transformation for the component. */\nDerive._gtt = 'derive';\n\n/**\n * @deprecated Use `<Derive>` instead.\n *\n * Marks JSX children as derivable by the GT compiler and CLI.\n *\n * Use `<Derive>` instead of `<Static>` for new code. This alias is kept for\n * backwards compatibility and renders its children unchanged at runtime.\n *\n * Run `gt validate` after adding or changing derived JSX content to verify that\n * each derivable expression can be resolved by the CLI before translating or\n * building.\n *\n * @example\n * ```jsx\n * function getSubject() {\n * return (Math.random() > 0.5) ? \"Alice\" : \"Brian\";\n * }\n * ...\n * <T>\n * <Static>\n * {getSubject()}\n * </Static>\n * is going to school today.\n * </T>\n * ```\n *\n * @param {T extends React.ReactNode} children - JSX content to derive for translation extraction.\n * @returns {T} The same children, unchanged at runtime.\n */\nexport const Static: typeof _Static = () => {\n throw new Error(typesFileError);\n};\n/** @internal _gtt - The GT transformation for the component. */\nStatic._gtt = 'derive';\n\n/**\n * The `<Branch>` component dynamically renders a specified branch of content or a fallback child component.\n * It allows for flexible content switching based on the `branch` prop and an object of possible branches (`...branches`).\n * If the specified `branch` is present in the `branches` object, it renders the content of that branch.\n * If the `branch` is not found, it renders the provided `children` as fallback content.\n *\n * @example\n * ```jsx\n * <Branch\n * branch=\"summary\"\n * summary={<p>This is a summary</p>}\n * details={<p>Details here</p>}\n * >\n * <p>Fallback content</p>\n * </Branch>\n * ```\n * If the `branch` prop is set to `\"summary\"`, it will render `<p>This is a summary</p>`. If the `branch` is not set or does not match any keys in the branches object, it renders the fallback content `<p>Fallback content</p>`.\n *\n * @param {any} [children] - Fallback content to render if no matching branch is found.\n * @param {string} [name=\"branch\"] - Optional name for the component, used for metadata or tracking purposes.\n * @param {string} [branch] - The name of the branch to render. The component looks for this key in the `...branches` object.\n * @param {...{[key: string]: any}} [branches] - A spread object containing possible branches as keys and their corresponding content as values.\n * @returns {React.JSX.Element} The rendered branch or fallback content.\n */\nexport const Branch: typeof _Branch = () => {\n throw new Error(typesFileError);\n};\n/** @internal _gtt - The GT transformation for the component. */\nBranch._gtt = 'branch';\n\n/**\n * The `<Plural>` component dynamically renders content based on the plural form of the given number (`n`).\n * It determines which content to display by matching the value of `n` to the appropriate pluralization branch,\n * based on the current locale or a default locale. If no matching plural branch is found, the component renders\n * the fallback `children` content.\n *\n * @example\n * ```jsx\n * <Plural\n * n={1}\n * one=\"There is 1 item\"\n * other=\"There are {n} items\"\n * />\n * ```\n * In this example, if `n` is 1, it renders `\"There is 1 item\"`. If `n` is a different number, it renders\n * `\"There are {n} items\"`.\n *\n * @param {any} [children] - Fallback content to render if no matching plural branch is found.\n * @param {number} [n] - The number used to determine the plural form. This is required for pluralization to work.\n * @param {string} [locale] - Optional parameter, the locale to use for pluralization format.\n * @param {...{[key: string]: any}} [branches] - A spread object containing possible plural branches, typically including `one` for singular\n * and `other` for plural forms, but it may vary depending on the locale.\n * @returns {React.JSX.Element} The rendered content corresponding to the plural form of `n`, or the fallback content.\n * @throws {Error} If `n` is not provided or not a valid number.\n */\nexport const Plural: typeof _Plural = () => {\n throw new Error(typesFileError);\n};\n/** @internal _gtt - The GT transformation for the component. */\nPlural._gtt = 'plural';\n\n/**\n * A dropdown component that allows users to select a locale.\n * @param {string[]} locales - An optional list of locales to use for the dropdown. If not provided, the list of locales from the `<GTProvider>` context is used.\n * @param {object} customNames - An optional object to map locales to custom names.\n * @returns {React.ReactElement | null} The rendered locale dropdown component or null to prevent rendering.\n */\nexport const LocaleSelector: typeof _LocaleSelector = () => {\n throw new Error(typesFileError);\n};\n\n/**\n * Returns the string translation function `t`.\n *\n * @returns {Function} A translation function that accepts an ICU format string and returns that ICU format string translated.\n * @param {InlineTranslationOptions} [options] - Translation options including variables and special `$`-prefixed options.\n * @param {string} [options.$context] - Additional context for the translation.\n * @param {string} [options.$id] - Optional identifier for the translation string.\n * @param {number} [options.$maxChars] - Maximum number of characters for the translated message.\n * @param {StringFormat} [options.$format] - The data format for the message (e.g., 'ICU', 'STRING'). Defaults to 'ICU'.\n *\n * @example\n * const t = useGT();\n * console.log(t('To be or not to be...'));\n *\n * const t = useGT();\n * return (<>\n * {\n * t('My name is {customName}', { customName: \"Brian\" } )\n * }\n * </>);\n *\n */\nexport const useGT: (\n _messages?: _Messages\n) => (message: string, options?: InlineTranslationOptions) => string = () => {\n throw new Error(typesFileError);\n};\n\n/**\n * Returns the dictionary access function `t`.\n *\n * @param {string} [id] - Optional prefix to prepend to the translation keys.\n * @returns {Function} A translation function that accepts a key string and returns the translated value.\n * The returned function accepts `DictionaryTranslationOptions` which includes:\n * - `$format` - The data format for the message (e.g., 'ICU', 'STRING'). Defaults to 'ICU'.\n * - `$maxChars` - Maximum number of characters for the translated message.\n *\n * @example\n * const t = useTranslations('user');\n * console.log(t('name')); // Translates item 'user.name'\n *\n * const t = useTranslations();\n * console.log(t('hello')); // Translates item 'hello'\n */\nexport const useTranslations: typeof _useTranslations = () => {\n throw new Error(typesFileError);\n};\n\n/**\n * Returns the user's current locale.\n *\n * @returns {string} BCP 47 locale tag, e.g., 'en-US'.\n *\n * @example\n * const locale = useLocale();\n * console.log(locale); // 'en-US'\n */\nexport const useLocale: typeof _useLocale = () => {\n throw new Error(typesFileError);\n};\n\n/**\n * Returns the user's list of supported locales.\n *\n * @returns {string[]} List of BCP 47 locale tags, e.g., ['en-US', 'fr', 'jp'].\n *\n * @example\n * const locales = useLocales();\n * console.log(locale); // ['en-US', 'fr', 'jp]\n */\nexport const useLocales: typeof _useLocales = () => {\n throw new Error(typesFileError);\n};\n\n/**\n * Returns the application's default locale.\n *\n * If no default locale is provided, it defaults to 'en'.\n *\n * @returns {string} A BCP 47 locale tag, e.g., 'en-US'.\n *\n * @example\n * const locale = useDefaultLocale();\n * console.log(locale); // 'en-US'\n */\nexport const useDefaultLocale: typeof _useDefaultLocale = () => {\n throw new Error(typesFileError);\n};\n\n/**\n * Returns the configured GT class instance.\n *\n * @returns {GT} The configured GT class instance.\n *\n * @example\n * const gt = useGTClass();\n * console.log(gt.getLocaleProperties('en-US'));\n */\nexport const useGTClass: typeof _useGTClass = () => {\n throw new Error(typesFileError);\n};\n\n/**\n * Returns the locale properties for the given locale.\n *\n * @param {string} locale - The locale to get the properties for.\n * @returns {LocaleProperties} The locale properties for the given locale.\n *\n * @example\n * const localeProperties = useLocaleProperties('en-US');\n * console.log(localeProperties);\n */\nexport const useLocaleProperties: typeof _useLocaleProperties = () => {\n throw new Error(typesFileError);\n};\n\n/**\n * Retrieves the text direction ('ltr' or 'rtl') for the current or specified locale from the `<GTProvider>` context.\n *\n * If no locale is provided, the direction for the current user's locale is returned.\n *\n * @param {string} [locale] - Optional locale code (e.g., 'ar', 'en-US'). If omitted, uses the current locale from context.\n * @returns {'ltr' | 'rtl'} The text direction for the locale: 'rtl' for right-to-left languages, otherwise 'ltr'.\n *\n * @example\n * const dir = useLocaleDirection(); // e.g., 'ltr'\n * const arabicDir = useLocaleDirection('ar'); // 'rtl'\n */\nexport const useLocaleDirection: typeof _useLocaleDirection = () => {\n throw new Error(typesFileError);\n};\n\n/**\n * Returns the version ID for the current source, if set.\n *\n * @returns {string | undefined} The version ID.\n *\n * @example\n * const versionId = useVersionId();\n * console.log(versionId); // 'abc123'\n */\nexport const useVersionId: typeof _useVersionId = () => {\n throw new Error(typesFileError);\n};\n\n/**\n * A dropdown component that allows users to select a region.\n *\n * @param {string[]} [regions] - An optional array of ISO 3166 region codes to display. If not provided, regions are inferred from supported locales in the `<GTProvider>` context.\n * @param {React.ReactNode} [placeholder] - Optional placeholder node to display as the first option when no region is selected.\n * @param {object} [customMapping] - An optional object to map region codes to custom display names, emojis, or associated locales. The value can be a string (display name) or an object with `name`, `emoji`, and/or `locale` properties.\n * @param {boolean} [prioritizeCurrentLocaleRegion] - If true, the region corresponding to the current locale is prioritized in the list.\n * @param {boolean} [sortRegionsAlphabetically] - If true, regions are sorted alphabetically by display name.\n * @param {boolean} [asLocaleSelector=false] - If true, selecting a region will also update the locale to the region's associated locale.\n * @param {object} [props] - Additional props to pass to the underlying `<select>` element.\n * @returns {React.JSX.Element | null} The rendered region dropdown component or null if no regions are available.\n *\n * @example\n * ```tsx\n * <RegionSelector\n * regions={['US', 'CA']}\n * customMapping={{ US: { name: \"United States\", emoji: \"🇺🇸\" } }}\n * placeholder=\"Select a region\"\n * />\n * ```\n */\nexport const RegionSelector: typeof _RegionSelector = () => {\n throw new Error(typesFileError);\n};\n\n/**\n * Registers a message to be translated. Returns the message unchanged if no options are provided.\n * @param {string | string[]} message The message to encode.\n * @param {InlineTranslationOptions} [options] The options to encode.\n * @returns The message or array of messages.\n *\n * @note - This function registers the message before the build process. The actual translation does not\n * occur until the m() function is invoked.\n *\n * @note - Message format\n * A message is broken into two parts separated by colons:\n * - interpolated content - the content with interpolated variables\n * - hash + options - a unique identifier for the source content and options for the translation\n *\n * @example - Basic usage\n *\n * const message1 = msg('Hello, World!');\n * console.log(message1); // \"Hello, World!\"\n *\n * const message2 = msg('Hello, {name}!', { name: 'Brian' });\n * console.log(message2); // \"Hello, Brian:eyIkX2hhc2giOiAiMHgxMjMiLCAiJF9zb3VyY2UiOiAiSGVsbG8sIHtuYW1lfSEiLCAibmFtZSI6ICJCcmlhbiJ9\"\n *\n * @example - Array usage\n *\n * const messages = msg(['Hello, Alice!', 'Hello, Bob!']);\n * console.log(messages); // [\"Hello, Alice!\", \"Hello, Bob!\"]\n *\n * @example - When specifying an id for an array, each message will have a unique id of `${id}.${index}`\n * const messages = msg(['Hello, Alice!', 'Hello, Bob!'], { $id: 'greetings' });\n * // \"Hello, Alice!\" id: \"greetings.0\"\n * // \"Hello, Bob!\" id: \"greetings.1\"\n */\nexport const useMessages: (\n _messages?: _Messages\n) => <T extends string | null | undefined>(\n encodedMsg: T,\n options?: InlineTranslationOptions\n) => T extends string ? string : T = () => {\n throw new Error(typesFileError);\n};\n\nexport type {\n DictionaryTranslationOptions,\n InlineTranslationOptions,\n RuntimeTranslationOptions,\n};\n\nexport type { StringFormat };\n\nexport {\n msg,\n decodeMsg,\n decodeOptions,\n mFallback,\n gtFallback,\n derive,\n declareVar,\n decodeVars,\n};\n\n/** @deprecated Use derive() instead. */\nexport { declareStatic };\n"],"mappings":";;;;;;;;;;;;;;AAoDA,MAAa,mBAAuC;AAClD,OAAM,IAAI,MAAMA,4BAAAA,eAAe;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgCjC,MAAa,UAAqB;AAChC,OAAM,IAAI,MAAMA,4BAAAA,eAAe;;;AAGjC,EAAE,OAAO;;;;;;;;;;;;;;;;;;AAmBT,MAAa,iBAAmC;AAC9C,OAAM,IAAI,MAAMA,4BAAAA,eAAe;;;AAGjC,SAAS,OAAO;;;;;;;;;;;;;;;;AAiBhB,MA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eAAe;;;;;;;;;;;;;AAcjC,MAAa,yBAAmD;AAC9D,OAAM,IAAI,MAAMA,4BAAAA,eAAe;;;;;;;;;;;AAYjC,MAAa,mBAAuC;AAClD,OAAM,IAAI,MAAMA,4BAAAA,eAAe;;;;;;;;;;;;AAajC,MAAa,4BAAyD;AACpE,OAAM,IAAI,MAAMA,4BAAAA,eAAe;;;;;;;;;;;;;;AAejC,MAAa,2BAAuD;AAClE,OAAM,IAAI,MAAMA,4BAAAA,eAAe;;;;;;;;;;;AAYjC,MAAa,qBAA2C;AACtD,OAAM,IAAI,MAAMA,4BAAAA,eAAe;;;;;;;;;;;;;;;;;;;;;;;AAwBjC,MAAa,uBAA+C;AAC1D,OAAM,IAAI,MAAMA,4BAAAA,eAAe;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmCjC,MAAa,oBAK8B;AACzC,OAAM,IAAI,MAAMA,4BAAAA,eAAe"}
|
|
1
|
+
{"version":3,"file":"index.types.js","names":["typesFileError"],"sources":["../src/index.types.ts"],"sourcesContent":["import { typesFileError } from './errors/createErrors';\nimport { GTProvider as _GTProvider } from './provider/GTProvider';\nimport { T as _T } from './server-dir/buildtime/T';\nimport {\n useTranslations as _useTranslations,\n useLocale as _useLocale,\n useLocales as _useLocales,\n useDefaultLocale as _useDefaultLocale,\n useGTClass as _useGTClass,\n useLocaleProperties as _useLocaleProperties,\n Currency as _Currency,\n DateTime as _DateTime,\n RelativeTime as _RelativeTime,\n Num as _Num,\n Var as _Var,\n Branch as _Branch,\n Plural as _Plural,\n LocaleSelector as _LocaleSelector,\n RegionSelector as _RegionSelector,\n useLocaleDirection as _useLocaleDirection,\n useVersionId as _useVersionId,\n} from 'gt-react/client';\nimport type {\n DictionaryTranslationOptions,\n InlineTranslationOptions,\n RuntimeTranslationOptions,\n} from 'gt-react';\nimport type { StringFormat } from '@generaltranslation/format/types';\nimport {\n msg,\n decodeMsg,\n decodeOptions,\n declareStatic,\n derive,\n declareVar,\n decodeVars,\n _Messages,\n Static as _Static,\n Derive as _Derive,\n mFallback,\n gtFallback,\n} from 'gt-react/internal';\n\n/**\n * Provides General Translation context to its children, which can then access `useGT`, `useLocale`, and `useDefaultLocale`.\n *\n * @param {React.ReactNode} children - The children components that will use the translation context.\n * @param {string} id - ID of a nested dictionary, so that only a subset of a large dictionary needs to be sent to the client.\n * @param {string} locale - The locale to use for the translation context.\n *\n * @returns {JSX.Element} The provider component for General Translation context.\n */\nexport const GTProvider: typeof _GTProvider = () => {\n throw new Error(typesFileError);\n};\n\n/**\n * Build-time translation component that renders its children in the user's given locale.\n *\n * @example\n * ```jsx\n * // Basic usage:\n * <T id=\"welcome_message\">\n * Hello, <Var>{name}</Var>!\n * </T>\n * ```\n *\n * @example\n * ```jsx\n * // Translating a plural\n * <T id=\"item_count\">\n * <Plural n={3} singular={<>You have <Num children={n}/> item.</>}>\n * You have <Num children={n}/> items.\n * </Plural>\n * </T>\n * ```\n *\n * @param {React.ReactNode} children - The content to be translated or displayed.\n * @param {string} [id] - Optional identifier for the translation string. If not provided, a hash will be generated from the content.\n * @param {any} [context] - Additional context for translation key generation.\n *\n * @returns {JSX.Element} The rendered translation or fallback content based on the provided configuration.\n *\n * @throws {Error} If a plural translation is requested but the `n` option is not provided.\n */\nexport const T: typeof _T = () => {\n throw new Error(typesFileError);\n};\n/** @internal _gtt - The GT transformation for the component. */\nT._gtt = 'translate';\n\n/**\n * The `<Currency>` component renders a formatted currency string, allowing customization of name, default value, currency type, and formatting options.\n *\n * @example\n * ```jsx\n * <Currency\n * currency=\"USD\"\n * >\n * 1000\n * </Currency>\n * ```\n *\n * @param {any} [children] - Optional content to render inside the currency component.\n * @param {string} [currency] - The currency type (e.g., USD, EUR, etc.).\n * @param {Intl.NumberFormatOptions} [options] - Optional formatting options to customize how the currency is displayed.\n * @returns {React.JSX.Element} The formatted currency component.\n */\nexport const Currency: typeof _Currency = () => {\n throw new Error(typesFileError);\n};\n/** @internal _gtt - The GT transformation for the component. */\nCurrency._gtt = 'variable-currency';\n\n/**\n * The `<DateTime>` component renders a formatted date or time string, allowing customization of the name, default value, and formatting options.\n * It utilizes the current locale and optional format settings to display the date.\n *\n * @example\n * ```jsx\n * <DateTime>\n * {new Date()}\n * </DateTime>\n * ```\n *\n * @param {any} [children] - Optional content (typically a date) to render inside the component.\n * @param {Intl.DateTimeFormatOptions} [options={}] - Optional formatting options for the date, following `Intl.DateTimeFormatOptions` specifications.\n * @returns {Promise<React.JSX.Element>} The formatted date or time component.\n */\nexport const DateTime: typeof _DateTime = () => {\n throw new Error(typesFileError);\n};\n/** @internal _gtt - The GT transformation for the component. */\nDateTime._gtt = 'variable-datetime';\n\n/**\n * The `<RelativeTime>` component renders a localized relative time string\n * (e.g., \"2 hours ago\", \"in 3 days\") using `Intl.RelativeTimeFormat`.\n *\n * @example\n * ```jsx\n * <RelativeTime date={someDate} />\n * ```\n *\n * @param {Date} [date] - A date to compute relative time from now.\n * @param {number} [value] - Explicit numeric value. Requires `unit`.\n * @param {Intl.RelativeTimeFormatUnit} [unit] - The unit of time.\n * @param {Date} [baseDate] - Base date for computing relative time. Defaults to `new Date()` at render time. Required for hydration safety.\n * @param {Intl.RelativeTimeFormatOptions} [options={}] - Formatting options.\n * @returns {Promise<React.JSX.Element>} The formatted relative time component.\n */\nexport const RelativeTime: typeof _RelativeTime = () => {\n throw new Error(typesFileError);\n};\n/** @internal _gtt - The GT transformation for the component. */\nRelativeTime._gtt = 'variable-relative-time';\n\n/**\n * The `<Num>` component renders a formatted number string, allowing customization of the name, default value, and formatting options.\n * It formats the number according to the current locale and optionally passed formatting options.\n *\n * @example\n * ```jsx\n * <Num\n * options={{ style: \"decimal\", maximumFractionDigits: 2 }}\n * >\n * 1000\n * </Num>\n * ```\n *\n * @param {any} [children] - Optional content (typically a number) to render inside the component.\n * @param {Intl.NumberFormatOptions} [options={}] - Optional formatting options for the number, following `Intl.NumberFormatOptions` specifications.\n * @returns {React.JSX.Element} The formatted number component.\n */\nexport const Num: typeof _Num = () => {\n throw new Error(typesFileError);\n};\n/** @internal _gtt - The GT transformation for the component. */\nNum._gtt = 'variable-number';\n\n/**\n * The `<Var>` component renders a variable value, which can either be passed as `children` or a `value`.\n * If `children` is provided, it will be used; otherwise, the `value` is rendered.\n *\n * @example\n * ```jsx\n * <Var>\n * John\n * </Var>\n * ```\n *\n * @param {any} [children] - The content to render inside the component. If provided, it will take precedence over `value`.\n * @returns {React.JSX.Element} The rendered variable component with either `children` or `value`.\n */\nexport const Var: typeof _Var = () => {\n throw new Error(typesFileError);\n};\n/** @internal _gtt - The GT transformation for the component. */\nVar._gtt = 'variable-variable';\n\n/**\n * Marks JSX children as derivable by the GT compiler and CLI.\n *\n * Use `<Derive>` inside translated JSX when child content is computed from\n * source code, but should still be discovered during extraction instead of\n * treated as a runtime interpolation variable. The CLI attempts to resolve the\n * derivable children into every possible static value and includes those values\n * in the source content that gets translated.\n *\n * `<Derive>` renders its children unchanged at runtime.\n *\n * Run `gt validate` after adding or changing `<Derive>` usage to verify that\n * each derivable expression can be resolved by the CLI before translating or\n * building.\n *\n * @example\n * ```jsx\n * function getSubject() {\n * return (Math.random() > 0.5) ? \"Alice\" : \"Brian\";\n * }\n * ...\n * <T>\n * <Derive>\n * {getSubject()}\n * </Derive>\n * is going to school today.\n * </T>\n * ```\n *\n * @param {T extends React.ReactNode} children - JSX content to derive for translation extraction.\n * @returns {T} The same children, unchanged at runtime.\n */\nexport const Derive: typeof _Derive = () => {\n throw new Error(typesFileError);\n};\n/** @internal _gtt - The GT transformation for the component. */\nDerive._gtt = 'derive';\n\n/**\n * @deprecated Use `<Derive>` instead.\n *\n * Marks JSX children as derivable by the GT compiler and CLI.\n *\n * Use `<Derive>` instead of `<Static>` for new code. This alias is kept for\n * backwards compatibility and renders its children unchanged at runtime.\n *\n * Run `gt validate` after adding or changing derived JSX content to verify that\n * each derivable expression can be resolved by the CLI before translating or\n * building.\n *\n * @example\n * ```jsx\n * function getSubject() {\n * return (Math.random() > 0.5) ? \"Alice\" : \"Brian\";\n * }\n * ...\n * <T>\n * <Static>\n * {getSubject()}\n * </Static>\n * is going to school today.\n * </T>\n * ```\n *\n * @param {T extends React.ReactNode} children - JSX content to derive for translation extraction.\n * @returns {T} The same children, unchanged at runtime.\n */\nexport const Static: typeof _Static = () => {\n throw new Error(typesFileError);\n};\n/** @internal _gtt - The GT transformation for the component. */\nStatic._gtt = 'derive';\n\n/**\n * The `<Branch>` component dynamically renders a specified branch of content or a fallback child component.\n * It allows for flexible content switching based on the `branch` prop and an object of possible branches (`...branches`).\n * If the specified `branch` is present in the `branches` object, it renders the content of that branch.\n * If the `branch` is not found, it renders the provided `children` as fallback content.\n *\n * @example\n * ```jsx\n * <Branch\n * branch=\"summary\"\n * summary={<p>This is a summary</p>}\n * details={<p>Details here</p>}\n * >\n * <p>Fallback content</p>\n * </Branch>\n * ```\n * If the `branch` prop is set to `\"summary\"`, it will render `<p>This is a summary</p>`. If the `branch` is not set or does not match any keys in the branches object, it renders the fallback content `<p>Fallback content</p>`.\n *\n * @param {any} [children] - Fallback content to render if no matching branch is found.\n * @param {string} [name=\"branch\"] - Optional name for the component, used for metadata or tracking purposes.\n * @param {string} [branch] - The name of the branch to render. The component looks for this key in the `...branches` object.\n * @param {...{[key: string]: any}} [branches] - A spread object containing possible branches as keys and their corresponding content as values.\n * @returns {React.JSX.Element} The rendered branch or fallback content.\n */\nexport const Branch: typeof _Branch = () => {\n throw new Error(typesFileError);\n};\n/** @internal _gtt - The GT transformation for the component. */\nBranch._gtt = 'branch';\n\n/**\n * The `<Plural>` component dynamically renders content based on the plural form of the given number (`n`).\n * It determines which content to display by matching the value of `n` to the appropriate pluralization branch,\n * based on the current locale or a default locale. If no matching plural branch is found, the component renders\n * the fallback `children` content.\n *\n * @example\n * ```jsx\n * <Plural\n * n={1}\n * one=\"There is 1 item\"\n * other=\"There are {n} items\"\n * />\n * ```\n * In this example, if `n` is 1, it renders `\"There is 1 item\"`. If `n` is a different number, it renders\n * `\"There are {n} items\"`.\n *\n * @param {any} [children] - Fallback content to render if no matching plural branch is found.\n * @param {number} [n] - The number used to determine the plural form. This is required for pluralization to work.\n * @param {string} [locale] - Optional parameter, the locale to use for pluralization format.\n * @param {...{[key: string]: any}} [branches] - A spread object containing possible plural branches, typically including `one` for singular\n * and `other` for plural forms, but it may vary depending on the locale.\n * @returns {React.JSX.Element} The rendered content corresponding to the plural form of `n`, or the fallback content.\n * @throws {Error} If `n` is not provided or not a valid number.\n */\nexport const Plural: typeof _Plural = () => {\n throw new Error(typesFileError);\n};\n/** @internal _gtt - The GT transformation for the component. */\nPlural._gtt = 'plural';\n\n/**\n * A dropdown component that allows users to select a locale.\n * @param {string[]} locales - An optional list of locales to use for the dropdown. If not provided, the list of locales from the `<GTProvider>` context is used.\n * @param {object} customNames - An optional object to map locales to custom names.\n * @returns {React.ReactElement | null} The rendered locale dropdown component or null to prevent rendering.\n */\nexport const LocaleSelector: typeof _LocaleSelector = () => {\n throw new Error(typesFileError);\n};\n\n/**\n * Returns the string translation function `t`.\n *\n * @returns {Function} A translation function that accepts an ICU format string and returns that ICU format string translated.\n * @param {InlineTranslationOptions} [options] - Translation options including variables and special `$`-prefixed options.\n * @param {string} [options.$context] - Additional context for the translation.\n * @param {string} [options.$id] - Optional identifier for the translation string.\n * @param {number} [options.$maxChars] - Maximum number of characters for the translated message.\n * @param {boolean} [options.$requiresReview] - Whether the translated message requires approval before use. Must be a boolean literal.\n * @param {StringFormat} [options.$format] - The data format for the message (e.g., 'ICU', 'STRING'). Defaults to 'ICU'.\n *\n * @example\n * const t = useGT();\n * console.log(t('To be or not to be...'));\n *\n * const t = useGT();\n * return (<>\n * {\n * t('My name is {customName}', { customName: \"Brian\" } )\n * }\n * </>);\n *\n */\nexport const useGT: (\n _messages?: _Messages\n) => (message: string, options?: InlineTranslationOptions) => string = () => {\n throw new Error(typesFileError);\n};\n\n/**\n * Returns the dictionary access function `t`.\n *\n * @param {string} [id] - Optional prefix to prepend to the translation keys.\n * @returns {Function} A translation function that accepts a key string and returns the translated value.\n * The returned function accepts `DictionaryTranslationOptions` which includes:\n * - `$format` - The data format for the message (e.g., 'ICU', 'STRING'). Defaults to 'ICU'.\n * - `$maxChars` - Maximum number of characters for the translated message.\n *\n * @example\n * const t = useTranslations('user');\n * console.log(t('name')); // Translates item 'user.name'\n *\n * const t = useTranslations();\n * console.log(t('hello')); // Translates item 'hello'\n */\nexport const useTranslations: typeof _useTranslations = () => {\n throw new Error(typesFileError);\n};\n\n/**\n * Returns the user's current locale.\n *\n * @returns {string} BCP 47 locale tag, e.g., 'en-US'.\n *\n * @example\n * const locale = useLocale();\n * console.log(locale); // 'en-US'\n */\nexport const useLocale: typeof _useLocale = () => {\n throw new Error(typesFileError);\n};\n\n/**\n * Returns the user's list of supported locales.\n *\n * @returns {string[]} List of BCP 47 locale tags, e.g., ['en-US', 'fr', 'jp'].\n *\n * @example\n * const locales = useLocales();\n * console.log(locale); // ['en-US', 'fr', 'jp]\n */\nexport const useLocales: typeof _useLocales = () => {\n throw new Error(typesFileError);\n};\n\n/**\n * Returns the application's default locale.\n *\n * If no default locale is provided, it defaults to 'en'.\n *\n * @returns {string} A BCP 47 locale tag, e.g., 'en-US'.\n *\n * @example\n * const locale = useDefaultLocale();\n * console.log(locale); // 'en-US'\n */\nexport const useDefaultLocale: typeof _useDefaultLocale = () => {\n throw new Error(typesFileError);\n};\n\n/**\n * Returns the configured GT class instance.\n *\n * @returns {GT} The configured GT class instance.\n *\n * @example\n * const gt = useGTClass();\n * console.log(gt.getLocaleProperties('en-US'));\n */\nexport const useGTClass: typeof _useGTClass = () => {\n throw new Error(typesFileError);\n};\n\n/**\n * Returns the locale properties for the given locale.\n *\n * @param {string} locale - The locale to get the properties for.\n * @returns {LocaleProperties} The locale properties for the given locale.\n *\n * @example\n * const localeProperties = useLocaleProperties('en-US');\n * console.log(localeProperties);\n */\nexport const useLocaleProperties: typeof _useLocaleProperties = () => {\n throw new Error(typesFileError);\n};\n\n/**\n * Retrieves the text direction ('ltr' or 'rtl') for the current or specified locale from the `<GTProvider>` context.\n *\n * If no locale is provided, the direction for the current user's locale is returned.\n *\n * @param {string} [locale] - Optional locale code (e.g., 'ar', 'en-US'). If omitted, uses the current locale from context.\n * @returns {'ltr' | 'rtl'} The text direction for the locale: 'rtl' for right-to-left languages, otherwise 'ltr'.\n *\n * @example\n * const dir = useLocaleDirection(); // e.g., 'ltr'\n * const arabicDir = useLocaleDirection('ar'); // 'rtl'\n */\nexport const useLocaleDirection: typeof _useLocaleDirection = () => {\n throw new Error(typesFileError);\n};\n\n/**\n * Returns the version ID for the current source, if set.\n *\n * @returns {string | undefined} The version ID.\n *\n * @example\n * const versionId = useVersionId();\n * console.log(versionId); // 'abc123'\n */\nexport const useVersionId: typeof _useVersionId = () => {\n throw new Error(typesFileError);\n};\n\n/**\n * A dropdown component that allows users to select a region.\n *\n * @param {string[]} [regions] - An optional array of ISO 3166 region codes to display. If not provided, regions are inferred from supported locales in the `<GTProvider>` context.\n * @param {React.ReactNode} [placeholder] - Optional placeholder node to display as the first option when no region is selected.\n * @param {object} [customMapping] - An optional object to map region codes to custom display names, emojis, or associated locales. The value can be a string (display name) or an object with `name`, `emoji`, and/or `locale` properties.\n * @param {boolean} [prioritizeCurrentLocaleRegion] - If true, the region corresponding to the current locale is prioritized in the list.\n * @param {boolean} [sortRegionsAlphabetically] - If true, regions are sorted alphabetically by display name.\n * @param {boolean} [asLocaleSelector=false] - If true, selecting a region will also update the locale to the region's associated locale.\n * @param {object} [props] - Additional props to pass to the underlying `<select>` element.\n * @returns {React.JSX.Element | null} The rendered region dropdown component or null if no regions are available.\n *\n * @example\n * ```tsx\n * <RegionSelector\n * regions={['US', 'CA']}\n * customMapping={{ US: { name: \"United States\", emoji: \"🇺🇸\" } }}\n * placeholder=\"Select a region\"\n * />\n * ```\n */\nexport const RegionSelector: typeof _RegionSelector = () => {\n throw new Error(typesFileError);\n};\n\n/**\n * Registers a message to be translated. Returns the message unchanged if no options are provided.\n * @param {string | string[]} message The message to encode.\n * @param {InlineTranslationOptions} [options] The options to encode.\n * @returns The message or array of messages.\n *\n * @note - This function registers the message before the build process. The actual translation does not\n * occur until the m() function is invoked.\n *\n * @note - Message format\n * A message is broken into two parts separated by colons:\n * - interpolated content - the content with interpolated variables\n * - hash + options - a unique identifier for the source content and options for the translation\n *\n * @example - Basic usage\n *\n * const message1 = msg('Hello, World!');\n * console.log(message1); // \"Hello, World!\"\n *\n * const message2 = msg('Hello, {name}!', { name: 'Brian' });\n * console.log(message2); // \"Hello, Brian:eyIkX2hhc2giOiAiMHgxMjMiLCAiJF9zb3VyY2UiOiAiSGVsbG8sIHtuYW1lfSEiLCAibmFtZSI6ICJCcmlhbiJ9\"\n *\n * @example - Array usage\n *\n * const messages = msg(['Hello, Alice!', 'Hello, Bob!']);\n * console.log(messages); // [\"Hello, Alice!\", \"Hello, Bob!\"]\n *\n * @example - When specifying an id for an array, each message will have a unique id of `${id}.${index}`\n * const messages = msg(['Hello, Alice!', 'Hello, Bob!'], { $id: 'greetings' });\n * // \"Hello, Alice!\" id: \"greetings.0\"\n * // \"Hello, Bob!\" id: \"greetings.1\"\n */\nexport const useMessages: (\n _messages?: _Messages\n) => <T extends string | null | undefined>(\n encodedMsg: T,\n options?: InlineTranslationOptions\n) => T extends string ? string : T = () => {\n throw new Error(typesFileError);\n};\n\nexport type {\n DictionaryTranslationOptions,\n InlineTranslationOptions,\n RuntimeTranslationOptions,\n};\n\nexport type { StringFormat };\n\nexport {\n msg,\n decodeMsg,\n decodeOptions,\n mFallback,\n gtFallback,\n derive,\n declareVar,\n decodeVars,\n};\n\n/** @deprecated Use derive() instead. */\nexport { declareStatic };\n"],"mappings":";;;;;;;;;;;;;;AAoDA,MAAa,mBAAuC;AAClD,OAAM,IAAI,MAAMA,4BAAAA,eAAe;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgCjC,MAAa,UAAqB;AAChC,OAAM,IAAI,MAAMA,4BAAAA,eAAe;;;AAGjC,EAAE,OAAO;;;;;;;;;;;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,MAAa,kBAAqC;AAChD,OAAM,IAAI,MAAMA,4BAAAA,eAAe;;;;;;;;;;;AAYjC,MAAa,mBAAuC;AAClD,OAAM,IAAI,MAAMA,4BAAAA,eAAe;;;;;;;;;;;;;AAcjC,MAAa,yBAAmD;AAC9D,OAAM,IAAI,MAAMA,4BAAAA,eAAe;;;;;;;;;;;AAYjC,MAAa,mBAAuC;AAClD,OAAM,IAAI,MAAMA,4BAAAA,eAAe;;;;;;;;;;;;AAajC,MAAa,4BAAyD;AACpE,OAAM,IAAI,MAAMA,4BAAAA,eAAe;;;;;;;;;;;;;;AAejC,MAAa,2BAAuD;AAClE,OAAM,IAAI,MAAMA,4BAAAA,eAAe;;;;;;;;;;;AAYjC,MAAa,qBAA2C;AACtD,OAAM,IAAI,MAAMA,4BAAAA,eAAe;;;;;;;;;;;;;;;;;;;;;;;AAwBjC,MAAa,uBAA+C;AAC1D,OAAM,IAAI,MAAMA,4BAAAA,eAAe;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmCjC,MAAa,oBAK8B;AACzC,OAAM,IAAI,MAAMA,4BAAAA,eAAe"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"getLocale.d.ts","sourceRoot":"","sources":["../../src/request/getLocale.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"getLocale.d.ts","sourceRoot":"","sources":["../../src/request/getLocale.ts"],"names":[],"mappings":"AASA;;;;;;;;GAQG;AACH,wBAAsB,SAAS,IAAI,OAAO,CAAC,MAAM,CAAC,CAuBjD;AAED,wBAAgB,SAAS,WAExB"}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
2
|
const require_config_dir_getI18NConfig = require("../config-dir/getI18NConfig.js");
|
|
3
3
|
const require_utils_use = require("../utils/use.js");
|
|
4
|
+
const require_request_localeValidation = require("./localeValidation.js");
|
|
4
5
|
const require_request_utils_legacyGetLocaleFunction = require("./utils/legacyGetLocaleFunction.js");
|
|
5
6
|
const require_request_utils_getRequestFunction = require("./utils/getRequestFunction.js");
|
|
6
7
|
const require_request_localeStore = require("./localeStore.js");
|
|
@@ -24,8 +25,7 @@ async function getLocale() {
|
|
|
24
25
|
if (process.env._GENERALTRANSLATION_ENABLE_SSG === "false") {
|
|
25
26
|
const requestFunction = require_request_utils_getRequestFunction.getRequestFunction("getLocale");
|
|
26
27
|
getLocaleFunction = async () => {
|
|
27
|
-
|
|
28
|
-
return gt.resolveAliasLocale(requestLocale || I18NConfig.getDefaultLocale());
|
|
28
|
+
return require_request_localeValidation.resolveLocaleOrDefault(await requestFunction(), I18NConfig, gt);
|
|
29
29
|
};
|
|
30
30
|
} else getLocaleFunction = require_request_utils_legacyGetLocaleFunction.legacyGetLocaleFunction(I18NConfig, gt);
|
|
31
31
|
return getLocaleFunction();
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"getLocale.js","names":["localeStore","getI18NConfig","getRequestFunction","legacyGetLocaleFunction","use"],"sources":["../../src/request/getLocale.ts"],"sourcesContent":["import { getI18NConfig } from '../config-dir/getI18NConfig';\nimport { use } from '../utils/use';\nimport { legacyGetLocaleFunction } from './utils/legacyGetLocaleFunction';\nimport { getRequestFunction } from './utils/getRequestFunction';\nimport { localeStore } from './localeStore';\n\nlet getLocaleFunction: () => Promise<string>;\n\n/**\n * Gets the user's current locale.\n *\n * @returns {Promise<string>} The user's locale, e.g., 'en-US'.\n *\n * @example\n * const locale = await getLocale();\n * console.log(locale); // 'en-US'\n */\nexport async function getLocale(): Promise<string> {\n // If a locale has been registered for this request, return it\n const registeredLocale = localeStore.getStore();\n if (registeredLocale) return registeredLocale;\n\n // Use the request function to get the locale\n if (getLocaleFunction) return await getLocaleFunction();\n const I18NConfig = getI18NConfig();\n const gt = I18NConfig.getGTClass();\n\n if (process.env._GENERALTRANSLATION_ENABLE_SSG === 'false') {\n const requestFunction = getRequestFunction('getLocale');\n // Support new behavior\n getLocaleFunction = async () => {\n const requestLocale = await requestFunction();\n return
|
|
1
|
+
{"version":3,"file":"getLocale.js","names":["localeStore","getI18NConfig","getRequestFunction","resolveLocaleOrDefault","legacyGetLocaleFunction","use"],"sources":["../../src/request/getLocale.ts"],"sourcesContent":["import { getI18NConfig } from '../config-dir/getI18NConfig';\nimport { use } from '../utils/use';\nimport { legacyGetLocaleFunction } from './utils/legacyGetLocaleFunction';\nimport { getRequestFunction } from './utils/getRequestFunction';\nimport { localeStore } from './localeStore';\nimport { resolveLocaleOrDefault } from './localeValidation';\n\nlet getLocaleFunction: () => Promise<string>;\n\n/**\n * Gets the user's current locale.\n *\n * @returns {Promise<string>} The user's locale, e.g., 'en-US'.\n *\n * @example\n * const locale = await getLocale();\n * console.log(locale); // 'en-US'\n */\nexport async function getLocale(): Promise<string> {\n // If a locale has been registered for this request, return it\n const registeredLocale = localeStore.getStore();\n if (registeredLocale) return registeredLocale;\n\n // Use the request function to get the locale\n if (getLocaleFunction) return await getLocaleFunction();\n const I18NConfig = getI18NConfig();\n const gt = I18NConfig.getGTClass();\n\n if (process.env._GENERALTRANSLATION_ENABLE_SSG === 'false') {\n const requestFunction = getRequestFunction('getLocale');\n // Support new behavior\n getLocaleFunction = async () => {\n const requestLocale = await requestFunction();\n return resolveLocaleOrDefault(requestLocale, I18NConfig, gt);\n };\n } else {\n // Support legacy behavior\n getLocaleFunction = legacyGetLocaleFunction(I18NConfig, gt);\n }\n\n return getLocaleFunction();\n}\n\nexport function useLocale() {\n return use(getLocale());\n}\n"],"mappings":";;;;;;;;AAOA,IAAI;;;;;;;;;;AAWJ,eAAsB,YAA6B;CAEjD,MAAM,mBAAmBA,4BAAAA,YAAY,UAAU;AAC/C,KAAI,iBAAkB,QAAO;AAG7B,KAAI,kBAAmB,QAAO,MAAM,mBAAmB;CACvD,MAAM,aAAaC,iCAAAA,eAAe;CAClC,MAAM,KAAK,WAAW,YAAY;AAElC,KAAI,QAAQ,IAAI,mCAAmC,SAAS;EAC1D,MAAM,kBAAkBC,yCAAAA,mBAAmB,YAAY;AAEvD,sBAAoB,YAAY;AAE9B,UAAOC,iCAAAA,uBAAuB,MADF,iBAAiB,EACA,YAAY,GAAG;;OAI9D,qBAAoBC,8CAAAA,wBAAwB,YAAY,GAAG;AAG7D,QAAO,mBAAmB;;AAG5B,SAAgB,YAAY;AAC1B,QAAOC,kBAAAA,IAAI,WAAW,CAAC"}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import type { GT } from 'generaltranslation';
|
|
2
|
+
import type { I18NConfiguration } from '../config-dir/I18NConfiguration';
|
|
3
|
+
export declare function resolveLocaleOrDefault(locale: unknown, I18NConfig: I18NConfiguration, gt: GT): string;
|
|
4
|
+
/**
|
|
5
|
+
* Checks whether a locale is valid and supported by the current gt-next config.
|
|
6
|
+
*
|
|
7
|
+
* Use this when route params or other request inputs should be rejected instead
|
|
8
|
+
* of falling back to the default locale.
|
|
9
|
+
*
|
|
10
|
+
* @param locale - The locale candidate to validate.
|
|
11
|
+
* @returns True when the locale resolves to one of the configured locales.
|
|
12
|
+
*/
|
|
13
|
+
export declare function isLocaleSupported(locale: unknown): locale is string;
|
|
14
|
+
//# sourceMappingURL=localeValidation.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"localeValidation.d.ts","sourceRoot":"","sources":["../../src/request/localeValidation.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,EAAE,EAAE,MAAM,oBAAoB,CAAC;AAE7C,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,iCAAiC,CAAC;AAsBzE,wBAAgB,sBAAsB,CACpC,MAAM,EAAE,OAAO,EACf,UAAU,EAAE,iBAAiB,EAC7B,EAAE,EAAE,EAAE,GACL,MAAM,CAWR;AAED;;;;;;;;GAQG;AACH,wBAAgB,iBAAiB,CAAC,MAAM,EAAE,OAAO,GAAG,MAAM,IAAI,MAAM,CAKnE"}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
+
const require_errors_createErrors = require("../errors/createErrors.js");
|
|
3
|
+
const require_config_dir_getI18NConfig = require("../config-dir/getI18NConfig.js");
|
|
4
|
+
//#region src/request/localeValidation.ts
|
|
5
|
+
function determineSupportedLocale(locale, I18NConfig, gt) {
|
|
6
|
+
if (typeof locale !== "string" || locale.length === 0) return void 0;
|
|
7
|
+
return gt.determineLocale([locale], I18NConfig.getLocales());
|
|
8
|
+
}
|
|
9
|
+
function warnInvalidLocale(locale, defaultLocale) {
|
|
10
|
+
if (process.env._GENERALTRANSLATION_DISABLE_INVALID_LOCALE_WARNING === "true") return;
|
|
11
|
+
console.warn(require_errors_createErrors.createInvalidRequestLocaleWarning(locale, defaultLocale));
|
|
12
|
+
}
|
|
13
|
+
function resolveLocaleOrDefault(locale, I18NConfig, gt) {
|
|
14
|
+
const defaultLocale = I18NConfig.getDefaultLocale();
|
|
15
|
+
const supportedLocale = determineSupportedLocale(locale, I18NConfig, gt);
|
|
16
|
+
if (supportedLocale) return gt.resolveAliasLocale(supportedLocale);
|
|
17
|
+
if (typeof locale === "string" && locale.length > 0) warnInvalidLocale(locale, defaultLocale);
|
|
18
|
+
return gt.resolveAliasLocale(defaultLocale);
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* Checks whether a locale is valid and supported by the current gt-next config.
|
|
22
|
+
*
|
|
23
|
+
* Use this when route params or other request inputs should be rejected instead
|
|
24
|
+
* of falling back to the default locale.
|
|
25
|
+
*
|
|
26
|
+
* @param locale - The locale candidate to validate.
|
|
27
|
+
* @returns True when the locale resolves to one of the configured locales.
|
|
28
|
+
*/
|
|
29
|
+
function isLocaleSupported(locale) {
|
|
30
|
+
const I18NConfig = require_config_dir_getI18NConfig.getI18NConfig();
|
|
31
|
+
return determineSupportedLocale(locale, I18NConfig, I18NConfig.getGTClass()) !== void 0;
|
|
32
|
+
}
|
|
33
|
+
//#endregion
|
|
34
|
+
exports.isLocaleSupported = isLocaleSupported;
|
|
35
|
+
exports.resolveLocaleOrDefault = resolveLocaleOrDefault;
|
|
36
|
+
|
|
37
|
+
//# sourceMappingURL=localeValidation.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"localeValidation.js","names":["createInvalidRequestLocaleWarning","getI18NConfig"],"sources":["../../src/request/localeValidation.ts"],"sourcesContent":["import type { GT } from 'generaltranslation';\nimport { getI18NConfig } from '../config-dir/getI18NConfig';\nimport type { I18NConfiguration } from '../config-dir/I18NConfiguration';\nimport { createInvalidRequestLocaleWarning } from '../errors/createErrors';\n\nfunction determineSupportedLocale(\n locale: unknown,\n I18NConfig: I18NConfiguration,\n gt: GT\n): string | undefined {\n if (typeof locale !== 'string' || locale.length === 0) return undefined;\n return gt.determineLocale([locale], I18NConfig.getLocales());\n}\n\nfunction warnInvalidLocale(locale: string, defaultLocale: string) {\n if (\n process.env._GENERALTRANSLATION_DISABLE_INVALID_LOCALE_WARNING === 'true'\n ) {\n return;\n }\n\n console.warn(createInvalidRequestLocaleWarning(locale, defaultLocale));\n}\n\nexport function resolveLocaleOrDefault(\n locale: unknown,\n I18NConfig: I18NConfiguration,\n gt: GT\n): string {\n const defaultLocale = I18NConfig.getDefaultLocale();\n const supportedLocale = determineSupportedLocale(locale, I18NConfig, gt);\n\n if (supportedLocale) return gt.resolveAliasLocale(supportedLocale);\n\n if (typeof locale === 'string' && locale.length > 0) {\n warnInvalidLocale(locale, defaultLocale);\n }\n\n return gt.resolveAliasLocale(defaultLocale);\n}\n\n/**\n * Checks whether a locale is valid and supported by the current gt-next config.\n *\n * Use this when route params or other request inputs should be rejected instead\n * of falling back to the default locale.\n *\n * @param locale - The locale candidate to validate.\n * @returns True when the locale resolves to one of the configured locales.\n */\nexport function isLocaleSupported(locale: unknown): locale is string {\n const I18NConfig = getI18NConfig();\n const gt = I18NConfig.getGTClass();\n\n return determineSupportedLocale(locale, I18NConfig, gt) !== undefined;\n}\n"],"mappings":";;;;AAKA,SAAS,yBACP,QACA,YACA,IACoB;AACpB,KAAI,OAAO,WAAW,YAAY,OAAO,WAAW,EAAG,QAAO,KAAA;AAC9D,QAAO,GAAG,gBAAgB,CAAC,OAAO,EAAE,WAAW,YAAY,CAAC;;AAG9D,SAAS,kBAAkB,QAAgB,eAAuB;AAChE,KACE,QAAQ,IAAI,uDAAuD,OAEnE;AAGF,SAAQ,KAAKA,4BAAAA,kCAAkC,QAAQ,cAAc,CAAC;;AAGxE,SAAgB,uBACd,QACA,YACA,IACQ;CACR,MAAM,gBAAgB,WAAW,kBAAkB;CACnD,MAAM,kBAAkB,yBAAyB,QAAQ,YAAY,GAAG;AAExE,KAAI,gBAAiB,QAAO,GAAG,mBAAmB,gBAAgB;AAElE,KAAI,OAAO,WAAW,YAAY,OAAO,SAAS,EAChD,mBAAkB,QAAQ,cAAc;AAG1C,QAAO,GAAG,mBAAmB,cAAc;;;;;;;;;;;AAY7C,SAAgB,kBAAkB,QAAmC;CACnE,MAAM,aAAaC,iCAAAA,eAAe;AAGlC,QAAO,yBAAyB,QAAQ,YAF7B,WAAW,YAEgC,CAAC,KAAK,KAAA"}
|
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
* Use this in Route Handlers and OG image handlers where next/root-params is unavailable.
|
|
4
4
|
* Must be called at the top of the request handler before any other gt-next functions.
|
|
5
5
|
*
|
|
6
|
-
* @param locale - A
|
|
6
|
+
* @param locale - A locale candidate to use for this request.
|
|
7
7
|
*/
|
|
8
8
|
export declare function registerLocale(locale: string): void;
|
|
9
9
|
//# sourceMappingURL=registerLocale.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"registerLocale.d.ts","sourceRoot":"","sources":["../../src/request/registerLocale.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"registerLocale.d.ts","sourceRoot":"","sources":["../../src/request/registerLocale.ts"],"names":[],"mappings":"AAIA;;;;;;GAMG;AACH,wBAAgB,cAAc,CAAC,MAAM,EAAE,MAAM,GAAG,IAAI,CAInD"}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
2
|
const require_config_dir_getI18NConfig = require("../config-dir/getI18NConfig.js");
|
|
3
|
+
const require_request_localeValidation = require("./localeValidation.js");
|
|
3
4
|
const require_request_localeStore = require("./localeStore.js");
|
|
4
5
|
//#region src/request/registerLocale.ts
|
|
5
6
|
/**
|
|
@@ -7,11 +8,12 @@ const require_request_localeStore = require("./localeStore.js");
|
|
|
7
8
|
* Use this in Route Handlers and OG image handlers where next/root-params is unavailable.
|
|
8
9
|
* Must be called at the top of the request handler before any other gt-next functions.
|
|
9
10
|
*
|
|
10
|
-
* @param locale - A
|
|
11
|
+
* @param locale - A locale candidate to use for this request.
|
|
11
12
|
*/
|
|
12
13
|
function registerLocale(locale) {
|
|
13
|
-
const
|
|
14
|
-
|
|
14
|
+
const I18NConfig = require_config_dir_getI18NConfig.getI18NConfig();
|
|
15
|
+
const gt = I18NConfig.getGTClass();
|
|
16
|
+
require_request_localeStore.localeStore.enterWith(require_request_localeValidation.resolveLocaleOrDefault(locale, I18NConfig, gt));
|
|
15
17
|
}
|
|
16
18
|
//#endregion
|
|
17
19
|
exports.registerLocale = registerLocale;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"registerLocale.js","names":["getI18NConfig"],"sources":["../../src/request/registerLocale.ts"],"sourcesContent":["import { getI18NConfig } from '../config-dir/getI18NConfig';\nimport { localeStore } from './localeStore';\n\n/**\n * Set the locale for the current request context.\n * Use this in Route Handlers and OG image handlers where next/root-params is unavailable.\n * Must be called at the top of the request handler before any other gt-next functions.\n *\n * @param locale - A
|
|
1
|
+
{"version":3,"file":"registerLocale.js","names":["getI18NConfig","resolveLocaleOrDefault"],"sources":["../../src/request/registerLocale.ts"],"sourcesContent":["import { getI18NConfig } from '../config-dir/getI18NConfig';\nimport { localeStore } from './localeStore';\nimport { resolveLocaleOrDefault } from './localeValidation';\n\n/**\n * Set the locale for the current request context.\n * Use this in Route Handlers and OG image handlers where next/root-params is unavailable.\n * Must be called at the top of the request handler before any other gt-next functions.\n *\n * @param locale - A locale candidate to use for this request.\n */\nexport function registerLocale(locale: string): void {\n const I18NConfig = getI18NConfig();\n const gt = I18NConfig.getGTClass();\n localeStore.enterWith(resolveLocaleOrDefault(locale, I18NConfig, gt));\n}\n"],"mappings":";;;;;;;;;;;;AAWA,SAAgB,eAAe,QAAsB;CACnD,MAAM,aAAaA,iCAAAA,eAAe;CAClC,MAAM,KAAK,WAAW,YAAY;AAClC,6BAAA,YAAY,UAAUC,iCAAAA,uBAAuB,QAAQ,YAAY,GAAG,CAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"legacyGetLocaleFunction.d.ts","sourceRoot":"","sources":["../../../src/request/utils/legacyGetLocaleFunction.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,EAAE,EAAE,MAAM,oBAAoB,CAAC;AAIxC,OAAO,EAAE,iBAAiB,EAAE,MAAM,oCAAoC,CAAC;
|
|
1
|
+
{"version":3,"file":"legacyGetLocaleFunction.d.ts","sourceRoot":"","sources":["../../../src/request/utils/legacyGetLocaleFunction.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,EAAE,EAAE,MAAM,oBAAoB,CAAC;AAIxC,OAAO,EAAE,iBAAiB,EAAE,MAAM,oCAAoC,CAAC;AAMvE;;GAEG;AACH,wBAAgB,uBAAuB,CACrC,UAAU,EAAE,iBAAiB,EAC7B,EAAE,EAAE,EAAE,GACL,MAAM,OAAO,CAAC,MAAM,CAAC,CAavB"}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
2
|
const require_request_utils_legacyGetRequestFunction = require("./legacyGetRequestFunction.js");
|
|
3
3
|
const require_request_utils_isSSR = require("./isSSR.js");
|
|
4
|
+
const require_request_localeValidation = require("../localeValidation.js");
|
|
4
5
|
//#region src/request/utils/legacyGetLocaleFunction.ts
|
|
5
6
|
let getLocaleFunction;
|
|
6
7
|
let getStaticLocaleFunction;
|
|
@@ -11,8 +12,7 @@ function legacyGetLocaleFunction(I18NConfig, gt) {
|
|
|
11
12
|
getLocaleFunction = require_request_utils_legacyGetRequestFunction.legacyGetRequestFunction("getLocale", true);
|
|
12
13
|
getStaticLocaleFunction = require_request_utils_legacyGetRequestFunction.legacyGetRequestFunction("getLocale", false);
|
|
13
14
|
return async () => {
|
|
14
|
-
|
|
15
|
-
return gt.resolveAliasLocale(locale || I18NConfig.getDefaultLocale());
|
|
15
|
+
return require_request_localeValidation.resolveLocaleOrDefault(require_request_utils_isSSR.isSSR() ? await getLocaleFunction() : await getStaticLocaleFunction(), I18NConfig, gt);
|
|
16
16
|
};
|
|
17
17
|
}
|
|
18
18
|
//#endregion
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"legacyGetLocaleFunction.js","names":["legacyGetRequestFunction","isSSR"],"sources":["../../../src/request/utils/legacyGetLocaleFunction.ts"],"sourcesContent":["import { GT } from 'generaltranslation';\nimport { RequestFunctionReturnType } from '../types';\nimport { legacyGetRequestFunction } from './legacyGetRequestFunction';\nimport { isSSR } from './isSSR';\nimport { I18NConfiguration } from '../../config-dir/I18NConfiguration';\n\nlet getLocaleFunction: () => Promise<RequestFunctionReturnType>;\nlet getStaticLocaleFunction: () => Promise<RequestFunctionReturnType>;\n\n/**\n * @deprecated\n */\nexport function legacyGetLocaleFunction(\n I18NConfig: I18NConfiguration,\n gt: GT\n): () => Promise<string> {\n // Construct getLocale function\n getLocaleFunction = legacyGetRequestFunction('getLocale', true);\n getStaticLocaleFunction = legacyGetRequestFunction('getLocale', false);\n\n // Construct locale function\n return async () => {\n // Always fallback to default locale\n const locale = isSSR()\n ? await getLocaleFunction()\n : await getStaticLocaleFunction();\n return
|
|
1
|
+
{"version":3,"file":"legacyGetLocaleFunction.js","names":["legacyGetRequestFunction","resolveLocaleOrDefault","isSSR"],"sources":["../../../src/request/utils/legacyGetLocaleFunction.ts"],"sourcesContent":["import { GT } from 'generaltranslation';\nimport { RequestFunctionReturnType } from '../types';\nimport { legacyGetRequestFunction } from './legacyGetRequestFunction';\nimport { isSSR } from './isSSR';\nimport { I18NConfiguration } from '../../config-dir/I18NConfiguration';\nimport { resolveLocaleOrDefault } from '../localeValidation';\n\nlet getLocaleFunction: () => Promise<RequestFunctionReturnType>;\nlet getStaticLocaleFunction: () => Promise<RequestFunctionReturnType>;\n\n/**\n * @deprecated\n */\nexport function legacyGetLocaleFunction(\n I18NConfig: I18NConfiguration,\n gt: GT\n): () => Promise<string> {\n // Construct getLocale function\n getLocaleFunction = legacyGetRequestFunction('getLocale', true);\n getStaticLocaleFunction = legacyGetRequestFunction('getLocale', false);\n\n // Construct locale function\n return async () => {\n // Always fallback to default locale\n const locale = isSSR()\n ? await getLocaleFunction()\n : await getStaticLocaleFunction();\n return resolveLocaleOrDefault(locale, I18NConfig, gt);\n };\n}\n"],"mappings":";;;;;AAOA,IAAI;AACJ,IAAI;;;;AAKJ,SAAgB,wBACd,YACA,IACuB;AAEvB,qBAAoBA,+CAAAA,yBAAyB,aAAa,KAAK;AAC/D,2BAA0BA,+CAAAA,yBAAyB,aAAa,MAAM;AAGtE,QAAO,YAAY;AAKjB,SAAOC,iCAAAA,uBAHQC,4BAAAA,OAAO,GAClB,MAAM,mBAAmB,GACzB,MAAM,yBAAyB,EACG,YAAY,GAAG"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"T.d.ts","sourceRoot":"","sources":["../../../src/server-dir/buildtime/T.tsx"],"names":[],"mappings":"AAEA,OAAO,EAAY,KAAK,SAAS,EAAE,MAAM,OAAO,CAAC;AAYjD,KAAK,MAAM,GAAG;IACZ,QAAQ,EAAE,SAAS,CAAC;IACpB,EAAE,CAAC,EAAE,MAAM,CAAC;IACZ,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,CAAC,GAAG,EAAE,MAAM,GAAG,SAAS,CAAC;CAC1B,CAAC;AAEF;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;AACH,wBAAsB,CAAC,CAAC,EACtB,QAAQ,EACR,EAAE,EACF,OAAO,EACP,KAAK,EACL,GAAG,OAAO,EACX,EAAE,MAAM,GAAG,OAAO,CAAC,SAAS,CAAC,
|
|
1
|
+
{"version":3,"file":"T.d.ts","sourceRoot":"","sources":["../../../src/server-dir/buildtime/T.tsx"],"names":[],"mappings":"AAEA,OAAO,EAAY,KAAK,SAAS,EAAE,MAAM,OAAO,CAAC;AAYjD,KAAK,MAAM,GAAG;IACZ,QAAQ,EAAE,SAAS,CAAC;IACpB,EAAE,CAAC,EAAE,MAAM,CAAC;IACZ,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,cAAc,CAAC,EAAE,OAAO,CAAC;IACzB,eAAe,CAAC,EAAE,OAAO,CAAC;IAC1B,CAAC,GAAG,EAAE,MAAM,GAAG,SAAS,CAAC;CAC1B,CAAC;AAEF;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;AACH,wBAAsB,CAAC,CAAC,EACtB,QAAQ,EACR,EAAE,EACF,OAAO,EACP,KAAK,EACL,GAAG,OAAO,EACX,EAAE,MAAM,GAAG,OAAO,CAAC,SAAS,CAAC,CAsK7B;yBA5KqB,CAAC"}
|
|
@@ -45,6 +45,7 @@ async function T({ children, id, context, _hash, ...options }) {
|
|
|
45
45
|
id = id ?? options?.$id;
|
|
46
46
|
context = context ?? options?.$context;
|
|
47
47
|
const maxChars = options?.$maxChars;
|
|
48
|
+
const requiresReview = typeof options?.$requiresReview === "boolean" ? options.$requiresReview : typeof options?.requiresReview === "boolean" ? options.requiresReview : void 0;
|
|
48
49
|
const taggedChildren = (0, gt_react_internal.addGTIdentifier)(children);
|
|
49
50
|
const renderDefault = () => {
|
|
50
51
|
return (0, gt_react_internal.renderDefaultChildren)({
|
|
@@ -65,6 +66,7 @@ async function T({ children, id, context, _hash, ...options }) {
|
|
|
65
66
|
source: childrenAsObjects,
|
|
66
67
|
...context && { context },
|
|
67
68
|
...maxChars != null && { maxChars: Math.abs(maxChars) },
|
|
69
|
+
...requiresReview === true && { requiresReview: true },
|
|
68
70
|
...id && { id },
|
|
69
71
|
dataFormat: "JSX"
|
|
70
72
|
});
|
|
@@ -91,6 +93,7 @@ async function T({ children, id, context, _hash, ...options }) {
|
|
|
91
93
|
source: childrenAsObjects,
|
|
92
94
|
...context && { context },
|
|
93
95
|
...maxChars != null && { maxChars: Math.abs(maxChars) },
|
|
96
|
+
...requiresReview === true && { requiresReview: true },
|
|
94
97
|
...id && { id },
|
|
95
98
|
dataFormat: "JSX"
|
|
96
99
|
});
|
|
@@ -102,7 +105,8 @@ async function T({ children, id, context, _hash, ...options }) {
|
|
|
102
105
|
$_hash: hash,
|
|
103
106
|
$format: "JSX",
|
|
104
107
|
...context && { $context: context },
|
|
105
|
-
...maxChars != null && { $maxChars: maxChars }
|
|
108
|
+
...maxChars != null && { $maxChars: maxChars },
|
|
109
|
+
...requiresReview === true && { $requiresReview: true }
|
|
106
110
|
}
|
|
107
111
|
}));
|
|
108
112
|
} catch {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"T.js","names":["getI18NConfig","getLocale","Suspense"],"sources":["../../../src/server-dir/buildtime/T.tsx"],"sourcesContent":["import { getI18NConfig } from '../../config-dir/getI18NConfig';\nimport { getLocale } from '../../request/getLocale';\nimport { Suspense, type ReactNode } from 'react';\nimport {\n addGTIdentifier,\n renderDefaultChildren,\n renderSkeleton,\n renderTranslatedChildren,\n TranslatedChildren,\n writeChildrenAsObjects,\n} from 'gt-react/internal';\nimport { renderVariable } from '../variables/renderVariable';\nimport { hashSource } from 'generaltranslation/id';\n\ntype TProps = {\n children: ReactNode;\n id?: string;\n context?: string;\n _hash?: string;\n $id?: string;\n $context?: string;\n $maxChars?: number;\n [key: string]: ReactNode;\n};\n\n/**\n * Build-time translation component that renders its children in the user's given locale.\n *\n * @example\n * ```jsx\n * // Basic usage:\n * <T id=\"welcome_message\">\n * Hello, <Var>{name}</Var>!\n * </T>\n * ```\n *\n * @example\n * ```jsx\n * // Translating a plural\n * <T id=\"item_count\">\n * <Plural n={3} singular={<>You have <Num children={n}/> item.</>}>\n * You have <Num children={n}/> items.\n * </Plural>\n * </T>\n * ```\n *\n * @param {React.ReactNode} children - The content to be translated or displayed.\n * @param {string} [id] - Optional identifier for the translation string. If not provided, a hash will be generated from the content.\n * @param {any} [context] - Additional context for translation key generation.\n *\n * @returns {JSX.Element} The rendered translation or fallback content based on the provided configuration.\n *\n * @throws {Error} If a plural translation is requested but the `n` option is not provided.\n */\nexport async function T({\n children,\n id,\n context,\n _hash,\n ...options\n}: TProps): Promise<ReactNode> {\n // ----- SET UP ----- //\n\n const I18NConfig = getI18NConfig();\n const locale = await getLocale();\n const defaultLocale = I18NConfig.getDefaultLocale();\n const [translationRequired, dialectTranslationRequired] =\n I18NConfig.requiresTranslation(locale);\n\n // Compatibility with different options\n id = id ?? options?.$id;\n context = context ?? options?.$context;\n const maxChars = options?.$maxChars;\n\n // ----- TAG CHILDREN ----- //\n\n const taggedChildren = addGTIdentifier(children);\n\n // ----- RENDERING FUNCTION #1: CONTENT IN DEFAULT LOCALE ----- //\n\n // render in default language\n const renderDefault = () => {\n return renderDefaultChildren({\n children: taggedChildren,\n defaultLocale,\n renderVariable,\n });\n };\n\n // ----- CHECK TRANSLATIONS REQUIRED ----- //\n\n // If no translation is required, render the default children\n // The dictionary wraps text in this <T> component\n // Thus, we need to also handle variables\n if (!translationRequired) {\n return renderDefault();\n }\n\n // ----- CHECK CACHED TRANSLATIONS ----- //\n\n // Begin by sending check to cache for translations\n const translationsPromise = I18NConfig.getCachedTranslations(locale);\n\n // Get the translation entry object\n const translations = await translationsPromise;\n\n let translationEntry = translations?.[id || ''];\n\n let hash;\n if (_hash && typeof translationEntry === 'undefined') {\n translationEntry = translations?.[_hash];\n }\n\n let childrenAsObjects;\n\n if (!translationEntry) {\n // Turns tagged children into objects\n // The hash is used to identify the translation\n childrenAsObjects = writeChildrenAsObjects(taggedChildren);\n hash = hashSource({\n source: childrenAsObjects,\n ...(context && { context }),\n ...(maxChars != null && { maxChars: Math.abs(maxChars) }),\n ...(id && { id }),\n dataFormat: 'JSX',\n });\n translationEntry = translations?.[hash];\n }\n\n // ----- RENDERING FUNCTION #2: RENDER TRANSLATED CONTENT ----- //\n\n const renderTranslation = (target: TranslatedChildren) => {\n return renderTranslatedChildren({\n source: taggedChildren,\n target,\n locales: [locale, defaultLocale],\n renderVariable,\n });\n };\n\n // ----- RENDER CACHED TRANSLATIONS ----- //\n\n // if we have a cached translation, render it\n if (translationEntry) {\n return (\n <Suspense fallback={renderTranslation(translationEntry)}>\n {renderTranslation(translationEntry)}\n </Suspense>\n );\n }\n\n if (\n // translationEntry === null || // If there was an error\n !I18NConfig.isDevelopmentApiEnabled() // Development translation disabled\n ) {\n return renderDefault();\n }\n\n // ----- TRANSLATE ON DEMAND ----- //\n // Since this is the buildtime translation component <T>, everything below is dev-only\n\n // Get render settings\n const renderSettings = I18NConfig.getRenderSettings();\n\n // Send on-demand translation request\n // (no entry has been found, this means that the translation is either (1) loading or (2) missing)\n const translationPromise = (async () => {\n try {\n childrenAsObjects ||= writeChildrenAsObjects(taggedChildren);\n hash ||=\n _hash ||\n hashSource({\n source: childrenAsObjects,\n ...(context && { context }),\n ...(maxChars != null && { maxChars: Math.abs(maxChars) }),\n ...(id && { id }),\n dataFormat: 'JSX',\n });\n const target = await I18NConfig.translate({\n // do on demand translation\n source: childrenAsObjects,\n targetLocale: locale,\n options: {\n ...(id && { $id: id }),\n $_hash: hash,\n $format: 'JSX',\n ...(context && { $context: context }),\n ...(maxChars != null && { $maxChars: maxChars }),\n },\n });\n return renderTranslation(target);\n } catch {\n return renderDefault();\n }\n })();\n\n // ----- DEFINE LOADING BEHAVIOR ----- //\n\n let loadingFallback;\n if (renderSettings.method === 'replace') {\n loadingFallback = renderDefault();\n } else if (renderSettings.method === 'skeleton') {\n loadingFallback = renderSkeleton();\n } else {\n loadingFallback = dialectTranslationRequired\n ? renderDefault()\n : renderSkeleton();\n }\n\n return (\n <Suspense key={locale} fallback={loadingFallback}>\n {translationPromise}\n </Suspense>\n );\n}\n/** @internal _gtt - The GT transformation for the component. */\nT._gtt = 'translate-server';\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
|
|
1
|
+
{"version":3,"file":"T.js","names":["getI18NConfig","getLocale","Suspense"],"sources":["../../../src/server-dir/buildtime/T.tsx"],"sourcesContent":["import { getI18NConfig } from '../../config-dir/getI18NConfig';\nimport { getLocale } from '../../request/getLocale';\nimport { Suspense, type ReactNode } from 'react';\nimport {\n addGTIdentifier,\n renderDefaultChildren,\n renderSkeleton,\n renderTranslatedChildren,\n TranslatedChildren,\n writeChildrenAsObjects,\n} from 'gt-react/internal';\nimport { renderVariable } from '../variables/renderVariable';\nimport { hashSource } from 'generaltranslation/id';\n\ntype TProps = {\n children: ReactNode;\n id?: string;\n context?: string;\n _hash?: string;\n $id?: string;\n $context?: string;\n $maxChars?: number;\n requiresReview?: boolean;\n $requiresReview?: boolean;\n [key: string]: ReactNode;\n};\n\n/**\n * Build-time translation component that renders its children in the user's given locale.\n *\n * @example\n * ```jsx\n * // Basic usage:\n * <T id=\"welcome_message\">\n * Hello, <Var>{name}</Var>!\n * </T>\n * ```\n *\n * @example\n * ```jsx\n * // Translating a plural\n * <T id=\"item_count\">\n * <Plural n={3} singular={<>You have <Num children={n}/> item.</>}>\n * You have <Num children={n}/> items.\n * </Plural>\n * </T>\n * ```\n *\n * @param {React.ReactNode} children - The content to be translated or displayed.\n * @param {string} [id] - Optional identifier for the translation string. If not provided, a hash will be generated from the content.\n * @param {any} [context] - Additional context for translation key generation.\n *\n * @returns {JSX.Element} The rendered translation or fallback content based on the provided configuration.\n *\n * @throws {Error} If a plural translation is requested but the `n` option is not provided.\n */\nexport async function T({\n children,\n id,\n context,\n _hash,\n ...options\n}: TProps): Promise<ReactNode> {\n // ----- SET UP ----- //\n\n const I18NConfig = getI18NConfig();\n const locale = await getLocale();\n const defaultLocale = I18NConfig.getDefaultLocale();\n const [translationRequired, dialectTranslationRequired] =\n I18NConfig.requiresTranslation(locale);\n\n // Compatibility with different options\n id = id ?? options?.$id;\n context = context ?? options?.$context;\n const maxChars = options?.$maxChars;\n const requiresReview =\n typeof options?.$requiresReview === 'boolean'\n ? options.$requiresReview\n : typeof options?.requiresReview === 'boolean'\n ? options.requiresReview\n : undefined;\n\n // ----- TAG CHILDREN ----- //\n\n const taggedChildren = addGTIdentifier(children);\n\n // ----- RENDERING FUNCTION #1: CONTENT IN DEFAULT LOCALE ----- //\n\n // render in default language\n const renderDefault = () => {\n return renderDefaultChildren({\n children: taggedChildren,\n defaultLocale,\n renderVariable,\n });\n };\n\n // ----- CHECK TRANSLATIONS REQUIRED ----- //\n\n // If no translation is required, render the default children\n // The dictionary wraps text in this <T> component\n // Thus, we need to also handle variables\n if (!translationRequired) {\n return renderDefault();\n }\n\n // ----- CHECK CACHED TRANSLATIONS ----- //\n\n // Begin by sending check to cache for translations\n const translationsPromise = I18NConfig.getCachedTranslations(locale);\n\n // Get the translation entry object\n const translations = await translationsPromise;\n\n let translationEntry = translations?.[id || ''];\n\n let hash;\n if (_hash && typeof translationEntry === 'undefined') {\n translationEntry = translations?.[_hash];\n }\n\n let childrenAsObjects;\n\n if (!translationEntry) {\n // Turns tagged children into objects\n // The hash is used to identify the translation\n childrenAsObjects = writeChildrenAsObjects(taggedChildren);\n hash = hashSource({\n source: childrenAsObjects,\n ...(context && { context }),\n ...(maxChars != null && { maxChars: Math.abs(maxChars) }),\n ...(requiresReview === true && { requiresReview: true }),\n ...(id && { id }),\n dataFormat: 'JSX',\n });\n translationEntry = translations?.[hash];\n }\n\n // ----- RENDERING FUNCTION #2: RENDER TRANSLATED CONTENT ----- //\n\n const renderTranslation = (target: TranslatedChildren) => {\n return renderTranslatedChildren({\n source: taggedChildren,\n target,\n locales: [locale, defaultLocale],\n renderVariable,\n });\n };\n\n // ----- RENDER CACHED TRANSLATIONS ----- //\n\n // if we have a cached translation, render it\n if (translationEntry) {\n return (\n <Suspense fallback={renderTranslation(translationEntry)}>\n {renderTranslation(translationEntry)}\n </Suspense>\n );\n }\n\n if (\n // translationEntry === null || // If there was an error\n !I18NConfig.isDevelopmentApiEnabled() // Development translation disabled\n ) {\n return renderDefault();\n }\n\n // ----- TRANSLATE ON DEMAND ----- //\n // Since this is the buildtime translation component <T>, everything below is dev-only\n\n // Get render settings\n const renderSettings = I18NConfig.getRenderSettings();\n\n // Send on-demand translation request\n // (no entry has been found, this means that the translation is either (1) loading or (2) missing)\n const translationPromise = (async () => {\n try {\n childrenAsObjects ||= writeChildrenAsObjects(taggedChildren);\n hash ||=\n _hash ||\n hashSource({\n source: childrenAsObjects,\n ...(context && { context }),\n ...(maxChars != null && { maxChars: Math.abs(maxChars) }),\n ...(requiresReview === true && { requiresReview: true }),\n ...(id && { id }),\n dataFormat: 'JSX',\n });\n // Dev-mode runtime translation is intentionally NOT review-gated (it's\n // a live preview; review gates production serving) — the flag rides\n // along so the platform records review intent on anything it persists\n const target = await I18NConfig.translate({\n // do on demand translation\n source: childrenAsObjects,\n targetLocale: locale,\n options: {\n ...(id && { $id: id }),\n $_hash: hash,\n $format: 'JSX',\n ...(context && { $context: context }),\n ...(maxChars != null && { $maxChars: maxChars }),\n ...(requiresReview === true && { $requiresReview: true }),\n },\n });\n return renderTranslation(target);\n } catch {\n return renderDefault();\n }\n })();\n\n // ----- DEFINE LOADING BEHAVIOR ----- //\n\n let loadingFallback;\n if (renderSettings.method === 'replace') {\n loadingFallback = renderDefault();\n } else if (renderSettings.method === 'skeleton') {\n loadingFallback = renderSkeleton();\n } else {\n loadingFallback = dialectTranslationRequired\n ? renderDefault()\n : renderSkeleton();\n }\n\n return (\n <Suspense key={locale} fallback={loadingFallback}>\n {translationPromise}\n </Suspense>\n );\n}\n/** @internal _gtt - The GT transformation for the component. */\nT._gtt = 'translate-server';\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwDA,eAAsB,EAAE,EACtB,UACA,IACA,SACA,OACA,GAAG,WAC0B;CAG7B,MAAM,aAAaA,iCAAAA,eAAe;CAClC,MAAM,SAAS,MAAMC,0BAAAA,WAAW;CAChC,MAAM,gBAAgB,WAAW,kBAAkB;CACnD,MAAM,CAAC,qBAAqB,8BAC1B,WAAW,oBAAoB,OAAO;AAGxC,MAAK,MAAM,SAAS;AACpB,WAAU,WAAW,SAAS;CAC9B,MAAM,WAAW,SAAS;CAC1B,MAAM,iBACJ,OAAO,SAAS,oBAAoB,YAChC,QAAQ,kBACR,OAAO,SAAS,mBAAmB,YACjC,QAAQ,iBACR,KAAA;CAIR,MAAM,kBAAA,GAAA,kBAAA,iBAAiC,SAAS;CAKhD,MAAM,sBAAsB;AAC1B,UAAA,GAAA,kBAAA,uBAA6B;GAC3B,UAAU;GACV;GACA,gBAAA,4CAAA;GACD,CAAC;;AAQJ,KAAI,CAAC,oBACH,QAAO,eAAe;CASxB,MAAM,eAAe,MAHO,WAAW,sBAAsB,OAGf;CAE9C,IAAI,mBAAmB,eAAe,MAAM;CAE5C,IAAI;AACJ,KAAI,SAAS,OAAO,qBAAqB,YACvC,oBAAmB,eAAe;CAGpC,IAAI;AAEJ,KAAI,CAAC,kBAAkB;AAGrB,uBAAA,GAAA,kBAAA,wBAA2C,eAAe;AAC1D,UAAA,GAAA,sBAAA,YAAkB;GAChB,QAAQ;G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AAI,eAAe,WAAW,UAC5B,mBAAkB,eAAe;UACxB,eAAe,WAAW,WACnC,oBAAA,GAAA,kBAAA,iBAAkC;KAElC,mBAAkB,6BACd,eAAe,IAAA,GAAA,kBAAA,iBACC;AAGtB,QACE,iBAAA,GAAA,kBAAA,KAACA,MAAAA,UAAD;EAAuB,UAAU;YAC9B;EACQ,EAFI,OAEJ;;;AAIf,EAAE,OAAO"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"getTranslationFunction.d.ts","sourceRoot":"","sources":["../../../src/server-dir/buildtime/getTranslationFunction.ts"],"names":[],"mappings":"AAYA,OAAO,KAAK,EACV,wBAAwB,EAExB,SAAS,EACV,MAAM,mBAAmB,CAAC;
|
|
1
|
+
{"version":3,"file":"getTranslationFunction.d.ts","sourceRoot":"","sources":["../../../src/server-dir/buildtime/getTranslationFunction.ts"],"names":[],"mappings":"AAYA,OAAO,KAAK,EACV,wBAAwB,EAExB,SAAS,EACV,MAAM,mBAAmB,CAAC;AA0d3B;;;;;;;;;;;;;GAaG;AACH,wBAAsB,KAAK,CACzB,SAAS,CAAC,EAAE,SAAS,GACpB,OAAO,CAAC,CAAC,OAAO,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,wBAAwB,KAAK,MAAM,CAAC,CAG1E;AAED;;GAEG;AACH,wBAAgB,KAAK,CAAC,SAAS,CAAC,EAAE,SAAS,aARtB,MAAM,YAAY,wBAAwB,KAAK,MAAM,CAUzE;AAED;;;;;;;;;GASG;AACH,wBAAsB,WAAW,CAC/B,SAAS,CAAC,EAAE,SAAS,GACpB,OAAO,EACR,CAAC,CAAC,SAAS,MAAM,GAAG,IAAI,GAAG,SAAS,EAClC,UAAU,EAAE,CAAC,EACb,OAAO,CAAC,EAAE,wBAAwB,KAC/B,CAAC,SAAS,MAAM,GAAG,MAAM,GAAG,CAAC,EACnC,CAGA;AAED;;GAEG;AACH,wBAAgB,WAAW,CACzB,SAAS,CAAC,EAAE,SAAS,GACpB,CAAC,CAAC,SAAS,MAAM,GAAG,IAAI,GAAG,SAAS,EACrC,UAAU,EAAE,CAAC,EACb,OAAO,CAAC,EAAE,wBAAwB,KAC/B,CAAC,SAAS,MAAM,GAAG,MAAM,GAAG,CAAC,CAEjC"}
|