generaltranslation 9.4.2 → 9.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +34 -0
- package/README.md +2 -1
- package/dist/{ApiError-BcjcnTAr.cjs → ApiError-BCjEo_CM.cjs} +1 -1
- package/dist/{ApiError-BcjcnTAr.cjs.map → ApiError-BCjEo_CM.cjs.map} +1 -1
- package/dist/{ApiError-CUKcz3YS.mjs → ApiError-DxWKM0Xt.mjs} +1 -1
- package/dist/{ApiError-CUKcz3YS.mjs.map → ApiError-DxWKM0Xt.mjs.map} +1 -1
- package/dist/adapter/createGtApi.d.ts +196 -27
- package/dist/adapter/createGtApi.js +561 -117
- package/dist/adapter/modelProvider.d.ts +4 -0
- package/dist/adapter/modelProvider.js +6 -0
- package/dist/derive-Cv5_y8Tf.mjs +656 -0
- package/dist/derive-Cv5_y8Tf.mjs.map +1 -0
- package/dist/{derive-DBCCXTmL.d.cts → derive-J2NQLqZm.d.cts} +1 -1
- package/dist/derive-t_E3ftJN.cjs +733 -0
- package/dist/derive-t_E3ftJN.cjs.map +1 -0
- package/dist/diagnostics-CqAHg_Vc.d.cts +34 -0
- package/dist/diagnostics-DKA2SkZB.mjs +45 -0
- package/dist/diagnostics-DKA2SkZB.mjs.map +1 -0
- package/dist/{unwrapApiResult-BzGfPw75.mjs → diagnostics-DKtiPUvo.cjs} +12 -31
- package/dist/diagnostics-DKtiPUvo.cjs.map +1 -0
- package/dist/diagnostics-DYtVjOm5.d.mts +34 -0
- package/dist/diagnostics.cjs +4 -0
- package/dist/diagnostics.d.cts +2 -0
- package/dist/diagnostics.d.mts +2 -0
- package/dist/diagnostics.d.ts +1 -0
- package/dist/diagnostics.js +1 -0
- package/dist/diagnostics.mjs +2 -0
- package/dist/errors.cjs +1 -1
- package/dist/errors.mjs +1 -1
- package/dist/file-B37WkCqM.cjs.map +1 -1
- package/dist/file-Dga6cyM8.mjs.map +1 -1
- package/dist/{id-X2zyx5Jk.mjs → id-B2wA7-S-.mjs} +19 -3
- package/dist/id-B2wA7-S-.mjs.map +1 -0
- package/dist/{id-pdr3R1xs.cjs → id-DJ_59q21.cjs} +25 -3
- package/dist/id-DJ_59q21.cjs.map +1 -0
- package/dist/id.cjs +1 -1
- package/dist/id.d.cts +1 -1
- package/dist/id.d.mts +1 -1
- package/dist/id.mjs +1 -1
- package/dist/index.cjs +94 -753
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +14 -33
- package/dist/index.d.mts +13 -32
- package/dist/index.d.ts +20 -16
- package/dist/index.js +110 -98
- package/dist/index.mjs +88 -746
- package/dist/index.mjs.map +1 -1
- package/dist/internal.cjs +16 -186
- package/dist/internal.cjs.map +1 -1
- package/dist/internal.d.cts +200 -62
- package/dist/internal.d.mts +199 -61
- package/dist/internal.d.ts +3 -1
- package/dist/internal.js +2 -1
- package/dist/internal.mjs +6 -178
- package/dist/internal.mjs.map +1 -1
- package/dist/logging/errors.d.ts +0 -1
- package/dist/logging/errors.js +0 -6
- package/dist/logging/logger.js +6 -4
- package/dist/openapi.json +2344 -845
- package/dist/runtime.cjs +580 -2
- package/dist/runtime.cjs.map +1 -0
- package/dist/runtime.d.cts +12 -6
- package/dist/runtime.d.mts +12 -6
- package/dist/runtime.d.ts +10 -4
- package/dist/runtime.js +10 -65
- package/dist/runtime.mjs +579 -1
- package/dist/runtime.mjs.map +1 -0
- package/dist/runtimeTranslate-CVw143pQ.mjs +506 -0
- package/dist/runtimeTranslate-CVw143pQ.mjs.map +1 -0
- package/dist/runtimeTranslate-DJioRjb6.cjs +601 -0
- package/dist/runtimeTranslate-DJioRjb6.cjs.map +1 -0
- package/dist/translate/awaitJobs.d.ts +2 -2
- package/dist/translate/awaitJobs.js +1 -156
- package/dist/translate/checkJobStatus.d.ts +2 -1
- package/dist/translate/checkJobStatus.js +1 -55
- package/dist/translate/createBranch.d.ts +2 -6
- package/dist/translate/createBranch.js +1 -53
- package/dist/translate/enqueueFiles.js +1 -95
- package/dist/translate/getProjectInfo.d.ts +2 -6
- package/dist/translate/getProjectInfo.js +1 -54
- package/dist/translate/processFileMoves.d.ts +3 -13
- package/dist/translate/processFileMoves.js +1 -90
- package/dist/translate/publishFiles.d.ts +3 -15
- package/dist/translate/publishFiles.js +1 -56
- package/dist/translate/queryBranchData.js +1 -53
- package/dist/translate/queryFileData.d.ts +3 -41
- package/dist/translate/queryFileData.js +1 -71
- package/dist/translate/runtimeTranslate.d.ts +6 -0
- package/dist/translate/runtimeTranslate.js +297 -0
- package/dist/translate/setupProject.d.ts +2 -6
- package/dist/translate/setupProject.js +1 -63
- package/dist/translate/submitUserEditDiffs.js +1 -68
- package/dist/translate/utils/fetchWithTimeout.js +19 -12
- package/dist/{types-bCr8pV1Z.d.cts → types-Si4UstLL.d.mts} +41 -165
- package/dist/types-dir/__tests__/runtimeTranslate.type-test.js +18 -0
- package/dist/types-dir/api/branch.d.ts +3 -9
- package/dist/types-dir/api/checkFileTranslations.d.ts +2 -22
- package/dist/types-dir/api/downloadFileBatch.d.ts +2 -7
- package/dist/types-dir/api/entry.d.ts +3 -8
- package/dist/types-dir/api/file.d.ts +2 -1
- package/dist/types-dir/api/json.d.ts +1 -4
- package/dist/types-dir/api/project.d.ts +2 -7
- package/dist/types-dir/api/uploadAssets.d.ts +3 -10
- package/dist/types-dir/api/uploadAssets.js +0 -4
- package/dist/types-dir/config.d.ts +1 -0
- package/dist/{types-Dp1drjxq.d.mts → types-yByDbKnV.d.cts} +41 -165
- package/dist/types.d.cts +2 -2
- package/dist/types.d.mts +2 -2
- package/dist/types.d.ts +26 -7
- package/package.json +15 -2
- package/dist/derive-2CDqwrvS.cjs +0 -303
- package/dist/derive-2CDqwrvS.cjs.map +0 -1
- package/dist/derive-CTzR56T_.mjs +0 -233
- package/dist/derive-CTzR56T_.mjs.map +0 -1
- package/dist/id-X2zyx5Jk.mjs.map +0 -1
- package/dist/id-pdr3R1xs.cjs.map +0 -1
- package/dist/isVariable-8-Wy5FnX.mjs +0 -20
- package/dist/isVariable-8-Wy5FnX.mjs.map +0 -1
- package/dist/isVariable-I3nllgeI.cjs +0 -25
- package/dist/isVariable-I3nllgeI.cjs.map +0 -1
- package/dist/projects/getProjectData.js +0 -87
- package/dist/runtime-Bcp4F2ME.mjs +0 -974
- package/dist/runtime-Bcp4F2ME.mjs.map +0 -1
- package/dist/runtime-C25lwh9m.cjs +0 -1027
- package/dist/runtime-C25lwh9m.cjs.map +0 -1
- package/dist/translate/api.d.ts +0 -4
- package/dist/translate/api.js +0 -4
- package/dist/translate/createTag.d.ts +0 -19
- package/dist/translate/createTag.js +0 -67
- package/dist/translate/downloadFileBatch.d.ts +0 -1
- package/dist/translate/downloadFileBatch.js +0 -80
- package/dist/translate/getOrphanedFiles.d.ts +0 -8
- package/dist/translate/getOrphanedFiles.js +0 -97
- package/dist/translate/querySourceFile.d.ts +0 -1
- package/dist/translate/querySourceFile.js +0 -67
- package/dist/translate/translateMany.d.ts +0 -1
- package/dist/translate/translateMany.js +0 -124
- package/dist/translate/uploadFonts.d.ts +0 -1
- package/dist/translate/uploadFonts.js +0 -74
- package/dist/translate/uploadSourceFiles.d.ts +0 -1
- package/dist/translate/uploadSourceFiles.js +0 -90
- package/dist/translate/uploadTranslations.d.ts +0 -1
- package/dist/translate/uploadTranslations.js +0 -106
- package/dist/translate/utils/apiRequest.d.ts +0 -1
- package/dist/translate/utils/apiRequest.js +0 -167
- package/dist/translate/utils/generateRequestHeaders.d.ts +0 -2
- package/dist/translate/utils/generateRequestHeaders.js +0 -21
- package/dist/translate/utils/handleFetchError.d.ts +0 -1
- package/dist/translate/utils/handleFetchError.js +0 -12
- package/dist/unwrapApiResult-BzGfPw75.mjs.map +0 -1
- package/dist/unwrapApiResult-Dv6Mfw_K.cjs +0 -134
- package/dist/unwrapApiResult-Dv6Mfw_K.cjs.map +0 -1
- /package/dist/{projects/getProjectData.d.ts → types-dir/__tests__/runtimeTranslate.type-test.d.ts} +0 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"runtime.mjs","names":["_isValidLocale","translateWithConfig","translateManyWithConfig","_getRegionProperties","_requiresTranslation","_resolveCanonicalLocale","_resolveAliasLocale"],"sources":["../src/runtime.ts"],"sourcesContent":["// `generaltranslation` language toolkit\n// © 2026, General Translation, Inc.\n\n// ----- IMPORTS ----- //\n\nimport {\n LocaleConfig,\n getRegionProperties as _getRegionProperties,\n isValidLocale as _isValidLocale,\n requiresTranslation as _requiresTranslation,\n resolveAliasLocale as _resolveAliasLocale,\n resolveCanonicalLocale as _resolveCanonicalLocale,\n standardizeLocale as _standardizeLocale,\n} from '@generaltranslation/format';\nimport type {\n CustomMapping,\n CustomRegionMapping,\n CutoffFormatOptions,\n FormatVariables,\n LocaleProperties,\n StringFormat,\n} from '@generaltranslation/format/types';\nimport type { UserTokenProvider } from '@generaltranslation/api';\nimport {\n TranslateManyResult,\n TranslationError,\n TranslationRequestConfig,\n TranslationResult,\n TranslateManyEntry,\n} from './types';\nimport {\n noSourceLocaleProvidedError,\n noTargetLocaleProvidedError,\n invalidLocaleError,\n invalidLocalesError,\n} from './logging/errors';\nimport {\n translate as translateWithConfig,\n translateMany as translateManyWithConfig,\n} from './translate/runtimeTranslate';\nimport { TranslateOptions } from './types-dir/api/entry';\n\n// ============================================================ //\n// Runtime Class //\n// ============================================================ //\n/**\n * Type representing the constructor parameters for the GT and GTRuntime classes.\n * @typedef {Object} GTConstructorParams\n * @property {string} [apiKey] - The API key for accessing the translation service\n * @property {string} [devApiKey] - Deprecated alias for apiKey\n * @property {string} [sourceLocale] - The default source locale for translations\n * @property {string} [targetLocale] - The default target locale for translations\n * @property {string[]} [locales] - Array of supported locales\n * @property {string} [projectId] - The project ID for the translation service\n * @property {string} [baseUrl] - The base URL for the translation service\n * @property {CustomMapping} [customMapping] - Custom mapping of locale codes to their names\n */\nexport type GTConstructorParams = {\n apiKey?: string;\n /** @deprecated Pass the key as `apiKey`; there is one kind of API key. */\n devApiKey?: string;\n sourceLocale?: string;\n targetLocale?: string;\n locales?: string[];\n projectId?: string;\n baseUrl?: string;\n customMapping?: CustomMapping;\n userTokenProvider?: UserTokenProvider;\n};\n\n/**\n * GTRuntime is the runtime core of the GT driver: locale management,\n * formatting, and runtime translation requests.\n *\n * Browser-facing SDK code constructs this class (via `generaltranslation/runtime`)\n * so production bundles do not ship the project/file management API client\n * that lives on the GT class exported from the main entry.\n *\n * @example\n * const gt = new GTRuntime({\n * sourceLocale: 'en-US',\n * targetLocale: 'es-ES',\n * locales: ['en-US', 'es-ES', 'fr-FR']\n * });\n */\nexport class GTRuntime {\n /** Base URL for the translation service API */\n baseUrl?: string;\n\n /** Project ID for the translation service */\n projectId?: string;\n\n /** API key for accessing the translation service */\n apiKey?: string;\n\n /** @deprecated Pass the key as `apiKey`; there is one kind of API key. */\n devApiKey?: string;\n\n /** User-token provider used when no API key is configured */\n userTokenProvider?: UserTokenProvider;\n\n /** Source locale for translations */\n sourceLocale?: string;\n\n /** Target locale for translations */\n targetLocale?: string;\n\n /** Array of supported locales */\n locales?: string[];\n\n /** Custom mapping for locale codes to their names */\n customMapping?: CustomMapping;\n\n /** Lazily derived reverse custom mapping for alias locales */\n reverseCustomMapping?: Record<string, string>;\n\n /** Lazily derived custom mapping for regions */\n customRegionMapping?: CustomRegionMapping;\n\n /** Runtime-safe locale and formatting helpers (backing field) */\n private _localeConfig!: LocaleConfig;\n\n /** Runtime-safe locale and formatting helpers */\n get localeConfig() {\n return this._localeConfig;\n }\n\n /**\n * Constructs an instance of the GTRuntime class.\n *\n * @param {GTConstructorParams} [params] - The parameters for initializing the GTRuntime instance\n * @throws {Error} If an invalid locale is provided\n * @throws {Error} If any of the provided locales are invalid\n *\n * @example\n * const gt = new GTRuntime({\n * apiKey: 'your-api-key',\n * sourceLocale: 'en-US',\n * targetLocale: 'es-ES',\n * locales: ['en-US', 'es-ES', 'fr-FR']\n * });\n */\n constructor(params: GTConstructorParams = {}) {\n // Read environment\n if (typeof process !== 'undefined') {\n this.apiKey ||= process.env?.GT_API_KEY;\n // Deprecated with devApiKey; frameworks resolve the hot-reload key themselves.\n this.devApiKey ||= process.env?.GT_DEV_API_KEY;\n this.projectId ||= process.env?.GT_PROJECT_ID;\n }\n // Set up config\n this.setConfig(params);\n }\n\n setConfig({\n apiKey,\n devApiKey,\n sourceLocale,\n targetLocale,\n locales,\n projectId,\n customMapping,\n baseUrl,\n userTokenProvider,\n }: GTConstructorParams) {\n const effectiveCustomMapping = customMapping ?? this.customMapping;\n\n // ----- Environment properties ----- //\n if (apiKey) this.apiKey = apiKey;\n if (devApiKey) this.devApiKey = devApiKey;\n if (projectId) this.projectId = projectId;\n if (userTokenProvider) this.userTokenProvider = userTokenProvider;\n\n // ----- Validate configured locale identities ----- //\n\n // source locale\n if (sourceLocale) {\n this.sourceLocale = sourceLocale;\n if (!_isValidLocale(this.sourceLocale, effectiveCustomMapping))\n throw new Error(invalidLocaleError(this.sourceLocale));\n }\n\n // target locale\n if (targetLocale) {\n this.targetLocale = targetLocale;\n if (!_isValidLocale(this.targetLocale, effectiveCustomMapping))\n throw new Error(invalidLocaleError(this.targetLocale));\n }\n\n // locales\n if (locales) {\n const result: string[] = [];\n const invalidLocales: string[] = [];\n locales.forEach((locale) => {\n if (_isValidLocale(locale, effectiveCustomMapping)) {\n result.push(locale);\n } else {\n invalidLocales.push(locale);\n }\n });\n if (invalidLocales.length > 0) {\n throw new Error(invalidLocalesError(invalidLocales));\n }\n this.locales = result;\n }\n\n // ----- Other properties ----- //\n if (baseUrl) this.baseUrl = baseUrl;\n if (customMapping) {\n this.customMapping = customMapping;\n this.reverseCustomMapping = Object.fromEntries(\n Object.entries(customMapping)\n .filter(\n ([, value]) => value && typeof value === 'object' && 'code' in value\n )\n .map(([key, value]) => [(value as { code: string }).code, key])\n );\n }\n this._localeConfig = new LocaleConfig({\n defaultLocale: this.sourceLocale,\n locales: this.locales ?? [],\n customMapping: this.customMapping,\n });\n }\n\n // -------------- Private Methods -------------- //\n\n /** Convert app identity only where a GT service expects a language code. */\n protected resolveServiceLocale(locale: string): string {\n return this.standardizeLocale(this.resolveCanonicalLocale(locale));\n }\n\n /**\n * Recover configured spelling without negotiating an unrelated dialect.\n * When several identities use the same service code and there is no request\n * context to disambiguate them, the first configured identity wins.\n */\n protected resolveServiceResponseLocale(locale: string): string {\n const canonical = this.standardizeLocale(locale);\n const configured = [\n ...(this.locales ?? []),\n this.sourceLocale,\n this.targetLocale,\n ...Object.keys(this.customMapping ?? {}),\n ];\n return (\n configured.find(\n (candidate) =>\n candidate && this.resolveServiceLocale(candidate) === canonical\n ) ?? locale\n );\n }\n\n protected _getTranslationConfig(): TranslationRequestConfig {\n return {\n baseUrl: this.baseUrl,\n apiKey: this.apiKey || this.devApiKey,\n projectId: this.projectId || '',\n userTokenProvider: this.userTokenProvider,\n };\n }\n\n /**\n * Translates a single source string to the target locale.\n * Routes through {@link translateMany} under the hood.\n *\n * @param {string} source - The source string to translate.\n * @param {object} options - Translation options including targetLocale and optional entry metadata.\n * @param {number} [timeout] - Timeout in milliseconds; 0 or omitted selects the runtime default.\n * @returns {Promise<TranslationResult | TranslationError>} The translated content.\n *\n * @example\n * const result = await gt.translate('Hello, world!', { targetLocale: 'es' });\n *\n * @example\n * const result = await gt.translate('Hello, world!', {\n * targetLocale: 'es',\n * dataFormat: 'ICU',\n * context: 'A formal greeting',\n * });\n */\n async translate(\n source: TranslateManyEntry,\n options: string | TranslateOptions,\n timeout?: number\n ): Promise<TranslationResult | TranslationError> {\n return translateWithConfig(\n source,\n options,\n {\n ...this._getTranslationConfig(),\n customMapping: this.customMapping,\n timeoutMs: timeout || undefined,\n },\n this\n );\n }\n\n /**\n * Translates multiple source strings to the target locale.\n * Each entry can be a plain string or an object with source and metadata fields.\n *\n * @param {TranslateManyEntry[] | Record<string, TranslateManyEntry>} sources - The source entries to translate. Can be an array or a record keyed by hash.\n * @param {object} options - Translation options including targetLocale.\n * @param {number} [timeout] - Timeout in milliseconds; 0 or omitted selects the runtime default.\n * @returns {Promise<TranslateManyResult | Record<string, TranslationResult>>} The translated contents. An array if sources was an array, a record if sources was a record.\n *\n * @example\n * const result = await gt.translateMany(\n * ['Hello, world!', 'Goodbye, world!'],\n * { targetLocale: 'es' }\n * );\n *\n * @example\n * const result = await gt.translateMany(\n * [{ source: 'Hello, world!', dataFormat: 'ICU' }],\n * { targetLocale: 'es' }\n * );\n *\n * @example\n * const result = await gt.translateMany(\n * { 'my-hash': 'Hello, world!' },\n * { targetLocale: 'es' }\n * );\n */\n async translateMany(\n sources: TranslateManyEntry[],\n options: string | TranslateOptions,\n timeout?: number\n ): Promise<TranslateManyResult>;\n async translateMany(\n sources: Record<string, TranslateManyEntry>,\n options: string | TranslateOptions,\n timeout?: number\n ): Promise<Record<string, TranslationResult>>;\n async translateMany(\n sources: TranslateManyEntry[] | Record<string, TranslateManyEntry>,\n options: string | TranslateOptions,\n timeout?: number\n ): Promise<TranslateManyResult | Record<string, TranslationResult>> {\n return translateManyWithConfig(\n sources,\n options,\n {\n ...this._getTranslationConfig(),\n customMapping: this.customMapping,\n timeoutMs: timeout || undefined,\n },\n this\n );\n }\n\n // -------------- Formatting -------------- //\n\n /**\n * Formats a string with cutoff behavior, applying a terminator when the string exceeds the maximum character limit.\n *\n * This method uses the GT instance's rendering locales by default for locale-specific terminator selection,\n * but can be overridden with custom locales in the options.\n *\n * @param {string} value - The string value to format with cutoff behavior.\n * @param {Object} [options] - Configuration options for cutoff formatting.\n * @param {string | string[]} [options.locales] - The locales to use for terminator selection. Defaults to instance's rendering locales.\n * @param {number} [options.maxChars] - The maximum number of characters to display.\n * - Undefined values are treated as no cutoff.\n * - Negative values follow .slice() behavior and terminator will be added before the value.\n * - 0 will result in an empty string.\n * - If cutoff results in an empty string, no terminator is added.\n * @param {CutoffFormatStyle} [options.style='ellipsis'] - The style of the terminator.\n * @param {string} [options.terminator] - Optional override the terminator to use.\n * @param {string} [options.separator] - Optional override the separator to use between the terminator and the value.\n * - If no terminator is provided, then separator is ignored.\n * @returns {string} The formatted string with terminator applied if cutoff occurs.\n *\n * @example\n * const gt = new GTRuntime({ targetLocale: 'en-US' });\n * gt.formatCutoff('Hello, world!', { maxChars: 8 });\n * // Returns: 'Hello, w...'\n *\n * @example\n * gt.formatCutoff('Hello, world!', { maxChars: -3 });\n * // Returns: '...ld!'\n */\n formatCutoff(\n value: string,\n options?: {\n locales?: string | string[];\n } & CutoffFormatOptions\n ): string {\n return this.localeConfig.formatCutoff(value, this.targetLocale, options);\n }\n\n /**\n * Formats a message according to the specified locales and options.\n *\n * @param {string} message - The message to format.\n * @param {string | string[]} [locales=libraryDefaultLocale] - The locales to use for formatting.\n * @param {FormatVariables} [variables={}] - The variables to use for formatting.\n * @param {StringFormat} [dataFormat='ICU'] - The format of the message.\n * @returns {string} The formatted message.\n *\n * @example\n * gt.formatMessage('Hello {name}', { name: 'John' });\n * // Returns: \"Hello John\"\n *\n * gt.formatMessage('Hello {name}', { name: 'John' }, { locales: ['fr'] });\n * // Returns: \"Bonjour John\"\n */\n formatMessage(\n message: string,\n options?: {\n locales?: string | string[];\n variables?: FormatVariables;\n dataFormat?: StringFormat;\n }\n ): string {\n return this.localeConfig.formatMessage(message, this.targetLocale, options);\n }\n /**\n * Formats a number according to the specified locales and options.\n *\n * @param {number} number - The number to format.\n * @param {Object} [options] - Additional options for number formatting.\n * @param {string | string[]} [options.locales] - The locales to use for formatting.\n * @param {Intl.NumberFormatOptions} [options] - Additional Intl.NumberFormat options.\n * @returns {string} The formatted number.\n *\n * @example\n * gt.formatNum(1234.56, { style: 'currency', currency: 'USD' });\n * // Returns: \"$1,234.56\"\n */\n formatNum(\n number: number,\n options?: {\n locales?: string | string[];\n } & Intl.NumberFormatOptions\n ): string {\n return this.localeConfig.formatNum(number, this.targetLocale, options);\n }\n\n /**\n * Formats a date according to the specified locales and options.\n *\n * @param {Date} date - The date to format.\n * @param {Object} [options] - Additional options for date formatting.\n * @param {string | string[]} [options.locales] - The locales to use for formatting.\n * @param {Intl.DateTimeFormatOptions} [options] - Additional Intl.DateTimeFormat options.\n * @returns {string} The formatted date.\n *\n * @example\n * gt.formatDateTime(new Date(), { dateStyle: 'full', timeStyle: 'long' });\n * // Returns: \"Thursday, March 14, 2024 at 2:30:45 PM GMT-7\"\n */\n formatDateTime(\n date: Date,\n options?: {\n locales?: string | string[];\n } & Intl.DateTimeFormatOptions\n ): string {\n return this.localeConfig.formatDateTime(date, this.targetLocale, options);\n }\n\n /**\n * Formats a currency value according to the specified locales and options.\n *\n * @param {number} value - The currency value to format.\n * @param {string} currency - The currency code (e.g., 'USD', 'EUR')\n * @param {Object} [options] - Additional options for currency formatting.\n * @param {string | string[]} [options.locales] - The locales to use for formatting.\n * @param {Intl.NumberFormatOptions} [options] - Additional Intl.NumberFormat options.\n * @returns {string} The formatted currency value.\n *\n * @example\n * gt.formatCurrency(1234.56, 'USD', { style: 'currency' });\n * // Returns: \"$1,234.56\"\n */\n formatCurrency(\n value: number,\n currency: string,\n options?: {\n locales?: string | string[];\n } & Intl.NumberFormatOptions\n ): string {\n return this.localeConfig.formatCurrency(\n value,\n currency,\n this.targetLocale,\n options\n );\n }\n\n /**\n * Formats a list of items according to the specified locales and options.\n *\n * @param {Array<string | number>} array - The list of items to format.\n * @param {Object} [options] - Additional options for list formatting.\n * @param {string | string[]} [options.locales] - The locales to use for formatting.\n * @param {Intl.ListFormatOptions} [options] - Additional Intl.ListFormat options.\n * @returns {string} The formatted list.\n *\n * @example\n * gt.formatList(['apple', 'banana', 'orange'], { type: 'conjunction' });\n * // Returns: \"apple, banana, and orange\"\n */\n formatList(\n array: Array<string | number>,\n options?: {\n locales?: string | string[];\n } & Intl.ListFormatOptions\n ) {\n return this.localeConfig.formatList(array, this.targetLocale, options);\n }\n\n /**\n * Formats a list of items according to the specified locales and options.\n * @param {Array<T>} array - The list of items to format.\n * @param {Object} [options] - Additional options for list formatting.\n * @param {string | string[]} [options.locales] - The locales to use for formatting.\n * @param {Intl.ListFormatOptions} [options] - Additional Intl.ListFormat options.\n * @returns {Array<T | string>} The formatted list parts.\n *\n * @example\n * gt.formatListToParts(['apple', 42, { foo: 'bar' }], { type: 'conjunction', style: 'short', locales: ['en'] });\n * // Returns: ['apple', ', ', 42, ' and ', '{ foo: \"bar\" }']\n */\n formatListToParts<T>(\n array: Array<T>,\n options?: {\n locales?: string | string[];\n } & Intl.ListFormatOptions\n ): Array<T | string> {\n return this.localeConfig.formatListToParts<T>(\n array,\n this.targetLocale,\n options\n );\n }\n\n /**\n * Formats a relative time value according to the specified locales and options.\n *\n * @param {number} value - The relative time value to format.\n * @param {Intl.RelativeTimeFormatUnit} unit - The unit of time (e.g., 'second', 'minute', 'hour', 'day', 'week', 'month', 'year')\n * @param {Object} options - Additional options for relative time formatting.\n * @param {string | string[]} [options.locales] - The locales to use for formatting.\n * @param {Intl.RelativeTimeFormatOptions} [options] - Additional Intl.RelativeTimeFormat options.\n * @returns {string} The formatted relative time string.\n *\n * @example\n * gt.formatRelativeTime(-1, 'day', { locales: ['en-US'], numeric: 'auto' });\n * // Returns: \"yesterday\"\n */\n formatRelativeTime(\n value: number,\n unit: Intl.RelativeTimeFormatUnit,\n options?: {\n locales?: string | string[];\n } & Omit<Intl.RelativeTimeFormatOptions, 'locales'>\n ): string {\n return this.localeConfig.formatRelativeTime(\n value,\n unit,\n this.targetLocale,\n options\n );\n }\n\n /**\n * Formats a relative time string from a Date, automatically selecting the best unit.\n *\n * @param {Date} date - The date to format relative to now.\n * @param {Object} [options] - Additional options for relative time formatting.\n * @param {string | string[]} [options.locales] - The locales to use for formatting.\n * @returns {string} The formatted relative time string (e.g., \"2 hours ago\", \"in 3 days\")\n *\n * @example\n * gt.formatRelativeTimeFromDate(new Date(Date.now() - 3600000));\n * // Returns: \"1 hour ago\"\n */\n formatRelativeTimeFromDate(\n date: Date,\n options?: {\n locales?: string | string[];\n baseDate?: Date;\n } & Omit<Intl.RelativeTimeFormatOptions, 'locales'>\n ): string {\n return this.localeConfig.formatRelativeTimeFromDate(\n date,\n this.targetLocale,\n options\n );\n }\n\n // -------------- Locale Properties -------------- //\n\n /**\n * Retrieves the display name of a locale code using Intl.DisplayNames, returning an empty string if no name is found.\n *\n * @param {string} [locale=this.targetLocale] - A BCP-47 locale code.\n * @returns {string} The display name corresponding to the code.\n * @throws {Error} If no target locale is provided.\n *\n * @example\n * gt.getLocaleName('es-ES');\n * // Returns: \"Spanish (Spain)\"\n */\n getLocaleName(locale = this.targetLocale): string {\n if (!locale) throw new Error(noTargetLocaleProvidedError('getLocaleName'));\n return this.localeConfig.getLocaleName(locale);\n }\n\n /**\n * Retrieves an emoji based on a given locale code.\n * Uses the locale's region (if present) to select an emoji or falls back on default emojis.\n *\n * @param {string} [locale=this.targetLocale] - A BCP-47 locale code (e.g., 'en-US', 'fr-CA')\n * @returns {string} The emoji representing the locale or its region.\n * @throws {Error} If no target locale is provided.\n *\n * @example\n * gt.getLocaleEmoji('es-ES');\n * // Returns: \"🇪🇸\"\n */\n getLocaleEmoji(locale = this.targetLocale): string {\n if (!locale) throw new Error(noTargetLocaleProvidedError('getLocaleEmoji'));\n return this.localeConfig.getLocaleEmoji(locale);\n }\n\n /**\n * Generates linguistic details for a given locale code.\n *\n * This function returns information about the locale,\n * script, and region of a given language code both in a standard form and in a maximized form (with likely script and region).\n * The function provides these names in both your default language and native forms, and an associated emoji.\n *\n * @param {string} [locale=this.targetLocale] - The locale code to get properties for (e.g., \"de-AT\").\n * @returns {LocaleProperties} - An object containing detailed information about the locale.\n *\n * @property {string} code - The full locale code, e.g., \"de-AT\".\n * @property {string} name - Language name in the default display language, e.g., \"Austrian German\".\n * @property {string} nativeName - Language name in the locale's native language, e.g., \"Österreichisches Deutsch\".\n * @property {string} languageCode - The base language code, e.g., \"de\".\n * @property {string} languageName - The language name in the default display language, e.g., \"German\".\n * @property {string} nativeLanguageName - The language name in the native language, e.g., \"Deutsch\".\n * @property {string} nameWithRegionCode - Language name with region in the default language, e.g., \"German (AT)\".\n * @property {string} nativeNameWithRegionCode - Language name with region in the native language, e.g., \"Deutsch (AT)\".\n * @property {string} regionCode - The region code from maximization, e.g., \"AT\".\n * @property {string} regionName - The region name in the default display language, e.g., \"Austria\".\n * @property {string} nativeRegionName - The region name in the native language, e.g., \"Österreich\".\n * @property {string} scriptCode - The script code from maximization, e.g., \"Latn\".\n * @property {string} scriptName - The script name in the default display language, e.g., \"Latin\".\n * @property {string} nativeScriptName - The script name in the native language, e.g., \"Lateinisch\".\n * @property {string} maximizedCode - The maximized locale code, e.g., \"de-Latn-AT\".\n * @property {string} maximizedName - Maximized locale name with likely script in the default language, e.g., \"Austrian German (Latin)\".\n * @property {string} nativeMaximizedName - Maximized locale name in the native language, e.g., \"Österreichisches Deutsch (Lateinisch)\".\n * @property {string} minimizedCode - Minimized locale code, e.g., \"de-AT\" (or \"de\" for \"de-DE\").\n * @property {string} minimizedName - Minimized language name in the default language, e.g., \"Austrian German\".\n * @property {string} nativeMinimizedName - Minimized language name in the native language, e.g., \"Österreichisches Deutsch\".\n * @property {string} emoji - The emoji associated with the locale's region, if applicable.\n */\n getLocaleProperties(locale = this.targetLocale): LocaleProperties {\n if (!locale)\n throw new Error(noTargetLocaleProvidedError('getLocaleProperties'));\n return this.localeConfig.getLocaleProperties(locale);\n }\n\n /**\n * Retrieves multiple properties for a given region code, including:\n * - `code`: the original region code\n * - `name`: the localized display name\n * - `emoji`: the associated flag or symbol\n *\n * Behavior:\n * - Accepts ISO 3166-1 alpha-2 or UN M.49 region codes (e.g., `\"US\"`, `\"FR\"`, `\"419\"`).\n * - Uses the instance's `targetLocale` to localize the region name for the user.\n * - If `customMapping` contains a `name` or `emoji` for the region, those override the default values.\n * - Otherwise, uses `Intl.DisplayNames` to get the localized region name, falling back to `libraryDefaultLocale`.\n * - Falls back to the region code as `name` if display name resolution fails.\n * - Falls back to a default emoji if no emoji mapping is found in built-in data or `customMapping`.\n *\n * @param {string} [region=this.getLocaleProperties().regionCode] - The region code to look up (e.g., `\"US\"`, `\"GB\"`, `\"DE\"`).\n * @param {CustomRegionMapping} [customMapping] - Optional mapping of region codes to custom names and/or emojis.\n * @returns {{ code: string, name: string, emoji: string }} An object containing:\n * - `code`: the input region code\n * - `name`: the localized or custom region name\n * - `emoji`: the matching emoji flag or symbol\n *\n * @throws {Error} If no target locale is available to determine region properties.\n *\n * @example\n * const gt = new GTRuntime({ targetLocale: 'en-US' });\n * gt.getRegionProperties('US');\n * // => { code: 'US', name: 'United States', emoji: '🇺🇸' }\n *\n * @example\n * const gt = new GTRuntime({ targetLocale: 'fr-FR' });\n * gt.getRegionProperties('US');\n * // => { code: 'US', name: 'États-Unis', emoji: '🇺🇸' }\n *\n * @example\n * gt.getRegionProperties('US', { US: { name: 'USA', emoji: '🗽' } });\n * // => { code: 'US', name: 'USA', emoji: '🗽' }\n */\n getRegionProperties(\n region = this.getLocaleProperties().regionCode,\n customMapping?: CustomRegionMapping\n ): { code: string; name: string; emoji: string } {\n if (!customMapping) {\n if (this.customMapping && !this.customRegionMapping) {\n // Lazy derive custom region mapping from customMapping\n const customRegionMapping: CustomRegionMapping = {};\n for (const [locale, lp] of Object.entries(this.customMapping)) {\n if (\n lp &&\n typeof lp === 'object' &&\n lp.regionCode &&\n !customRegionMapping[lp.regionCode]\n ) {\n const { regionName: name, emoji } = lp;\n customRegionMapping[lp.regionCode] = {\n locale,\n ...(name && { name }),\n ...(emoji && { emoji }),\n };\n }\n }\n this.customRegionMapping = customRegionMapping;\n }\n customMapping = this.customRegionMapping;\n }\n return _getRegionProperties(\n region,\n this.targetLocale, // this.targetLocale because we want it in the user's language\n customMapping\n );\n }\n\n /**\n * Determines whether a translation is required based on the source and target locales.\n *\n * @param {string} [sourceLocale=this.sourceLocale] - The locale code for the original content.\n * @param {string} [targetLocale=this.targetLocale] - The locale code to translate into.\n * @param {string[]} [approvedLocales=this.locales] - Optional array of approved target locales.\n * @returns {boolean} True if translation is required, false otherwise\n * @throws {Error} If no source locale is provided.\n * @throws {Error} If no target locale is provided.\n *\n * @example\n * gt.requiresTranslation('en-US', 'es-ES');\n * // Returns: true\n */\n requiresTranslation(\n sourceLocale = this.sourceLocale,\n targetLocale = this.targetLocale,\n approvedLocales: string[] | undefined = this.locales,\n customMapping: CustomMapping | undefined = this.customMapping\n ): boolean {\n if (!sourceLocale)\n throw new Error(noSourceLocaleProvidedError('requiresTranslation'));\n if (!targetLocale)\n throw new Error(noTargetLocaleProvidedError('requiresTranslation'));\n if (customMapping === this.customMapping) {\n return this.localeConfig.requiresTranslation(\n targetLocale,\n sourceLocale,\n approvedLocales\n );\n }\n return _requiresTranslation(\n sourceLocale,\n targetLocale,\n approvedLocales,\n customMapping\n );\n }\n\n /**\n * Determines the best matching locale from the provided approved locales list.\n *\n * @param {string | string[]} locales - A single locale or array of locales in preference order.\n * @param {string[]} [approvedLocales=this.locales] - Array of approved locales in preference order.\n * @returns {string | undefined} The best matching locale, or undefined if no match is found.\n *\n * @example\n * gt.determineLocale(['fr-CA', 'fr-FR'], ['en-US', 'fr-FR', 'es-ES']);\n * // Returns: \"fr-FR\"\n */\n determineLocale(\n locales: string | string[],\n approvedLocales: string[] | undefined = this.locales || [],\n customMapping: CustomMapping | undefined = this.customMapping\n ): string | undefined {\n if (customMapping === this.customMapping) {\n return this.localeConfig.determineLocale(locales, approvedLocales ?? []);\n }\n return new LocaleConfig({ customMapping }).determineLocale(\n locales,\n approvedLocales ?? []\n );\n }\n\n /**\n * Gets the text direction for a given locale code.\n *\n * @param {string} [locale=this.targetLocale] - A BCP-47 locale code.\n * @returns {'ltr' | 'rtl'} 'rtl' if the locale is right-to-left; otherwise 'ltr'.\n * @throws {Error} If no target locale is provided.\n *\n * @example\n * gt.getLocaleDirection('ar-SA');\n * // Returns: \"rtl\"\n */\n getLocaleDirection(locale = this.targetLocale): 'ltr' | 'rtl' {\n if (!locale)\n throw new Error(noTargetLocaleProvidedError('getLocaleDirection'));\n return this.localeConfig.getLocaleDirection(locale);\n }\n\n /**\n * Checks if a given BCP 47 locale code is valid.\n *\n * @param {string} [locale=this.targetLocale] - The BCP 47 locale code to validate.\n * @param {CustomMapping} [customMapping=this.customMapping] - The custom mapping to use for validation.\n * @returns {boolean} True if the locale code is valid, false otherwise\n * @throws {Error} If no target locale is provided.\n *\n * @example\n * gt.isValidLocale('en-US');\n * // Returns: true\n */\n isValidLocale(\n locale = this.targetLocale,\n customMapping: CustomMapping | undefined = this.customMapping\n ): boolean {\n if (!locale) throw new Error(noTargetLocaleProvidedError('isValidLocale'));\n if (customMapping === this.customMapping) {\n return this.localeConfig.isValidLocale(locale);\n }\n return _isValidLocale(locale, customMapping);\n }\n\n /**\n * Resolves the canonical locale for a given locale.\n * @param locale - The locale to resolve the canonical locale for\n * @param customMapping - The custom mapping to use for resolving the canonical locale\n * @returns The canonical locale, or the input locale when no canonical mapping exists.\n */\n resolveCanonicalLocale(\n locale: string | undefined = this.targetLocale,\n customMapping: CustomMapping | undefined = this.customMapping\n ): string {\n if (!locale)\n throw new Error(noTargetLocaleProvidedError('resolveCanonicalLocale'));\n if (customMapping === this.customMapping) {\n return this.localeConfig.resolveCanonicalLocale(locale);\n }\n return _resolveCanonicalLocale(locale, customMapping);\n }\n\n /**\n * Resolves the alias locale for a given locale.\n * @param locale - The locale to resolve the alias locale for\n * @param customMapping - The custom mapping to use for resolving the alias locale\n * @returns The configured alias for a canonical locale, or the input locale when already an alias or no alias mapping exists.\n */\n resolveAliasLocale(\n locale: string,\n customMapping: CustomMapping | undefined = this.customMapping\n ): string {\n if (!locale)\n throw new Error(noTargetLocaleProvidedError('resolveAliasLocale'));\n if (customMapping === this.customMapping) {\n return this.localeConfig.resolveAliasLocale(locale);\n }\n return _resolveAliasLocale(locale, customMapping);\n }\n\n /**\n * Standardizes a BCP 47 locale code to ensure correct formatting.\n *\n * @param {string} [locale=this.targetLocale] - The BCP 47 locale code to standardize.\n * @returns {string} The standardized locale code, or the input string if it cannot be standardized.\n * @throws {Error} If no target locale is provided.\n *\n * @example\n * gt.standardizeLocale('en_us');\n * // Returns: \"en-US\"\n */\n standardizeLocale(locale = this.targetLocale): string {\n if (!locale)\n throw new Error(noTargetLocaleProvidedError('standardizeLocale'));\n return this.localeConfig.standardizeLocale(locale);\n }\n\n /**\n * Checks if multiple BCP 47 locale codes represent the same dialect.\n *\n * @param {...(string | string[])} locales - The BCP 47 locale codes to compare.\n * @returns {boolean} True if all codes represent the same dialect, false otherwise\n *\n * @example\n * gt.isSameDialect('en-US', 'en-GB');\n * // Returns: false\n *\n * gt.isSameDialect('en', 'en-US');\n * // Returns: true\n */\n isSameDialect(...locales: (string | string[])[]): boolean {\n return this.localeConfig.isSameDialect(...locales);\n }\n\n /**\n * Checks if multiple BCP 47 locale codes represent the same language.\n *\n * @param {...(string | string[])} locales - The BCP 47 locale codes to compare.\n * @returns {boolean} True if all codes represent the same language, false otherwise\n *\n * @example\n * gt.isSameLanguage('en-US', 'en-GB');\n * // Returns: true\n */\n isSameLanguage(...locales: (string | string[])[]): boolean {\n return this.localeConfig.isSameLanguage(...locales);\n }\n\n /**\n * Checks if a locale is a superset of another locale.\n *\n * @param {string} superLocale - The locale to check if it is a superset\n * @param {string} subLocale - The locale to check if it is a subset\n * @returns {boolean} True if superLocale is a superset of subLocale, false otherwise\n *\n * @example\n * gt.isSupersetLocale('en', 'en-US');\n * // Returns: true\n *\n * gt.isSupersetLocale('en-US', 'en');\n * // Returns: false\n */\n isSupersetLocale(superLocale: string, subLocale: string): boolean {\n return this.localeConfig.isSupersetLocale(superLocale, subLocale);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAqFA,IAAa,YAAb,MAAuB;;CAsCrB,IAAI,eAAe;AACjB,SAAO,KAAK;;;;;;;;;;;;;;;;;CAkBd,YAAY,SAA8B,EAAE,EAAE;AAE5C,MAAI,OAAO,YAAY,aAAa;AAClC,QAAK,WAAW,QAAQ,KAAK;AAE7B,QAAK,cAAc,QAAQ,KAAK;AAChC,QAAK,cAAc,QAAQ,KAAK;;AAGlC,OAAK,UAAU,OAAO;;CAGxB,UAAU,EACR,QACA,WACA,cACA,cAC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KAAK,cACzB,QAAO,KAAK,aAAa,uBAAuB,OAAO;AAEzD,SAAOK,uBAAwB,QAAQ,cAAc;;;;;;;;CASvD,mBACE,QACA,gBAA2C,KAAK,eACxC;AACR,MAAI,CAAC,OACH,OAAM,IAAI,MAAM,4BAA4B,qBAAqB,CAAC;AACpE,MAAI,kBAAkB,KAAK,cACzB,QAAO,KAAK,aAAa,mBAAmB,OAAO;AAErD,SAAOC,mBAAoB,QAAQ,cAAc;;;;;;;;;;;;;CAcnD,kBAAkB,SAAS,KAAK,cAAsB;AACpD,MAAI,CAAC,OACH,OAAM,IAAI,MAAM,4BAA4B,oBAAoB,CAAC;AACnE,SAAO,KAAK,aAAa,kBAAkB,OAAO;;;;;;;;;;;;;;;CAgBpD,cAAc,GAAG,SAAyC;AACxD,SAAO,KAAK,aAAa,cAAc,GAAG,QAAQ;;;;;;;;;;;;CAapD,eAAe,GAAG,SAAyC;AACzD,SAAO,KAAK,aAAa,eAAe,GAAG,QAAQ;;;;;;;;;;;;;;;;CAiBrD,iBAAiB,aAAqB,WAA4B;AAChE,SAAO,KAAK,aAAa,iBAAiB,aAAa,UAAU"}
|
|
@@ -0,0 +1,506 @@
|
|
|
1
|
+
import { t as createDiagnosticMessage } from "./diagnostics-DKA2SkZB.mjs";
|
|
2
|
+
import { t as hashSource } from "./id-B2wA7-S-.mjs";
|
|
3
|
+
import { t as ApiError } from "./ApiError-DxWKM0Xt.mjs";
|
|
4
|
+
import { ModelProvider, createApiClient, translate } from "@generaltranslation/api";
|
|
5
|
+
import { resolveCanonicalLocale, standardizeLocale } from "@generaltranslation/format";
|
|
6
|
+
//#region src/settings/settings.ts
|
|
7
|
+
const libraryDefaultLocale = "en";
|
|
8
|
+
const defaultTimeout = 6e4;
|
|
9
|
+
//#endregion
|
|
10
|
+
//#region src/settings/settingsUrls.ts
|
|
11
|
+
const defaultCacheUrl = "https://cdn.gtx.dev";
|
|
12
|
+
const defaultBaseUrl = "https://api.gtx.dev";
|
|
13
|
+
const defaultRuntimeApiUrl = "https://api.gtx.dev";
|
|
14
|
+
//#endregion
|
|
15
|
+
//#region src/logging/errors.ts
|
|
16
|
+
const GT_SOURCE = "GT";
|
|
17
|
+
const translationTimeoutError = (timeout) => createDiagnosticMessage({
|
|
18
|
+
source: GT_SOURCE,
|
|
19
|
+
severity: "Error",
|
|
20
|
+
whatHappened: `Translation request timed out after ${timeout}ms`,
|
|
21
|
+
fix: "Try again, or increase the request timeout if the source content is large"
|
|
22
|
+
});
|
|
23
|
+
const apiError = (status, statusText, error) => createDiagnosticMessage({
|
|
24
|
+
source: GT_SOURCE,
|
|
25
|
+
severity: "Error",
|
|
26
|
+
whatHappened: `The translation API returned ${status} ${statusText}`,
|
|
27
|
+
fix: "Check the request configuration and try again",
|
|
28
|
+
details: error
|
|
29
|
+
});
|
|
30
|
+
const noTargetLocaleProvidedError = (functionName) => createDiagnosticMessage({
|
|
31
|
+
source: GT_SOURCE,
|
|
32
|
+
severity: "Error",
|
|
33
|
+
whatHappened: `Cannot call \`${functionName}\` without a specified locale`,
|
|
34
|
+
fix: `Pass a locale to \`${functionName}\` or specify targetLocale in the GT constructor`
|
|
35
|
+
});
|
|
36
|
+
const noSourceLocaleProvidedError = (functionName) => createDiagnosticMessage({
|
|
37
|
+
source: GT_SOURCE,
|
|
38
|
+
severity: "Error",
|
|
39
|
+
whatHappened: `Cannot call \`${functionName}\` without a specified locale`,
|
|
40
|
+
fix: `Pass a locale to \`${functionName}\` or specify sourceLocale in the GT constructor`
|
|
41
|
+
});
|
|
42
|
+
const noProjectIdProvidedError = (functionName) => createDiagnosticMessage({
|
|
43
|
+
source: GT_SOURCE,
|
|
44
|
+
severity: "Error",
|
|
45
|
+
whatHappened: `Cannot call \`${functionName}\` without a specified project ID`,
|
|
46
|
+
fix: `Pass a project ID to \`${functionName}\` or specify projectId in the GT constructor`
|
|
47
|
+
});
|
|
48
|
+
const noApiKeyProvidedError = (functionName) => createDiagnosticMessage({
|
|
49
|
+
source: GT_SOURCE,
|
|
50
|
+
severity: "Error",
|
|
51
|
+
whatHappened: `Cannot call \`${functionName}\` without a specified API key`,
|
|
52
|
+
fix: `Pass an API key to \`${functionName}\` or specify apiKey in the GT constructor`
|
|
53
|
+
});
|
|
54
|
+
const invalidLocaleError = (locale) => createDiagnosticMessage({
|
|
55
|
+
source: GT_SOURCE,
|
|
56
|
+
severity: "Error",
|
|
57
|
+
whatHappened: `Locale "${locale}" is not valid`,
|
|
58
|
+
fix: "Use a valid BCP 47 locale code or add a custom mapping"
|
|
59
|
+
});
|
|
60
|
+
const invalidLocalesError = (locales) => createDiagnosticMessage({
|
|
61
|
+
source: GT_SOURCE,
|
|
62
|
+
severity: "Error",
|
|
63
|
+
whatHappened: `These locales are not valid: ${locales.join(", ")}`,
|
|
64
|
+
fix: "Use valid BCP 47 locale codes or add custom mappings"
|
|
65
|
+
});
|
|
66
|
+
//#endregion
|
|
67
|
+
//#region src/logging/logger.ts
|
|
68
|
+
const LOG_LEVELS = {
|
|
69
|
+
debug: 0,
|
|
70
|
+
info: 1,
|
|
71
|
+
warn: 2,
|
|
72
|
+
error: 3,
|
|
73
|
+
off: 4
|
|
74
|
+
};
|
|
75
|
+
const LOG_COLORS = {
|
|
76
|
+
debug: "\x1B[36m",
|
|
77
|
+
info: "\x1B[32m",
|
|
78
|
+
warn: "\x1B[33m",
|
|
79
|
+
error: "\x1B[31m",
|
|
80
|
+
off: ""
|
|
81
|
+
};
|
|
82
|
+
const RESET_COLOR = "\x1B[0m";
|
|
83
|
+
/**
|
|
84
|
+
* Get the configured log level from environment variable or default to 'warn'
|
|
85
|
+
*/
|
|
86
|
+
function getConfiguredLogLevel() {
|
|
87
|
+
if (typeof process !== "undefined" && process.env?._GT_LOG_LEVEL) {
|
|
88
|
+
const envLevel = process.env._GT_LOG_LEVEL.toLowerCase();
|
|
89
|
+
if (envLevel in LOG_LEVELS) return envLevel;
|
|
90
|
+
}
|
|
91
|
+
return "warn";
|
|
92
|
+
}
|
|
93
|
+
/**
|
|
94
|
+
* Console log handler that outputs formatted messages to console
|
|
95
|
+
*/
|
|
96
|
+
var ConsoleLogHandler = class {
|
|
97
|
+
constructor(config) {
|
|
98
|
+
this.config = config;
|
|
99
|
+
}
|
|
100
|
+
handle(entry) {
|
|
101
|
+
const parts = [];
|
|
102
|
+
if (this.config.includeTimestamp) parts.push(`[${entry.timestamp.toISOString()}]`);
|
|
103
|
+
const colorCode = LOG_COLORS[entry.level];
|
|
104
|
+
const levelText = `[${entry.level.toUpperCase()}]`;
|
|
105
|
+
parts.push(`${colorCode}${levelText}${RESET_COLOR}`);
|
|
106
|
+
if (this.config.prefix) parts.push(`[${this.config.prefix}]`);
|
|
107
|
+
if (this.config.includeContext && entry.context) parts.push(`[${entry.context}]`);
|
|
108
|
+
parts.push(entry.message);
|
|
109
|
+
if (entry.metadata && Object.keys(entry.metadata).length > 0) parts.push(`\n Metadata: ${JSON.stringify(entry.metadata, null, 2)}`);
|
|
110
|
+
const formattedMessage = parts.join(" ");
|
|
111
|
+
switch (entry.level) {
|
|
112
|
+
case "debug":
|
|
113
|
+
console.debug(formattedMessage);
|
|
114
|
+
break;
|
|
115
|
+
case "info":
|
|
116
|
+
console.info(formattedMessage);
|
|
117
|
+
break;
|
|
118
|
+
case "warn":
|
|
119
|
+
console.warn(formattedMessage);
|
|
120
|
+
break;
|
|
121
|
+
case "error":
|
|
122
|
+
console.error(formattedMessage);
|
|
123
|
+
break;
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
};
|
|
127
|
+
/**
|
|
128
|
+
* Main Logger class providing structured logging capabilities.
|
|
129
|
+
*/
|
|
130
|
+
var Logger = class {
|
|
131
|
+
constructor(config = {}) {
|
|
132
|
+
this.config = {
|
|
133
|
+
level: getConfiguredLogLevel(),
|
|
134
|
+
includeTimestamp: true,
|
|
135
|
+
includeContext: true,
|
|
136
|
+
enableConsole: true,
|
|
137
|
+
handlers: [],
|
|
138
|
+
...config
|
|
139
|
+
};
|
|
140
|
+
this.handlers = [...this.config.handlers || []];
|
|
141
|
+
if (this.config.enableConsole) this.handlers.push(new ConsoleLogHandler(this.config));
|
|
142
|
+
}
|
|
143
|
+
/**
|
|
144
|
+
* Add a custom log handler
|
|
145
|
+
*/
|
|
146
|
+
addHandler(handler) {
|
|
147
|
+
this.handlers.push(handler);
|
|
148
|
+
}
|
|
149
|
+
/**
|
|
150
|
+
* Remove a log handler
|
|
151
|
+
*/
|
|
152
|
+
removeHandler(handler) {
|
|
153
|
+
const index = this.handlers.indexOf(handler);
|
|
154
|
+
if (index > -1) this.handlers.splice(index, 1);
|
|
155
|
+
}
|
|
156
|
+
/**
|
|
157
|
+
* Update logger configuration
|
|
158
|
+
*/
|
|
159
|
+
configure(config) {
|
|
160
|
+
this.config = {
|
|
161
|
+
...this.config,
|
|
162
|
+
...config
|
|
163
|
+
};
|
|
164
|
+
}
|
|
165
|
+
/**
|
|
166
|
+
* Check if a log level should be output based on current configuration
|
|
167
|
+
*/
|
|
168
|
+
shouldLog(level) {
|
|
169
|
+
return LOG_LEVELS[level] >= LOG_LEVELS[this.config.level];
|
|
170
|
+
}
|
|
171
|
+
/**
|
|
172
|
+
* Internal logging method that creates log entries and passes them to handlers
|
|
173
|
+
*/
|
|
174
|
+
log(level, message, context, metadata) {
|
|
175
|
+
if (!this.shouldLog(level)) return;
|
|
176
|
+
const entry = {
|
|
177
|
+
level,
|
|
178
|
+
message,
|
|
179
|
+
timestamp: /* @__PURE__ */ new Date(),
|
|
180
|
+
context,
|
|
181
|
+
metadata
|
|
182
|
+
};
|
|
183
|
+
this.handlers.forEach((handler) => {
|
|
184
|
+
try {
|
|
185
|
+
handler.handle(entry);
|
|
186
|
+
} catch (error) {
|
|
187
|
+
console.error("Error in log handler:", error);
|
|
188
|
+
}
|
|
189
|
+
});
|
|
190
|
+
}
|
|
191
|
+
/**
|
|
192
|
+
* Log a debug message
|
|
193
|
+
* Used for detailed diagnostic information, typically of interest only when diagnosing problems
|
|
194
|
+
*/
|
|
195
|
+
debug(message, context, metadata) {
|
|
196
|
+
this.log("debug", message, context, metadata);
|
|
197
|
+
}
|
|
198
|
+
/**
|
|
199
|
+
* Log an info message
|
|
200
|
+
* Used for general information about application operation.
|
|
201
|
+
*/
|
|
202
|
+
info(message, context, metadata) {
|
|
203
|
+
this.log("info", message, context, metadata);
|
|
204
|
+
}
|
|
205
|
+
/**
|
|
206
|
+
* Log a warning message
|
|
207
|
+
* Used for potentially problematic situations that don't prevent operation
|
|
208
|
+
*/
|
|
209
|
+
warn(message, context, metadata) {
|
|
210
|
+
this.log("warn", message, context, metadata);
|
|
211
|
+
}
|
|
212
|
+
/**
|
|
213
|
+
* Log an error message
|
|
214
|
+
* Used for error events that might still allow the application to continue.
|
|
215
|
+
*/
|
|
216
|
+
error(message, context, metadata) {
|
|
217
|
+
this.log("error", message, context, metadata);
|
|
218
|
+
}
|
|
219
|
+
/**
|
|
220
|
+
* Create a child logger with a specific context
|
|
221
|
+
*/
|
|
222
|
+
child(context) {
|
|
223
|
+
return new ContextLogger(this, context);
|
|
224
|
+
}
|
|
225
|
+
/**
|
|
226
|
+
* Get current logger configuration
|
|
227
|
+
*/
|
|
228
|
+
getConfig() {
|
|
229
|
+
return { ...this.config };
|
|
230
|
+
}
|
|
231
|
+
};
|
|
232
|
+
/**
|
|
233
|
+
* Context logger that automatically includes context information.
|
|
234
|
+
*/
|
|
235
|
+
var ContextLogger = class ContextLogger {
|
|
236
|
+
constructor(logger, context) {
|
|
237
|
+
this.logger = logger;
|
|
238
|
+
this.context = context;
|
|
239
|
+
}
|
|
240
|
+
debug(message, metadata) {
|
|
241
|
+
this.logger.debug(message, this.context, metadata);
|
|
242
|
+
}
|
|
243
|
+
info(message, metadata) {
|
|
244
|
+
this.logger.info(message, this.context, metadata);
|
|
245
|
+
}
|
|
246
|
+
warn(message, metadata) {
|
|
247
|
+
this.logger.warn(message, this.context, metadata);
|
|
248
|
+
}
|
|
249
|
+
error(message, metadata) {
|
|
250
|
+
this.logger.error(message, this.context, metadata);
|
|
251
|
+
}
|
|
252
|
+
child(childContext) {
|
|
253
|
+
return new ContextLogger(this.logger, `${this.context}:${childContext}`);
|
|
254
|
+
}
|
|
255
|
+
};
|
|
256
|
+
const gtInstanceLogger = /* @__PURE__ */ (/* @__PURE__ */ new Logger({
|
|
257
|
+
level: getConfiguredLogLevel(),
|
|
258
|
+
includeTimestamp: true,
|
|
259
|
+
includeContext: true,
|
|
260
|
+
prefix: "GT"
|
|
261
|
+
})).child("GT instance");
|
|
262
|
+
//#endregion
|
|
263
|
+
//#region src/adapter/modelProvider.ts
|
|
264
|
+
const supportedModelProviders = /* @__PURE__ */ Object.values(ModelProvider);
|
|
265
|
+
function isModelProvider(value) {
|
|
266
|
+
return supportedModelProviders.includes(value);
|
|
267
|
+
}
|
|
268
|
+
//#endregion
|
|
269
|
+
//#region src/translate/utils/fetchWithTimeout.ts
|
|
270
|
+
/**
|
|
271
|
+
* @internal
|
|
272
|
+
*
|
|
273
|
+
* Wraps a fetch implementation with the runtime translation timeout.
|
|
274
|
+
*
|
|
275
|
+
* @param url - The URL to fetch.
|
|
276
|
+
* @param options - The options to pass to the fetch function.
|
|
277
|
+
* @param timeoutMs - The timeout in milliseconds. Omitted selects `defaultTimeout`,
|
|
278
|
+
* `0` is a literal zero, and `false` disables the runtime-owned timer.
|
|
279
|
+
* @param fetchImplementation - The fetch implementation to call. Defaults to global fetch.
|
|
280
|
+
* @returns The response from the fetch function.
|
|
281
|
+
*/
|
|
282
|
+
async function fetchWithTimeout(url, options, timeoutMs = defaultTimeout, fetchImplementation = globalThis.fetch) {
|
|
283
|
+
const controller = new AbortController();
|
|
284
|
+
const signals = [controller.signal];
|
|
285
|
+
if (options.signal) signals.push(options.signal);
|
|
286
|
+
if (url instanceof Request) signals.push(url.signal);
|
|
287
|
+
const signal = AbortSignal.any(signals);
|
|
288
|
+
let timedOut = false;
|
|
289
|
+
const timeoutId = timeoutMs === false ? null : setTimeout(() => {
|
|
290
|
+
timedOut = !signal.aborted;
|
|
291
|
+
controller.abort();
|
|
292
|
+
}, timeoutMs);
|
|
293
|
+
try {
|
|
294
|
+
return await fetchImplementation(url, {
|
|
295
|
+
...options,
|
|
296
|
+
signal
|
|
297
|
+
});
|
|
298
|
+
} catch (error) {
|
|
299
|
+
if (timedOut && timeoutMs !== false && error === controller.signal.reason) throw translationTimeoutError(timeoutMs);
|
|
300
|
+
throw error;
|
|
301
|
+
} finally {
|
|
302
|
+
if (timeoutId) clearTimeout(timeoutId);
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
//#endregion
|
|
306
|
+
//#region src/translate/utils/unwrapApiResult.ts
|
|
307
|
+
function isErrorResult(error) {
|
|
308
|
+
return typeof error === "object" && error !== null && "error" in error && typeof error.error === "string";
|
|
309
|
+
}
|
|
310
|
+
function hasDecodedError(result) {
|
|
311
|
+
return isErrorResult(result.error) || typeof result.error === "string";
|
|
312
|
+
}
|
|
313
|
+
/**
|
|
314
|
+
* Unwraps a `@generaltranslation/api` SDK result, returning its data or
|
|
315
|
+
* throwing an `ApiError` built from the failed response.
|
|
316
|
+
*/
|
|
317
|
+
function unwrapApiResult(result) {
|
|
318
|
+
if (result.data !== void 0) return result.data;
|
|
319
|
+
if (result.response) {
|
|
320
|
+
const details = isErrorResult(result.error) ? result.error.error : typeof result.error === "string" ? result.error : result.response.statusText;
|
|
321
|
+
throw new ApiError(details, result.response.status, details);
|
|
322
|
+
}
|
|
323
|
+
throw result.error;
|
|
324
|
+
}
|
|
325
|
+
//#endregion
|
|
326
|
+
//#region src/translate/utils/validateResponse.ts
|
|
327
|
+
async function validateResponse(response) {
|
|
328
|
+
if (!response.ok) {
|
|
329
|
+
let errorMsg = "Unknown error";
|
|
330
|
+
try {
|
|
331
|
+
const text = await response.text();
|
|
332
|
+
try {
|
|
333
|
+
errorMsg = JSON.parse(text).error;
|
|
334
|
+
} catch {
|
|
335
|
+
errorMsg = text || "Unknown error";
|
|
336
|
+
}
|
|
337
|
+
} catch {}
|
|
338
|
+
throw new ApiError(apiError(response.status, response.statusText, errorMsg), response.status, errorMsg);
|
|
339
|
+
}
|
|
340
|
+
}
|
|
341
|
+
//#endregion
|
|
342
|
+
//#region src/translate/runtimeTranslate.ts
|
|
343
|
+
/**
|
|
344
|
+
* @internal
|
|
345
|
+
* Credential/provider errors are reported before the project error, and both
|
|
346
|
+
* before any locale validation. GT/GTRuntime share this ordering.
|
|
347
|
+
*/
|
|
348
|
+
function validateAuth(functionName, config) {
|
|
349
|
+
const errors = [];
|
|
350
|
+
if (!config.apiKey && !config.userTokenProvider) errors.push(noApiKeyProvidedError(functionName));
|
|
351
|
+
if (!config.projectId) errors.push(noProjectIdProvidedError(functionName));
|
|
352
|
+
if (errors.length) throw new Error(errors.join("\n"));
|
|
353
|
+
}
|
|
354
|
+
/**
|
|
355
|
+
* @internal
|
|
356
|
+
*
|
|
357
|
+
* Shared preparation for every translation surface (classes and the tooling
|
|
358
|
+
* facade): normalize the string shorthand, validate auth, require a target
|
|
359
|
+
* locale, default the source locale and canonicalize both for the wire.
|
|
360
|
+
*
|
|
361
|
+
* @param defaults - Instance defaults supplied by GT/GTRuntime. Facade calls pass none.
|
|
362
|
+
*/
|
|
363
|
+
function prepareTranslation(functionName, options, config, defaults = {}) {
|
|
364
|
+
if (typeof options === "string") options = { targetLocale: options };
|
|
365
|
+
validateAuth(functionName, config);
|
|
366
|
+
const targetLocale = options?.targetLocale || defaults.targetLocale;
|
|
367
|
+
if (!targetLocale) {
|
|
368
|
+
const error = noTargetLocaleProvidedError(functionName);
|
|
369
|
+
gtInstanceLogger.error(error);
|
|
370
|
+
throw new Error(error);
|
|
371
|
+
}
|
|
372
|
+
const { customMapping, ...requestConfig } = config;
|
|
373
|
+
const resolveServiceLocale = (locale) => standardizeLocale(resolveCanonicalLocale(locale, customMapping));
|
|
374
|
+
return {
|
|
375
|
+
options: {
|
|
376
|
+
...options,
|
|
377
|
+
targetLocale: resolveServiceLocale(targetLocale),
|
|
378
|
+
sourceLocale: resolveServiceLocale(options?.sourceLocale || defaults.sourceLocale || "en")
|
|
379
|
+
},
|
|
380
|
+
config: requestConfig
|
|
381
|
+
};
|
|
382
|
+
}
|
|
383
|
+
/**
|
|
384
|
+
* @internal
|
|
385
|
+
* Translates a single entry with explicit configuration and optional locale defaults.
|
|
386
|
+
*/
|
|
387
|
+
async function translate$1(source, options, config, defaults) {
|
|
388
|
+
const prepared = prepareTranslation("translate", options, config, defaults);
|
|
389
|
+
return (await executeTranslationBatch([source], prepared.options, prepared.config))[0];
|
|
390
|
+
}
|
|
391
|
+
async function translateMany(sources, options, config, defaults) {
|
|
392
|
+
const prepared = prepareTranslation("translateMany", options, config, defaults);
|
|
393
|
+
return await executeTranslationBatch(sources, prepared.options, prepared.config);
|
|
394
|
+
}
|
|
395
|
+
function isJsonObject(value) {
|
|
396
|
+
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
397
|
+
}
|
|
398
|
+
function isGtProp(value) {
|
|
399
|
+
if (!isJsonObject(value)) return false;
|
|
400
|
+
if (value.t !== void 0 && value.t !== "p" && value.t !== "b") return false;
|
|
401
|
+
if ([
|
|
402
|
+
"pl",
|
|
403
|
+
"ti",
|
|
404
|
+
"alt",
|
|
405
|
+
"arl",
|
|
406
|
+
"arb",
|
|
407
|
+
"ard"
|
|
408
|
+
].some((key) => value[key] !== void 0 && typeof value[key] !== "string")) return false;
|
|
409
|
+
return value.b === void 0 || isJsonObject(value.b) && Object.values(value.b).every(isJsxChildren);
|
|
410
|
+
}
|
|
411
|
+
function isJsxElement(value) {
|
|
412
|
+
if (!isJsonObject(value)) return false;
|
|
413
|
+
return (value.t === void 0 || typeof value.t === "string") && (value.i === void 0 || typeof value.i === "number") && (value.d === void 0 || isGtProp(value.d)) && (value.c === void 0 || isJsxChildren(value.c));
|
|
414
|
+
}
|
|
415
|
+
function isJsxChild(value) {
|
|
416
|
+
return typeof value === "string" || isJsxElement(value);
|
|
417
|
+
}
|
|
418
|
+
function isJsxChildren(value) {
|
|
419
|
+
return value === null || typeof value === "boolean" || isJsxChild(value) || Array.isArray(value) && value.every(isJsxChild);
|
|
420
|
+
}
|
|
421
|
+
function toTranslationResult(result) {
|
|
422
|
+
if (!result.success) return result;
|
|
423
|
+
if (result.dataFormat === "JSX" && isJsxChildren(result.translation)) return {
|
|
424
|
+
success: true,
|
|
425
|
+
translation: result.translation,
|
|
426
|
+
dataFormat: result.dataFormat,
|
|
427
|
+
locale: result.locale
|
|
428
|
+
};
|
|
429
|
+
if (result.dataFormat !== "JSX" && typeof result.translation === "string") return {
|
|
430
|
+
success: true,
|
|
431
|
+
translation: result.translation,
|
|
432
|
+
dataFormat: result.dataFormat,
|
|
433
|
+
locale: result.locale
|
|
434
|
+
};
|
|
435
|
+
return {
|
|
436
|
+
success: false,
|
|
437
|
+
error: "Invalid translation returned",
|
|
438
|
+
code: 500
|
|
439
|
+
};
|
|
440
|
+
}
|
|
441
|
+
async function executeTranslationBatch(requests, globalMetadata, config) {
|
|
442
|
+
const isArray = Array.isArray(requests);
|
|
443
|
+
const hashOrder = isArray ? [] : void 0;
|
|
444
|
+
const requestsObject = {};
|
|
445
|
+
const entries = isArray ? requests.map((r) => [void 0, r]) : Object.entries(requests);
|
|
446
|
+
for (const [key, request] of entries) {
|
|
447
|
+
const { source, metadata } = typeof request === "string" ? { source: request } : request;
|
|
448
|
+
const hash = key ?? metadata?.hash ?? hashSource({
|
|
449
|
+
source,
|
|
450
|
+
...metadata?.context && { context: metadata.context },
|
|
451
|
+
...metadata?.maxChars != null && { maxChars: metadata.maxChars },
|
|
452
|
+
...metadata?.fileFormat && { fileFormat: metadata.fileFormat },
|
|
453
|
+
dataFormat: metadata?.dataFormat ?? "STRING"
|
|
454
|
+
});
|
|
455
|
+
hashOrder?.push(hash);
|
|
456
|
+
requestsObject[hash] = {
|
|
457
|
+
source,
|
|
458
|
+
metadata
|
|
459
|
+
};
|
|
460
|
+
}
|
|
461
|
+
if (globalMetadata.modelProvider !== void 0 && !isModelProvider(globalMetadata.modelProvider)) throw new Error(createDiagnosticMessage({
|
|
462
|
+
source: "generaltranslation",
|
|
463
|
+
severity: "Error",
|
|
464
|
+
whatHappened: "The configured model provider is not supported",
|
|
465
|
+
details: String(globalMetadata.modelProvider),
|
|
466
|
+
fix: `Use one of: ${supportedModelProviders.join(", ")}`
|
|
467
|
+
}));
|
|
468
|
+
const client = createApiClient({
|
|
469
|
+
apiKey: config.apiKey,
|
|
470
|
+
apiVersion: config.apiVersion,
|
|
471
|
+
userTokenProvider: config.userTokenProvider,
|
|
472
|
+
baseUrl: config.baseUrl || "https://api.gtx.dev",
|
|
473
|
+
fetch: (input, init) => fetchWithTimeout(input, init ?? {}, config.timeoutMs, config.fetch),
|
|
474
|
+
projectId: config.projectId,
|
|
475
|
+
retryPolicy: "none",
|
|
476
|
+
timeoutMs: false
|
|
477
|
+
});
|
|
478
|
+
const result = await translate({
|
|
479
|
+
body: {
|
|
480
|
+
requests: requestsObject,
|
|
481
|
+
targetLocale: globalMetadata.targetLocale,
|
|
482
|
+
sourceLocale: globalMetadata.sourceLocale,
|
|
483
|
+
metadata: {
|
|
484
|
+
...globalMetadata,
|
|
485
|
+
modelProvider: globalMetadata.modelProvider
|
|
486
|
+
}
|
|
487
|
+
},
|
|
488
|
+
client
|
|
489
|
+
});
|
|
490
|
+
if (result.data === void 0 && result.response && !hasDecodedError(result)) {
|
|
491
|
+
await validateResponse(result.response);
|
|
492
|
+
throw result.error;
|
|
493
|
+
}
|
|
494
|
+
const runtimeResponse = unwrapApiResult(result);
|
|
495
|
+
const response = Object.fromEntries(Object.entries(runtimeResponse).map(([hash, translationResult]) => [hash, toTranslationResult(translationResult)]));
|
|
496
|
+
if (hashOrder) return hashOrder.map((hash) => response[hash] ?? {
|
|
497
|
+
success: false,
|
|
498
|
+
error: "No translation returned",
|
|
499
|
+
code: 500
|
|
500
|
+
});
|
|
501
|
+
return response;
|
|
502
|
+
}
|
|
503
|
+
//#endregion
|
|
504
|
+
export { unwrapApiResult as a, gtInstanceLogger as c, noSourceLocaleProvidedError as d, noTargetLocaleProvidedError as f, libraryDefaultLocale as g, defaultRuntimeApiUrl as h, isErrorResult as i, invalidLocaleError as l, defaultCacheUrl as m, translateMany as n, isModelProvider as o, defaultBaseUrl as p, validateAuth as r, supportedModelProviders as s, translate$1 as t, invalidLocalesError as u };
|
|
505
|
+
|
|
506
|
+
//# sourceMappingURL=runtimeTranslate-CVw143pQ.mjs.map
|