@weglot/translate-react 0.1.0 → 0.2.1

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.
Files changed (50) hide show
  1. package/README.md +71 -18
  2. package/build/plugin/build-translator.cjs +6 -2
  3. package/build/plugin/build-translator.mjs +6 -2
  4. package/build/plugin/build-translator.mjs.map +1 -1
  5. package/build/plugin/next.cjs +1 -0
  6. package/build/plugin/next.d.cts.map +1 -1
  7. package/build/plugin/next.d.mts.map +1 -1
  8. package/build/plugin/next.mjs +1 -0
  9. package/build/plugin/next.mjs.map +1 -1
  10. package/build/plugin/vite.cjs +1 -1
  11. package/build/plugin/vite.mjs +1 -1
  12. package/build/plugin/vite.mjs.map +1 -1
  13. package/build/plugin/webpack.cjs +1 -1
  14. package/build/plugin/webpack.mjs +1 -1
  15. package/build/plugin/webpack.mjs.map +1 -1
  16. package/build/runtime/translate-dynamic.cjs +6 -4
  17. package/build/runtime/translate-dynamic.d.cts.map +1 -1
  18. package/build/runtime/translate-dynamic.d.mts.map +1 -1
  19. package/build/runtime/translate-dynamic.mjs +7 -5
  20. package/build/runtime/translate-dynamic.mjs.map +1 -1
  21. package/build/translators/translation-service.cjs +7 -4
  22. package/build/translators/translation-service.mjs +7 -4
  23. package/build/translators/translation-service.mjs.map +1 -1
  24. package/build/translators/weglot/api-client.cjs +103 -23
  25. package/build/translators/weglot/api-client.mjs +103 -24
  26. package/build/translators/weglot/api-client.mjs.map +1 -1
  27. package/build/translators/weglot/engine.cjs +2 -5
  28. package/build/translators/weglot/engine.mjs +2 -5
  29. package/build/translators/weglot/engine.mjs.map +1 -1
  30. package/build/translators/weglot/translator.cjs +48 -24
  31. package/build/translators/weglot/translator.mjs +48 -24
  32. package/build/translators/weglot/translator.mjs.map +1 -1
  33. package/build/types.d.cts +13 -3
  34. package/build/types.d.cts.map +1 -1
  35. package/build/types.d.mts +13 -3
  36. package/build/types.d.mts.map +1 -1
  37. package/build/utils/config-factory.cjs +18 -4
  38. package/build/utils/config-factory.mjs +19 -5
  39. package/build/utils/config-factory.mjs.map +1 -1
  40. package/build/virtual/code-generator.cjs +2 -0
  41. package/build/virtual/code-generator.mjs +2 -0
  42. package/build/virtual/code-generator.mjs.map +1 -1
  43. package/build/virtual/config.cjs +3 -0
  44. package/build/virtual/config.d.cts +3 -1
  45. package/build/virtual/config.d.cts.map +1 -1
  46. package/build/virtual/config.d.mts +3 -1
  47. package/build/virtual/config.d.mts.map +1 -1
  48. package/build/virtual/config.mjs +3 -1
  49. package/build/virtual/config.mjs.map +1 -1
  50. package/package.json +1 -1
@@ -14,7 +14,9 @@ var TranslationService = class {
14
14
  apiKey: config.apiKey,
15
15
  sourceLocale: config.sourceLocale,
16
16
  apiLocales: config.apiLocales,
17
- translationEngine: config.translationEngine
17
+ translationEngine: config.translationEngine,
18
+ apiBaseUrl: config.apiBaseUrl,
19
+ translationTimeoutMs: config.translationTimeout * 1e3
18
20
  }, this.logger);
19
21
  }
20
22
  /**
@@ -30,7 +32,7 @@ var TranslationService = class {
30
32
  const workingHashes = requestedHashes || Object.keys(metadata);
31
33
  this.logger.debug(`Translation requested for ${workingHashes.length} hashes in locale: ${locale}`);
32
34
  const cachedTranslations = await this.cache.get(locale);
33
- const uncachedHashes = workingHashes.filter((hash) => !cachedTranslations[hash]);
35
+ const uncachedHashes = workingHashes.filter((hash) => !cachedTranslations[hash] || locale !== this.config.sourceLocale && cachedTranslations[hash] === metadata[hash]?.sourceText);
34
36
  this.logger.debug(`${uncachedHashes.length} hashes need processing, ${workingHashes.length - uncachedHashes.length} are cached`);
35
37
  const cachedCount = workingHashes.length - uncachedHashes.length;
36
38
  if (uncachedHashes.length === 0) return {
@@ -82,7 +84,7 @@ var TranslationService = class {
82
84
  errors.push({
83
85
  hash,
84
86
  sourceText: entry?.sourceText || "",
85
- error: "Translator doesn't return translation"
87
+ error: "No translation returned yet; Weglot may still be generating it"
86
88
  });
87
89
  }
88
90
  }
@@ -105,7 +107,8 @@ var TranslationService = class {
105
107
  total: workingHashes.length,
106
108
  cached: cachedCount,
107
109
  translated: Object.keys(newTranslations).length,
108
- failed: errors.length
110
+ failed: errors.length,
111
+ untranslated: locale === this.config.sourceLocale ? 0 : Object.entries(newTranslations).filter(([hash, text]) => text === filteredMetadata[hash]?.sourceText).length
109
112
  }
110
113
  };
111
114
  }
@@ -1 +1 @@
1
- {"version":3,"file":"translation-service.mjs","names":["config: TranslationServiceConfig","logger: Logger","filteredMetadata: MetadataSchema","newTranslations: Record<string, string>","errors: TranslationError[]","entries: Record<string, TranslatableEntry>","result: Record<string, string>"],"sources":["../../src/translators/translation-service.ts"],"sourcesContent":["/**\n * TranslationService - Main orchestrator for translation workflow\n *\n * Responsibilities:\n * - Coordinates between metadata, cache, and translator\n * - Determines what needs translation\n * - Handles caching strategy\n * - Manages partial failures\n */\n\nimport type { TranslationCache } from \"./cache\";\nimport type { TranslatableEntry, Translator } from \"./api\";\nimport type { WeglotEnvironment, MetadataSchema } from \"../types\";\nimport type { Logger } from \"../utils/logger\";\nimport type { LocaleCode } from \"../locale\";\nimport { UnsupportedLanguagePairError, WeglotTranslator } from \"./weglot\";\nimport { type CacheConfig, createCache } from \"./cache-factory\";\n\nexport type TranslationServiceConfig = {\n /**\n * Weglot project API key\n */\n apiKey: string;\n\n /**\n * Source locale (e.g., \"en\")\n */\n sourceLocale: LocaleCode;\n\n /** Public locale to the language code the translate API expects. */\n apiLocales?: Record<string, LocaleCode>;\n\n /** From the project settings; derived from the key length when absent. */\n translationEngine?: number;\n\n environment: WeglotEnvironment;\n} & CacheConfig;\n\nexport interface TranslationResult {\n /**\n * Successfully translated entries (hash -> translated text)\n */\n translations: Record<string, string>;\n\n errors: TranslationError[];\n\n /** The API refuses this target, so callers report it and move on. */\n unsupportedLocale?: boolean;\n\n stats: {\n total: number;\n cached: number;\n translated: number;\n failed: number;\n };\n}\n\nexport interface TranslationError {\n hash: string;\n sourceText: string;\n error: string;\n}\n\nexport class TranslationService {\n private translator: Translator<any>;\n private cache: TranslationCache;\n\n constructor(\n private config: TranslationServiceConfig,\n private logger: Logger,\n ) {\n this.cache = createCache(config);\n this.translator = new WeglotTranslator(\n {\n apiKey: config.apiKey,\n sourceLocale: config.sourceLocale,\n apiLocales: config.apiLocales,\n translationEngine: config.translationEngine,\n },\n this.logger,\n );\n }\n\n /**\n * Translate entries to target locale\n *\n * @param locale Target locale (including source locale)\n * @param metadata Metadata schema with all entries\n * @param requestedHashes Optional: only translate specific hashes\n * @returns Translation result with translations and errors\n */\n async translate(\n locale: LocaleCode,\n metadata: MetadataSchema,\n requestedHashes?: string[],\n ): Promise<TranslationResult> {\n const startTime = performance.now();\n\n // Step 1: Determine which hashes we need to work with\n const workingHashes = requestedHashes || Object.keys(metadata);\n\n this.logger.debug(\n `Translation requested for ${workingHashes.length} hashes in locale: ${locale}`,\n );\n\n // Step 2: Check cache first (same for all locales, including source)\n const cachedTranslations = await this.cache.get(locale);\n\n // Step 3: Determine what needs translation\n const uncachedHashes = workingHashes.filter(\n (hash) => !cachedTranslations[hash],\n );\n this.logger.debug(\n `${uncachedHashes.length} hashes need processing, ${workingHashes.length - uncachedHashes.length} are cached`,\n );\n\n const cachedCount = workingHashes.length - uncachedHashes.length;\n\n if (uncachedHashes.length === 0) {\n return {\n translations: this.pickTranslations(cachedTranslations, workingHashes),\n errors: [],\n stats: {\n total: workingHashes.length,\n cached: cachedCount,\n translated: 0,\n failed: 0,\n },\n };\n }\n\n this.logger.debug(\n `Generating translations for ${uncachedHashes.length} uncached hashes in ${locale}...`,\n );\n\n // Step 4: Filter metadata to only uncached entries\n const filteredMetadata: MetadataSchema = Object.fromEntries(\n uncachedHashes\n .map((hash) => [hash, metadata[hash]])\n .filter(([_, entry]) => entry !== undefined),\n );\n\n // Step 5: Prepare entries for translation\n const entriesToTranslate = this.prepareEntries(\n filteredMetadata,\n uncachedHashes,\n );\n\n // Step 6: Translate or return source text\n let newTranslations: Record<string, string> = {};\n const errors: TranslationError[] = [];\n\n if (locale === this.config.sourceLocale) {\n // For source locale, just return the sourceText\n this.logger.debug(\n `Source locale detected, returning sourceText for ${uncachedHashes.length} entries`,\n );\n for (const [hash, entry] of Object.entries(entriesToTranslate)) {\n newTranslations[hash] = entry.text;\n }\n } else if (Object.keys(entriesToTranslate).length > 0) {\n // For other locales, translate entries\n try {\n this.logger.debug(\n `Translating ${locale} with ${Object.keys(entriesToTranslate).length} entries`,\n );\n const translatedTexts = await this.translator.translate(\n locale,\n entriesToTranslate,\n );\n newTranslations = { ...translatedTexts };\n } catch (error) {\n const errorMessage =\n error instanceof Error ? error.message : String(error);\n const unsupportedLocale = error instanceof UnsupportedLanguagePairError;\n if (unsupportedLocale) {\n this.logger.warn(\n `Locale \"${locale}\" cannot be translated: ${errorMessage}`,\n );\n } else {\n this.logger.error(\n `Translation failed for locale \"${locale}\": ${errorMessage}`,\n );\n }\n if (error instanceof Error && error.stack) {\n this.logger.debug(`Stack trace: ${error.stack}`);\n }\n\n return {\n unsupportedLocale,\n translations: this.pickTranslations(\n cachedTranslations,\n workingHashes,\n ),\n errors: [\n {\n hash: \"all\",\n sourceText: \"all\",\n error: errorMessage,\n },\n ],\n stats: {\n total: workingHashes.length,\n cached: cachedCount,\n translated: 0,\n failed: uncachedHashes.length,\n },\n };\n }\n\n // Check for partial failures (some hashes didn't get translated)\n for (const hash of uncachedHashes) {\n if (!newTranslations[hash]) {\n const entry = filteredMetadata[hash];\n errors.push({\n hash,\n sourceText: entry?.sourceText || \"\",\n error: \"Translator doesn't return translation\",\n });\n }\n }\n }\n\n // Step 7: Update cache with successful translations\n if (Object.keys(newTranslations).length > 0) {\n try {\n await this.cache.update(locale, newTranslations);\n } catch (error) {\n this.logger.error(`Failed to update cache:`, error);\n // Don't fail the request if cache update fails\n }\n }\n\n // Step 8: Merge and return\n const allTranslations = { ...cachedTranslations, ...newTranslations };\n const result = this.pickTranslations(allTranslations, workingHashes);\n\n const endTime = performance.now();\n this.logger.debug(\n `Translation completed for ${locale}: ${Object.keys(newTranslations).length} new, ${cachedCount} cached, ${errors.length} errors in ${(endTime - startTime).toFixed(2)}ms`,\n );\n\n return {\n translations: result,\n errors,\n stats: {\n total: workingHashes.length,\n cached: cachedCount,\n translated: Object.keys(newTranslations).length,\n failed: errors.length,\n },\n };\n }\n\n /**\n * Prepare metadata entries for translation\n */\n private prepareEntries(\n metadata: MetadataSchema,\n hashes: string[],\n ): Record<string, TranslatableEntry> {\n const entries: Record<string, TranslatableEntry> = {};\n\n for (const hash of hashes) {\n const entry = metadata[hash];\n if (entry) {\n entries[hash] = {\n text: entry.sourceText,\n context: entry.context || {},\n };\n }\n }\n\n return entries;\n }\n\n /**\n * Pick only requested translations from the full set\n */\n // TODO (AleksandrSl 14/12/2025): SHould I use this in the build somehow?\n private pickTranslations(\n allTranslations: Record<string, string>,\n requestedHashes: string[],\n ): Record<string, string> {\n const result: Record<string, string> = {};\n\n for (const hash of requestedHashes) {\n if (allTranslations[hash]) {\n result[hash] = allTranslations[hash];\n }\n }\n\n return result;\n }\n}\n"],"mappings":";;;;;AA+DA,IAAa,qBAAb,MAAgC;CAC9B,AAAQ;CACR,AAAQ;CAER,YACE,AAAQA,QACR,AAAQC,QACR;EAFQ;EACA;AAER,OAAK,QAAQ,YAAY,OAAO;AAChC,OAAK,aAAa,IAAI,iBACpB;GACE,QAAQ,OAAO;GACf,cAAc,OAAO;GACrB,YAAY,OAAO;GACnB,mBAAmB,OAAO;GAC3B,EACD,KAAK,OACN;;;;;;;;;;CAWH,MAAM,UACJ,QACA,UACA,iBAC4B;EAC5B,MAAM,YAAY,YAAY,KAAK;EAGnC,MAAM,gBAAgB,mBAAmB,OAAO,KAAK,SAAS;AAE9D,OAAK,OAAO,MACV,6BAA6B,cAAc,OAAO,qBAAqB,SACxE;EAGD,MAAM,qBAAqB,MAAM,KAAK,MAAM,IAAI,OAAO;EAGvD,MAAM,iBAAiB,cAAc,QAClC,SAAS,CAAC,mBAAmB,MAC/B;AACD,OAAK,OAAO,MACV,GAAG,eAAe,O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,MAClB,QAAO,QAAQ,gBAAgB;AAInC,SAAO"}
1
+ {"version":3,"file":"translation-service.mjs","names":["config: TranslationServiceConfig","logger: Logger","filteredMetadata: MetadataSchema","newTranslations: Record<string, string>","errors: TranslationError[]","entries: Record<string, TranslatableEntry>","result: Record<string, string>"],"sources":["../../src/translators/translation-service.ts"],"sourcesContent":["/**\n * TranslationService - Main orchestrator for translation workflow\n *\n * Responsibilities:\n * - Coordinates between metadata, cache, and translator\n * - Determines what needs translation\n * - Handles caching strategy\n * - Manages partial failures\n */\n\nimport type { TranslationCache } from \"./cache\";\nimport type { TranslatableEntry, Translator } from \"./api\";\nimport type { WeglotEnvironment, MetadataSchema } from \"../types\";\nimport type { Logger } from \"../utils/logger\";\nimport type { LocaleCode } from \"../locale\";\nimport { UnsupportedLanguagePairError, WeglotTranslator } from \"./weglot\";\nimport { type CacheConfig, createCache } from \"./cache-factory\";\n\nexport type TranslationServiceConfig = {\n /**\n * Weglot project API key\n */\n apiKey: string;\n\n /**\n * Source locale (e.g., \"en\")\n */\n sourceLocale: LocaleCode;\n\n /** Public locale to the language code the translate API expects. */\n apiLocales?: Record<string, LocaleCode>;\n\n /** From the project settings; the modern engine when absent. */\n translationEngine?: number;\n\n /** The project's regional API host, from the project settings. */\n apiBaseUrl?: string;\n\n /** Seconds to wait for translations Weglot is still generating. */\n translationTimeout: number;\n\n environment: WeglotEnvironment;\n} & CacheConfig;\n\nexport interface TranslationResult {\n /**\n * Successfully translated entries (hash -> translated text)\n */\n translations: Record<string, string>;\n\n errors: TranslationError[];\n\n /** The API refuses this target, so callers report it and move on. */\n unsupportedLocale?: boolean;\n\n stats: {\n total: number;\n cached: number;\n translated: number;\n failed: number;\n /** New entries kept as their source text: refused by Weglot or identical. */\n untranslated?: number;\n };\n}\n\nexport interface TranslationError {\n hash: string;\n sourceText: string;\n error: string;\n}\n\nexport class TranslationService {\n private translator: Translator<any>;\n private cache: TranslationCache;\n\n constructor(\n private config: TranslationServiceConfig,\n private logger: Logger,\n ) {\n this.cache = createCache(config);\n this.translator = new WeglotTranslator(\n {\n apiKey: config.apiKey,\n sourceLocale: config.sourceLocale,\n apiLocales: config.apiLocales,\n translationEngine: config.translationEngine,\n apiBaseUrl: config.apiBaseUrl,\n translationTimeoutMs: config.translationTimeout * 1000,\n },\n this.logger,\n );\n }\n\n /**\n * Translate entries to target locale\n *\n * @param locale Target locale (including source locale)\n * @param metadata Metadata schema with all entries\n * @param requestedHashes Optional: only translate specific hashes\n * @returns Translation result with translations and errors\n */\n async translate(\n locale: LocaleCode,\n metadata: MetadataSchema,\n requestedHashes?: string[],\n ): Promise<TranslationResult> {\n const startTime = performance.now();\n\n // Step 1: Determine which hashes we need to work with\n const workingHashes = requestedHashes || Object.keys(metadata);\n\n this.logger.debug(\n `Translation requested for ${workingHashes.length} hashes in locale: ${locale}`,\n );\n\n // Step 2: Check cache first (same for all locales, including source)\n const cachedTranslations = await this.cache.get(locale);\n\n // Step 3: Determine what needs translation. A cached source text is asked\n // again, as it may stand for a word Weglot had not taken in yet.\n const uncachedHashes = workingHashes.filter(\n (hash) =>\n !cachedTranslations[hash] ||\n (locale !== this.config.sourceLocale &&\n cachedTranslations[hash] === metadata[hash]?.sourceText),\n );\n this.logger.debug(\n `${uncachedHashes.length} hashes need processing, ${workingHashes.length - uncachedHashes.length} are cached`,\n );\n\n const cachedCount = workingHashes.length - uncachedHashes.length;\n\n if (uncachedHashes.length === 0) {\n return {\n translations: this.pickTranslations(cachedTranslations, workingHashes),\n errors: [],\n stats: {\n total: workingHashes.length,\n cached: cachedCount,\n translated: 0,\n failed: 0,\n },\n };\n }\n\n this.logger.debug(\n `Generating translations for ${uncachedHashes.length} uncached hashes in ${locale}...`,\n );\n\n // Step 4: Filter metadata to only uncached entries\n const filteredMetadata: MetadataSchema = Object.fromEntries(\n uncachedHashes\n .map((hash) => [hash, metadata[hash]])\n .filter(([_, entry]) => entry !== undefined),\n );\n\n // Step 5: Prepare entries for translation\n const entriesToTranslate = this.prepareEntries(\n filteredMetadata,\n uncachedHashes,\n );\n\n // Step 6: Translate or return source text\n let newTranslations: Record<string, string> = {};\n const errors: TranslationError[] = [];\n\n if (locale === this.config.sourceLocale) {\n // For source locale, just return the sourceText\n this.logger.debug(\n `Source locale detected, returning sourceText for ${uncachedHashes.length} entries`,\n );\n for (const [hash, entry] of Object.entries(entriesToTranslate)) {\n newTranslations[hash] = entry.text;\n }\n } else if (Object.keys(entriesToTranslate).length > 0) {\n // For other locales, translate entries\n try {\n this.logger.debug(\n `Translating ${locale} with ${Object.keys(entriesToTranslate).length} entries`,\n );\n const translatedTexts = await this.translator.translate(\n locale,\n entriesToTranslate,\n );\n newTranslations = { ...translatedTexts };\n } catch (error) {\n const errorMessage =\n error instanceof Error ? error.message : String(error);\n const unsupportedLocale = error instanceof UnsupportedLanguagePairError;\n if (unsupportedLocale) {\n this.logger.warn(\n `Locale \"${locale}\" cannot be translated: ${errorMessage}`,\n );\n } else {\n this.logger.error(\n `Translation failed for locale \"${locale}\": ${errorMessage}`,\n );\n }\n if (error instanceof Error && error.stack) {\n this.logger.debug(`Stack trace: ${error.stack}`);\n }\n\n return {\n unsupportedLocale,\n translations: this.pickTranslations(\n cachedTranslations,\n workingHashes,\n ),\n errors: [\n {\n hash: \"all\",\n sourceText: \"all\",\n error: errorMessage,\n },\n ],\n stats: {\n total: workingHashes.length,\n cached: cachedCount,\n translated: 0,\n failed: uncachedHashes.length,\n },\n };\n }\n\n // Check for partial failures (some hashes didn't get translated)\n for (const hash of uncachedHashes) {\n if (!newTranslations[hash]) {\n const entry = filteredMetadata[hash];\n errors.push({\n hash,\n sourceText: entry?.sourceText || \"\",\n error: \"No translation returned yet; Weglot may still be generating it\",\n });\n }\n }\n }\n\n // Step 7: Update cache with successful translations\n if (Object.keys(newTranslations).length > 0) {\n try {\n await this.cache.update(locale, newTranslations);\n } catch (error) {\n this.logger.error(`Failed to update cache:`, error);\n // Don't fail the request if cache update fails\n }\n }\n\n // Step 8: Merge and return\n const allTranslations = { ...cachedTranslations, ...newTranslations };\n const result = this.pickTranslations(allTranslations, workingHashes);\n\n const endTime = performance.now();\n this.logger.debug(\n `Translation completed for ${locale}: ${Object.keys(newTranslations).length} new, ${cachedCount} cached, ${errors.length} errors in ${(endTime - startTime).toFixed(2)}ms`,\n );\n\n return {\n translations: result,\n errors,\n stats: {\n total: workingHashes.length,\n cached: cachedCount,\n translated: Object.keys(newTranslations).length,\n failed: errors.length,\n untranslated:\n locale === this.config.sourceLocale\n ? 0\n : Object.entries(newTranslations).filter(\n ([hash, text]) => text === filteredMetadata[hash]?.sourceText,\n ).length,\n },\n };\n }\n\n /**\n * Prepare metadata entries for translation\n */\n private prepareEntries(\n metadata: MetadataSchema,\n hashes: string[],\n ): Record<string, TranslatableEntry> {\n const entries: Record<string, TranslatableEntry> = {};\n\n for (const hash of hashes) {\n const entry = metadata[hash];\n if (entry) {\n entries[hash] = {\n text: entry.sourceText,\n context: entry.context || {},\n };\n }\n }\n\n return entries;\n }\n\n /**\n * Pick only requested translations from the full set\n */\n // TODO (AleksandrSl 14/12/2025): SHould I use this in the build somehow?\n private pickTranslations(\n allTranslations: Record<string, string>,\n requestedHashes: string[],\n ): Record<string, string> {\n const result: Record<string, string> = {};\n\n for (const hash of requestedHashes) {\n if (allTranslations[hash]) {\n result[hash] = allTranslations[hash];\n }\n }\n\n return result;\n }\n}\n"],"mappings":";;;;;AAuEA,IAAa,qBAAb,MAAgC;CAC9B,AAAQ;CACR,AAAQ;CAER,YACE,AAAQA,QACR,AAAQC,QACR;EAFQ;EACA;AAER,OAAK,QAAQ,YAAY,OAAO;AAChC,OAAK,aAAa,IAAI,iBACpB;GACE,QAAQ,OAAO;GACf,cAAc,OAAO;GACrB,YAAY,OAAO;GACnB,mBAAmB,OAAO;GAC1B,YAAY,OAAO;GACnB,sBAAsB,OAAO,qBAAqB;GACnD,EACD,KAAK,OACN;;;;;;;;;;CAWH,MAAM,UACJ,QACA,UACA,iBAC4B;EAC5B,MAAM,YAAY,YAAY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OAAO,eACnB,IACA,OAAO,QAAQ,gBAAgB,CAAC,QAC7B,CAAC,MAAM,UAAU,SAAS,iBAAiB,OAAO,WACpD,CAAC;IACT;GACF;;;;;CAMH,AAAQ,eACN,UACA,QACmC;EACnC,MAAMC,UAA6C,EAAE;AAErD,OAAK,MAAM,QAAQ,QAAQ;GACzB,MAAM,QAAQ,SAAS;AACvB,OAAI,MACF,SAAQ,QAAQ;IACd,MAAM,MAAM;IACZ,SAAS,MAAM,WAAW,EAAE;IAC7B;;AAIL,SAAO;;;;;CAOT,AAAQ,iBACN,iBACA,iBACwB;EACxB,MAAMC,SAAiC,EAAE;AAEzC,OAAK,MAAM,QAAQ,gBACjB,KAAI,gBAAgB,MAClB,QAAO,QAAQ,gBAAgB;AAInC,SAAO"}
@@ -3,25 +3,18 @@ const require_definitions_generated = require('./definitions/definitions.generat
3
3
 
4
4
  //#region src/translators/weglot/api-client.ts
5
5
  /**
6
- * Thin HTTP client for the Weglot public API.
7
- *
8
- * - Translation: POST https://api.weglot.com/translate?api_key=<key>
9
- * - Project settings: cdn.weglot.com/projects-settings/<id>.json for v1 keys,
10
- * api.weglot.com/project-settings otherwise (weglot-js getCdnSettings.ts).
11
- *
12
- * Translations made through the API are recorded in the Weglot project and
13
- * can be reviewed/edited in the Weglot dashboard.
6
+ * Weglot API client. Weglot translates with an LLM: a word not translated yet
7
+ * comes back null and is queued, so callers poll until it is ready.
14
8
  */
15
- const TRANSLATE_URL = "https://api.weglot.com/translate";
16
- const CDN_SETTINGS_URL = "https://cdn.weglot.com/projects-settings";
17
- const API_SETTINGS_URL = "https://api.weglot.com/project-settings";
18
- const V1_KEY_PREFIX = "wg_";
9
+ const DEFAULT_SETTINGS_URL = "https://api.weglot.com/project-settings";
10
+ const DEFAULT_API_BASE_URL = "https://api.weglot.com";
11
+ const SUPPORTED_PRODUCT = "2.0";
19
12
  const WORD_TYPE_TEXT = require_definitions_generated.WORD_TYPE.TEXT;
20
13
  const REQUEST_URL = "https://compiler.weglot.com/";
21
- function settingsUrlFor(apiKey) {
22
- if (apiKey.startsWith(V1_KEY_PREFIX)) return `${CDN_SETTINGS_URL}/${apiKey.slice(3)}.json`;
23
- return `${API_SETTINGS_URL}?api_key=${apiKey}`;
24
- }
14
+ const WORD_LABEL = "translate-react";
15
+ const MAX_WORDS_PER_REQUEST = 100;
16
+ const DEFAULT_POLL_INTERVAL_MS = 5e3;
17
+ const REFUSED_AFTER_MISSES = 2;
25
18
  /** The API validates the pair independently of the project's languages, so
26
19
  * `en`→`sr-latn` can be refused. Callers skip the locale rather than failing. */
27
20
  var UnsupportedLanguagePairError = class extends Error {
@@ -32,42 +25,128 @@ var UnsupportedLanguagePairError = class extends Error {
32
25
  this.name = "UnsupportedLanguagePairError";
33
26
  }
34
27
  };
28
+ /** A 400 the API gives a whole request when one of its words is unreadable. */
29
+ var RefusedRequestError = class extends Error {};
30
+ const wellFormed = (text) => text.replace(/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g, "�");
31
+ const defaultSleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
35
32
  var WeglotApiClient = class {
36
- constructor(apiKey) {
33
+ apiBaseUrl;
34
+ constructor(apiKey, apiBaseUrl) {
37
35
  this.apiKey = apiKey;
36
+ this.apiBaseUrl = apiBaseUrl || DEFAULT_API_BASE_URL;
38
37
  }
38
+ /** One request. A word not translated yet comes back null, with an id once the API has queued it. */
39
39
  async translate(params) {
40
- const response = await fetch(`${TRANSLATE_URL}?api_key=${this.apiKey}`, {
40
+ const query = params.live ? "?live=1" : "";
41
+ const response = await fetch(`${this.apiBaseUrl}/translate${query}`, {
41
42
  method: "POST",
42
- headers: { "Content-Type": "application/json" },
43
+ headers: {
44
+ "Content-Type": "application/json",
45
+ Accept: "application/json",
46
+ Authorization: `Key ${this.apiKey}`
47
+ },
43
48
  body: JSON.stringify({
44
49
  l_from: params.from,
45
50
  l_to: params.to,
46
51
  request_url: REQUEST_URL,
47
52
  words: params.words.map((w, index) => ({
48
53
  t: params.types?.[index] ?? WORD_TYPE_TEXT,
49
- w
54
+ w: wellFormed(w),
55
+ l: [WORD_LABEL]
50
56
  }))
51
57
  })
52
58
  });
53
59
  if (!response.ok) {
54
60
  const body = await response.text().catch(() => "");
55
61
  if (response.status === 400 && /not valid languages pair/i.test(body)) throw new UnsupportedLanguagePairError(params.from, params.to);
62
+ if (response.status === 400) throw new RefusedRequestError(`Weglot translate API refused the request (400): ${body || "no response body"}`);
56
63
  throw new Error(`Weglot translate API error (${response.status}): ${body || "no response body"}`);
57
64
  }
58
- const toWords = (await response.json()).to_words;
65
+ const data = await response.json();
66
+ const toWords = data.to_words;
59
67
  if (!Array.isArray(toWords) || toWords.length !== params.words.length) throw new Error(`Weglot translate API returned a mismatched word count (sent ${params.words.length}, received ${Array.isArray(toWords) ? toWords.length : "none"})`);
60
- return toWords;
68
+ const ids = Array.isArray(data.ids) ? data.ids : null;
69
+ return {
70
+ words: toWords,
71
+ accepted: toWords.map((value, index) => value !== null || ids === null || (ids[index] ?? null) !== null)
72
+ };
73
+ }
74
+ /** Re-polls words until translated or the deadline. A failed request leaves
75
+ * its words pending, so one error never discards what was already received. */
76
+ async translateUntilReady(params, { deadline, pollIntervalMs = DEFAULT_POLL_INTERVAL_MS, sleep = defaultSleep }) {
77
+ const words = new Array(params.words.length).fill(null);
78
+ const everAccepted = new Array(params.words.length).fill(false);
79
+ const misses = new Array(params.words.length).fill(0);
80
+ const refused = /* @__PURE__ */ new Set();
81
+ let pending = params.words.map((_, index) => index);
82
+ let received = false;
83
+ let anyAccepted = false;
84
+ let lastError;
85
+ while (true) {
86
+ for (let i = 0; i < pending.length; i += MAX_WORDS_PER_REQUEST) try {
87
+ const answers = await this.sendIsolatingRefused(params, pending.slice(i, i + MAX_WORDS_PER_REQUEST), refused);
88
+ received = true;
89
+ for (const { index, word, accepted } of answers) {
90
+ words[index] = word;
91
+ if (accepted) {
92
+ everAccepted[index] = true;
93
+ anyAccepted = true;
94
+ } else misses[index]++;
95
+ }
96
+ } catch (error) {
97
+ if (error instanceof UnsupportedLanguagePairError) throw error;
98
+ lastError = error;
99
+ }
100
+ if (anyAccepted) {
101
+ for (const index of pending) if (!everAccepted[index] && misses[index] >= REFUSED_AFTER_MISSES) refused.add(index);
102
+ }
103
+ pending = pending.filter((index) => words[index] === null && !refused.has(index));
104
+ const remaining = deadline - Date.now();
105
+ if (pending.length === 0 || remaining <= 0) {
106
+ if (!received && lastError !== void 0) throw lastError;
107
+ return {
108
+ words,
109
+ refused: [...refused].sort((a, b) => a - b)
110
+ };
111
+ }
112
+ await sleep(Math.min(pollIntervalMs, remaining));
113
+ }
114
+ }
115
+ /** Splits a request the API refuses until the unreadable word is alone, then marks it refused. */
116
+ async sendIsolatingRefused(params, indexes, refused) {
117
+ try {
118
+ const { words, accepted } = await require_timeout.withTimeout(this.translate({
119
+ from: params.from,
120
+ to: params.to,
121
+ words: indexes.map((index) => params.words[index]),
122
+ types: params.types && indexes.map((index) => params.types[index])
123
+ }), require_timeout.DEFAULT_TIMEOUTS.AI_API, `Weglot API translation to ${params.to}`);
124
+ return indexes.map((index, k) => ({
125
+ index,
126
+ word: words[k],
127
+ accepted: accepted[k]
128
+ }));
129
+ } catch (error) {
130
+ if (!(error instanceof RefusedRequestError)) throw error;
131
+ if (indexes.length === 1) {
132
+ refused.add(indexes[0]);
133
+ return [];
134
+ }
135
+ const middle = Math.ceil(indexes.length / 2);
136
+ return [...await this.sendIsolatingRefused(params, indexes.slice(0, middle), refused), ...await this.sendIsolatingRefused(params, indexes.slice(middle), refused)];
137
+ }
61
138
  }
62
139
  async fetchSettings() {
63
- const response = await require_timeout.withTimeout(fetch(settingsUrlFor(this.apiKey)), require_timeout.DEFAULT_TIMEOUTS.AI_API, "Weglot project settings fetch");
140
+ const response = await require_timeout.withTimeout(fetch(`${process.env.WEGLOT_SETTINGS_URL || DEFAULT_SETTINGS_URL}?api_key=${encodeURIComponent(this.apiKey)}`, { headers: { Accept: "application/json" } }), require_timeout.DEFAULT_TIMEOUTS.AI_API, "Weglot project settings fetch");
64
141
  if (!response.ok) throw new Error(`Failed to fetch Weglot project settings (${response.status}). Check that your Weglot project key is valid.`);
65
142
  const data = await response.json();
143
+ if (data.product !== SUPPORTED_PRODUCT) throw new Error("@weglot/translate-react does not support the Weglot project this key belongs to. Check that you are using the right project key.");
66
144
  if (!data.language_from || !Array.isArray(data.languages)) throw new Error("Unexpected Weglot project settings format: missing language_from or languages.");
67
145
  const languages = data.languages.filter((lang) => lang.enabled !== false);
68
146
  return {
69
147
  sourceLocale: data.language_from,
70
148
  targetLocales: languages.map((lang) => lang.custom_code || lang.language_to),
149
+ apiBaseUrl: (data.api_base_url || DEFAULT_API_BASE_URL).replace(/\/+$/, ""),
71
150
  translationEngine: data.translation_engine,
72
151
  apiLocales: Object.fromEntries(languages.map((lang) => [lang.custom_code || lang.language_to, lang.language_to]))
73
152
  };
@@ -75,5 +154,6 @@ var WeglotApiClient = class {
75
154
  };
76
155
 
77
156
  //#endregion
157
+ exports.DEFAULT_API_BASE_URL = DEFAULT_API_BASE_URL;
78
158
  exports.UnsupportedLanguagePairError = UnsupportedLanguagePairError;
79
159
  exports.WeglotApiClient = WeglotApiClient;
@@ -3,25 +3,18 @@ import { WORD_TYPE } from "./definitions/definitions.generated.mjs";
3
3
 
4
4
  //#region src/translators/weglot/api-client.ts
5
5
  /**
6
- * Thin HTTP client for the Weglot public API.
7
- *
8
- * - Translation: POST https://api.weglot.com/translate?api_key=<key>
9
- * - Project settings: cdn.weglot.com/projects-settings/<id>.json for v1 keys,
10
- * api.weglot.com/project-settings otherwise (weglot-js getCdnSettings.ts).
11
- *
12
- * Translations made through the API are recorded in the Weglot project and
13
- * can be reviewed/edited in the Weglot dashboard.
6
+ * Weglot API client. Weglot translates with an LLM: a word not translated yet
7
+ * comes back null and is queued, so callers poll until it is ready.
14
8
  */
15
- const TRANSLATE_URL = "https://api.weglot.com/translate";
16
- const CDN_SETTINGS_URL = "https://cdn.weglot.com/projects-settings";
17
- const API_SETTINGS_URL = "https://api.weglot.com/project-settings";
18
- const V1_KEY_PREFIX = "wg_";
9
+ const DEFAULT_SETTINGS_URL = "https://api.weglot.com/project-settings";
10
+ const DEFAULT_API_BASE_URL = "https://api.weglot.com";
11
+ const SUPPORTED_PRODUCT = "2.0";
19
12
  const WORD_TYPE_TEXT = WORD_TYPE.TEXT;
20
13
  const REQUEST_URL = "https://compiler.weglot.com/";
21
- function settingsUrlFor(apiKey) {
22
- if (apiKey.startsWith(V1_KEY_PREFIX)) return `${CDN_SETTINGS_URL}/${apiKey.slice(3)}.json`;
23
- return `${API_SETTINGS_URL}?api_key=${apiKey}`;
24
- }
14
+ const WORD_LABEL = "translate-react";
15
+ const MAX_WORDS_PER_REQUEST = 100;
16
+ const DEFAULT_POLL_INTERVAL_MS = 5e3;
17
+ const REFUSED_AFTER_MISSES = 2;
25
18
  /** The API validates the pair independently of the project's languages, so
26
19
  * `en`→`sr-latn` can be refused. Callers skip the locale rather than failing. */
27
20
  var UnsupportedLanguagePairError = class extends Error {
@@ -32,42 +25,128 @@ var UnsupportedLanguagePairError = class extends Error {
32
25
  this.name = "UnsupportedLanguagePairError";
33
26
  }
34
27
  };
28
+ /** A 400 the API gives a whole request when one of its words is unreadable. */
29
+ var RefusedRequestError = class extends Error {};
30
+ const wellFormed = (text) => text.replace(/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g, "�");
31
+ const defaultSleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
35
32
  var WeglotApiClient = class {
36
- constructor(apiKey) {
33
+ apiBaseUrl;
34
+ constructor(apiKey, apiBaseUrl) {
37
35
  this.apiKey = apiKey;
36
+ this.apiBaseUrl = apiBaseUrl || DEFAULT_API_BASE_URL;
38
37
  }
38
+ /** One request. A word not translated yet comes back null, with an id once the API has queued it. */
39
39
  async translate(params) {
40
- const response = await fetch(`${TRANSLATE_URL}?api_key=${this.apiKey}`, {
40
+ const query = params.live ? "?live=1" : "";
41
+ const response = await fetch(`${this.apiBaseUrl}/translate${query}`, {
41
42
  method: "POST",
42
- headers: { "Content-Type": "application/json" },
43
+ headers: {
44
+ "Content-Type": "application/json",
45
+ Accept: "application/json",
46
+ Authorization: `Key ${this.apiKey}`
47
+ },
43
48
  body: JSON.stringify({
44
49
  l_from: params.from,
45
50
  l_to: params.to,
46
51
  request_url: REQUEST_URL,
47
52
  words: params.words.map((w, index) => ({
48
53
  t: params.types?.[index] ?? WORD_TYPE_TEXT,
49
- w
54
+ w: wellFormed(w),
55
+ l: [WORD_LABEL]
50
56
  }))
51
57
  })
52
58
  });
53
59
  if (!response.ok) {
54
60
  const body = await response.text().catch(() => "");
55
61
  if (response.status === 400 && /not valid languages pair/i.test(body)) throw new UnsupportedLanguagePairError(params.from, params.to);
62
+ if (response.status === 400) throw new RefusedRequestError(`Weglot translate API refused the request (400): ${body || "no response body"}`);
56
63
  throw new Error(`Weglot translate API error (${response.status}): ${body || "no response body"}`);
57
64
  }
58
- const toWords = (await response.json()).to_words;
65
+ const data = await response.json();
66
+ const toWords = data.to_words;
59
67
  if (!Array.isArray(toWords) || toWords.length !== params.words.length) throw new Error(`Weglot translate API returned a mismatched word count (sent ${params.words.length}, received ${Array.isArray(toWords) ? toWords.length : "none"})`);
60
- return toWords;
68
+ const ids = Array.isArray(data.ids) ? data.ids : null;
69
+ return {
70
+ words: toWords,
71
+ accepted: toWords.map((value, index) => value !== null || ids === null || (ids[index] ?? null) !== null)
72
+ };
73
+ }
74
+ /** Re-polls words until translated or the deadline. A failed request leaves
75
+ * its words pending, so one error never discards what was already received. */
76
+ async translateUntilReady(params, { deadline, pollIntervalMs = DEFAULT_POLL_INTERVAL_MS, sleep = defaultSleep }) {
77
+ const words = new Array(params.words.length).fill(null);
78
+ const everAccepted = new Array(params.words.length).fill(false);
79
+ const misses = new Array(params.words.length).fill(0);
80
+ const refused = /* @__PURE__ */ new Set();
81
+ let pending = params.words.map((_, index) => index);
82
+ let received = false;
83
+ let anyAccepted = false;
84
+ let lastError;
85
+ while (true) {
86
+ for (let i = 0; i < pending.length; i += MAX_WORDS_PER_REQUEST) try {
87
+ const answers = await this.sendIsolatingRefused(params, pending.slice(i, i + MAX_WORDS_PER_REQUEST), refused);
88
+ received = true;
89
+ for (const { index, word, accepted } of answers) {
90
+ words[index] = word;
91
+ if (accepted) {
92
+ everAccepted[index] = true;
93
+ anyAccepted = true;
94
+ } else misses[index]++;
95
+ }
96
+ } catch (error) {
97
+ if (error instanceof UnsupportedLanguagePairError) throw error;
98
+ lastError = error;
99
+ }
100
+ if (anyAccepted) {
101
+ for (const index of pending) if (!everAccepted[index] && misses[index] >= REFUSED_AFTER_MISSES) refused.add(index);
102
+ }
103
+ pending = pending.filter((index) => words[index] === null && !refused.has(index));
104
+ const remaining = deadline - Date.now();
105
+ if (pending.length === 0 || remaining <= 0) {
106
+ if (!received && lastError !== void 0) throw lastError;
107
+ return {
108
+ words,
109
+ refused: [...refused].sort((a, b) => a - b)
110
+ };
111
+ }
112
+ await sleep(Math.min(pollIntervalMs, remaining));
113
+ }
114
+ }
115
+ /** Splits a request the API refuses until the unreadable word is alone, then marks it refused. */
116
+ async sendIsolatingRefused(params, indexes, refused) {
117
+ try {
118
+ const { words, accepted } = await withTimeout(this.translate({
119
+ from: params.from,
120
+ to: params.to,
121
+ words: indexes.map((index) => params.words[index]),
122
+ types: params.types && indexes.map((index) => params.types[index])
123
+ }), DEFAULT_TIMEOUTS.AI_API, `Weglot API translation to ${params.to}`);
124
+ return indexes.map((index, k) => ({
125
+ index,
126
+ word: words[k],
127
+ accepted: accepted[k]
128
+ }));
129
+ } catch (error) {
130
+ if (!(error instanceof RefusedRequestError)) throw error;
131
+ if (indexes.length === 1) {
132
+ refused.add(indexes[0]);
133
+ return [];
134
+ }
135
+ const middle = Math.ceil(indexes.length / 2);
136
+ return [...await this.sendIsolatingRefused(params, indexes.slice(0, middle), refused), ...await this.sendIsolatingRefused(params, indexes.slice(middle), refused)];
137
+ }
61
138
  }
62
139
  async fetchSettings() {
63
- const response = await withTimeout(fetch(settingsUrlFor(this.apiKey)), DEFAULT_TIMEOUTS.AI_API, "Weglot project settings fetch");
140
+ const response = await withTimeout(fetch(`${process.env.WEGLOT_SETTINGS_URL || DEFAULT_SETTINGS_URL}?api_key=${encodeURIComponent(this.apiKey)}`, { headers: { Accept: "application/json" } }), DEFAULT_TIMEOUTS.AI_API, "Weglot project settings fetch");
64
141
  if (!response.ok) throw new Error(`Failed to fetch Weglot project settings (${response.status}). Check that your Weglot project key is valid.`);
65
142
  const data = await response.json();
143
+ if (data.product !== SUPPORTED_PRODUCT) throw new Error("@weglot/translate-react does not support the Weglot project this key belongs to. Check that you are using the right project key.");
66
144
  if (!data.language_from || !Array.isArray(data.languages)) throw new Error("Unexpected Weglot project settings format: missing language_from or languages.");
67
145
  const languages = data.languages.filter((lang) => lang.enabled !== false);
68
146
  return {
69
147
  sourceLocale: data.language_from,
70
148
  targetLocales: languages.map((lang) => lang.custom_code || lang.language_to),
149
+ apiBaseUrl: (data.api_base_url || DEFAULT_API_BASE_URL).replace(/\/+$/, ""),
71
150
  translationEngine: data.translation_engine,
72
151
  apiLocales: Object.fromEntries(languages.map((lang) => [lang.custom_code || lang.language_to, lang.language_to]))
73
152
  };
@@ -75,5 +154,5 @@ var WeglotApiClient = class {
75
154
  };
76
155
 
77
156
  //#endregion
78
- export { UnsupportedLanguagePairError, WeglotApiClient };
157
+ export { DEFAULT_API_BASE_URL, UnsupportedLanguagePairError, WeglotApiClient };
79
158
  //# sourceMappingURL=api-client.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"api-client.mjs","names":["from: string","to: string","apiKey: string"],"sources":["../../../src/translators/weglot/api-client.ts"],"sourcesContent":["/**\n * Thin HTTP client for the Weglot public API.\n *\n * - Translation: POST https://api.weglot.com/translate?api_key=<key>\n * - Project settings: cdn.weglot.com/projects-settings/<id>.json for v1 keys,\n * api.weglot.com/project-settings otherwise (weglot-js getCdnSettings.ts).\n *\n * Translations made through the API are recorded in the Weglot project and\n * can be reviewed/edited in the Weglot dashboard.\n */\n\nimport { DEFAULT_TIMEOUTS, withTimeout } from \"../../utils/timeout\";\nimport { WORD_TYPE } from \"./definitions/definitions.generated\";\n\nconst TRANSLATE_URL = \"https://api.weglot.com/translate\";\nconst CDN_SETTINGS_URL = \"https://cdn.weglot.com/projects-settings\";\nconst API_SETTINGS_URL = \"https://api.weglot.com/project-settings\";\n// v1 keys are the project id behind a \"wg_\" prefix; the CDN is keyed by the id.\nconst V1_KEY_PREFIX = \"wg_\";\n// Body text; other types identify attributes (VALUE, IMG_ALT) and would misfile it.\nconst WORD_TYPE_TEXT = WORD_TYPE.TEXT;\n// The API requires a request_url identifying the caller.\nconst REQUEST_URL = \"https://compiler.weglot.com/\";\n\nexport type WeglotProjectSettings = {\n sourceLocale: string;\n targetLocales: string[];\n /** Public locale to the code the translate API expects: `a0` is served as `br`,\n * and only `a0` is a valid pair. */\n apiLocales: Record<string, string>;\n /** Inline elements allowed in a segment; absent on older projects, then derived\n * from the key length. */\n translationEngine?: number;\n};\n\nexport function settingsUrlFor(apiKey: string): string {\n if (apiKey.startsWith(V1_KEY_PREFIX)) {\n return `${CDN_SETTINGS_URL}/${apiKey.slice(V1_KEY_PREFIX.length)}.json`;\n }\n return `${API_SETTINGS_URL}?api_key=${apiKey}`;\n}\n\n/** The API validates the pair independently of the project's languages, so\n * `en`→`sr-latn` can be refused. Callers skip the locale rather than failing. */\nexport class UnsupportedLanguagePairError extends Error {\n constructor(\n readonly from: string,\n readonly to: string,\n ) {\n super(`The Weglot API does not translate \"${from}\" to \"${to}\".`);\n this.name = \"UnsupportedLanguagePairError\";\n }\n}\n\nexport class WeglotApiClient {\n constructor(private readonly apiKey: string) {}\n\n async translate(params: {\n from: string;\n to: string;\n words: string[];\n /** Word type per word; body text when omitted. */\n types?: number[];\n }): Promise<string[]> {\n const response = await fetch(\n `${TRANSLATE_URL}?api_key=${this.apiKey}`,\n {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({\n l_from: params.from,\n l_to: params.to,\n request_url: REQUEST_URL,\n words: params.words.map((w, index) => ({\n t: params.types?.[index] ?? WORD_TYPE_TEXT,\n w,\n })),\n }),\n },\n );\n\n if (!response.ok) {\n const body = await response.text().catch(() => \"\");\n if (response.status === 400 && /not valid languages pair/i.test(body)) {\n throw new UnsupportedLanguagePairError(params.from, params.to);\n }\n throw new Error(\n `Weglot translate API error (${response.status}): ${body || \"no response body\"}`,\n );\n }\n\n const data = (await response.json()) as { to_words?: string[] };\n const toWords = data.to_words;\n if (!Array.isArray(toWords) || toWords.length !== params.words.length) {\n throw new Error(\n `Weglot translate API returned a mismatched word count (sent ${params.words.length}, received ${Array.isArray(toWords) ? toWords.length : \"none\"})`,\n );\n }\n return toWords;\n }\n\n async fetchSettings(): Promise<WeglotProjectSettings> {\n const response = await withTimeout(\n fetch(settingsUrlFor(this.apiKey)),\n DEFAULT_TIMEOUTS.AI_API,\n \"Weglot project settings fetch\",\n );\n\n if (!response.ok) {\n throw new Error(\n `Failed to fetch Weglot project settings (${response.status}). Check that your Weglot project key is valid.`,\n );\n }\n\n const data = (await response.json()) as {\n language_from?: string;\n languages?: {\n language_to: string;\n custom_code?: string | null;\n enabled?: boolean;\n }[];\n translation_engine?: number;\n };\n\n if (!data.language_from || !Array.isArray(data.languages)) {\n throw new Error(\n \"Unexpected Weglot project settings format: missing language_from or languages.\",\n );\n }\n\n // Disabled languages are not public, so they are not built.\n const languages = data.languages.filter((lang) => lang.enabled !== false);\n\n return {\n sourceLocale: data.language_from,\n targetLocales: languages.map((lang) => lang.custom_code || lang.language_to),\n translationEngine: data.translation_engine,\n apiLocales: Object.fromEntries(\n languages.map((lang) => [\n lang.custom_code || lang.language_to,\n lang.language_to,\n ]),\n ),\n };\n }\n}\n"],"mappings":";;;;;;;;;;;;;;AAcA,MAAM,gBAAgB;AACtB,MAAM,mBAAmB;AAC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;AAEH,SAAO;;CAGT,MAAM,gBAAgD;EACpD,MAAM,WAAW,MAAM,YACrB,MAAM,eAAe,KAAK,OAAO,CAAC,EAClC,iBAAiB,QACjB,gCACD;AAED,MAAI,CAAC,SAAS,GACZ,OAAM,IAAI,MACR,4CAA4C,SAAS,OAAO,iDAC7D;EAGH,MAAM,OAAQ,MAAM,SAAS,MAAM;AAUnC,MAAI,CAAC,KAAK,iBAAiB,CAAC,MAAM,QAAQ,KAAK,UAAU,CACvD,OAAM,IAAI,MACR,iFACD;EAIH,MAAM,YAAY,KAAK,UAAU,QAAQ,SAAS,KAAK,YAAY,MAAM;AAEzE,SAAO;GACL,cAAc,KAAK;GACnB,eAAe,UAAU,KAAK,SAAS,KAAK,eAAe,KAAK,YAAY;GAC5E,mBAAmB,KAAK;GACxB,YAAY,OAAO,YACjB,UAAU,KAAK,SAAS,CACtB,KAAK,eAAe,KAAK,aACzB,KAAK,YACN,CAAC,CACH;GACF"}
1
+ {"version":3,"file":"api-client.mjs","names":["from: string","to: string","apiKey: string","words: (string | null)[]","everAccepted: boolean[]","misses: number[]","lastError: unknown"],"sources":["../../../src/translators/weglot/api-client.ts"],"sourcesContent":["/**\n * Weglot API client. Weglot translates with an LLM: a word not translated yet\n * comes back null and is queued, so callers poll until it is ready.\n */\n\nimport { DEFAULT_TIMEOUTS, withTimeout } from \"../../utils/timeout\";\nimport { WORD_TYPE } from \"./definitions/definitions.generated\";\n\nconst DEFAULT_SETTINGS_URL = \"https://api.weglot.com/project-settings\";\nexport const DEFAULT_API_BASE_URL = \"https://api.weglot.com\";\nconst SUPPORTED_PRODUCT = \"2.0\";\n// Body text; other types identify attributes (VALUE, IMG_ALT) and would misfile it.\nconst WORD_TYPE_TEXT = WORD_TYPE.TEXT;\n// The API requires a request_url identifying the caller.\nconst REQUEST_URL = \"https://compiler.weglot.com/\";\n// Tags the words in the dashboard with where they came from.\nconst WORD_LABEL = \"translate-react\";\nexport const MAX_WORDS_PER_REQUEST = 100;\nexport const DEFAULT_POLL_INTERVAL_MS = 5_000;\n// The API sometimes takes new words only on a second request; one still without an id after this many is refused.\nconst REFUSED_AFTER_MISSES = 2;\n\nexport type WeglotProjectSettings = {\n sourceLocale: string;\n targetLocales: string[];\n /** Public locale to the code the translate API expects: `a0` is served as `br`,\n * and only `a0` is a valid pair. */\n apiLocales: Record<string, string>;\n /** The project's regional API host, e.g. https://eu.api.weglot.com. */\n apiBaseUrl: string;\n /** Inline elements allowed in a segment; absent on older projects. */\n translationEngine?: number;\n};\n\nexport type TranslateParams = {\n from: string;\n to: string;\n words: string[];\n /** Word type per word; body text when omitted. */\n types?: number[];\n /** Marks a request made while a page renders, as opposed to a build. */\n live?: boolean;\n};\n\nexport type TranslateResponse = {\n /** Null while not translated yet. */\n words: (string | null)[];\n /** Whether the API took each word in: it was translated or given an id. */\n accepted: boolean[];\n};\n\nexport type PolledTranslation = {\n /** Null for words still queued at the deadline or refused. */\n words: (string | null)[];\n /** Indexes of the words the API will not translate. */\n refused: number[];\n};\n\nexport type PollOptions = {\n /** Epoch ms after which words still queued are given up on. */\n deadline: number;\n pollIntervalMs?: number;\n sleep?: (ms: number) => Promise<void>;\n};\n\n/** The API validates the pair independently of the project's languages, so\n * `en`→`sr-latn` can be refused. Callers skip the locale rather than failing. */\nexport class UnsupportedLanguagePairError extends Error {\n constructor(\n readonly from: string,\n readonly to: string,\n ) {\n super(`The Weglot API does not translate \"${from}\" to \"${to}\".`);\n this.name = \"UnsupportedLanguagePairError\";\n }\n}\n\n/** A 400 the API gives a whole request when one of its words is unreadable. */\nclass RefusedRequestError extends Error {}\n\nconst wellFormed = (text: string) =>\n text.replace(/[\\uD800-\\uDBFF](?![\\uDC00-\\uDFFF])|(?<![\\uD800-\\uDBFF])[\\uDC00-\\uDFFF]/g, \"\\uFFFD\");\n\nconst defaultSleep = (ms: number) =>\n new Promise<void>((resolve) => setTimeout(resolve, ms));\n\nexport class WeglotApiClient {\n private readonly apiBaseUrl: string;\n\n constructor(\n private readonly apiKey: string,\n apiBaseUrl?: string,\n ) {\n this.apiBaseUrl = apiBaseUrl || DEFAULT_API_BASE_URL;\n }\n\n /** One request. A word not translated yet comes back null, with an id once the API has queued it. */\n async translate(params: TranslateParams): Promise<TranslateResponse> {\n const query = params.live ? \"?live=1\" : \"\";\n const response = await fetch(`${this.apiBaseUrl}/translate${query}`, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Accept: \"application/json\",\n Authorization: `Key ${this.apiKey}`,\n },\n body: JSON.stringify({\n l_from: params.from,\n l_to: params.to,\n request_url: REQUEST_URL,\n words: params.words.map((w, index) => ({\n t: params.types?.[index] ?? WORD_TYPE_TEXT,\n // A lone surrogate makes the API refuse the whole request.\n w: wellFormed(w),\n l: [WORD_LABEL],\n })),\n }),\n });\n\n if (!response.ok) {\n const body = await response.text().catch(() => \"\");\n if (response.status === 400 && /not valid languages pair/i.test(body)) {\n throw new UnsupportedLanguagePairError(params.from, params.to);\n }\n if (response.status === 400) {\n throw new RefusedRequestError(\n `Weglot translate API refused the request (400): ${body || \"no response body\"}`,\n );\n }\n throw new Error(\n `Weglot translate API error (${response.status}): ${body || \"no response body\"}`,\n );\n }\n\n const data = (await response.json()) as {\n to_words?: (string | null)[];\n ids?: (string | null)[];\n };\n const toWords = data.to_words;\n if (!Array.isArray(toWords) || toWords.length !== params.words.length) {\n throw new Error(\n `Weglot translate API returned a mismatched word count (sent ${params.words.length}, received ${Array.isArray(toWords) ? toWords.length : \"none\"})`,\n );\n }\n const ids = Array.isArray(data.ids) ? data.ids : null;\n\n return {\n words: toWords,\n accepted: toWords.map(\n (value, index) => value !== null || ids === null || (ids[index] ?? null) !== null,\n ),\n };\n }\n\n /** Re-polls words until translated or the deadline. A failed request leaves\n * its words pending, so one error never discards what was already received. */\n async translateUntilReady(\n params: TranslateParams,\n { deadline, pollIntervalMs = DEFAULT_POLL_INTERVAL_MS, sleep = defaultSleep }: PollOptions,\n ): Promise<PolledTranslation> {\n const words: (string | null)[] = new Array(params.words.length).fill(null);\n const everAccepted: boolean[] = new Array(params.words.length).fill(false);\n const misses: number[] = new Array(params.words.length).fill(0);\n const refused = new Set<number>();\n let pending = params.words.map((_, index) => index);\n let received = false;\n let anyAccepted = false;\n let lastError: unknown;\n\n while (true) {\n for (let i = 0; i < pending.length; i += MAX_WORDS_PER_REQUEST) {\n try {\n const answers = await this.sendIsolatingRefused(\n params,\n pending.slice(i, i + MAX_WORDS_PER_REQUEST),\n refused,\n );\n received = true;\n for (const { index, word, accepted } of answers) {\n words[index] = word;\n if (accepted) {\n everAccepted[index] = true;\n anyAccepted = true;\n } else {\n misses[index]++;\n }\n }\n } catch (error) {\n if (error instanceof UnsupportedLanguagePairError) throw error;\n lastError = error;\n }\n }\n\n // Only while the API takes other words in: otherwise it is not ready, and the words stay pending.\n if (anyAccepted) {\n for (const index of pending) {\n if (!everAccepted[index] && misses[index] >= REFUSED_AFTER_MISSES) refused.add(index);\n }\n }\n pending = pending.filter((index) => words[index] === null && !refused.has(index));\n\n const remaining = deadline - Date.now();\n if (pending.length === 0 || remaining <= 0) {\n // Nothing ever got through: a key or quota problem, not a slow queue.\n if (!received && lastError !== undefined) throw lastError;\n return { words, refused: [...refused].sort((a, b) => a - b) };\n }\n await sleep(Math.min(pollIntervalMs, remaining));\n }\n }\n\n /** Splits a request the API refuses until the unreadable word is alone, then marks it refused. */\n private async sendIsolatingRefused(\n params: TranslateParams,\n indexes: number[],\n refused: Set<number>,\n ): Promise<{ index: number; word: string | null; accepted: boolean }[]> {\n try {\n const { words, accepted } = await withTimeout(\n this.translate({\n from: params.from,\n to: params.to,\n words: indexes.map((index) => params.words[index]),\n types: params.types && indexes.map((index) => params.types![index]),\n }),\n DEFAULT_TIMEOUTS.AI_API,\n `Weglot API translation to ${params.to}`,\n );\n return indexes.map((index, k) => ({ index, word: words[k], accepted: accepted[k] }));\n } catch (error) {\n if (!(error instanceof RefusedRequestError)) throw error;\n if (indexes.length === 1) {\n refused.add(indexes[0]);\n return [];\n }\n const middle = Math.ceil(indexes.length / 2);\n return [\n ...(await this.sendIsolatingRefused(params, indexes.slice(0, middle), refused)),\n ...(await this.sendIsolatingRefused(params, indexes.slice(middle), refused)),\n ];\n }\n }\n\n async fetchSettings(): Promise<WeglotProjectSettings> {\n const response = await withTimeout(\n // Overridable to point at another settings endpoint.\n fetch(`${process.env.WEGLOT_SETTINGS_URL || DEFAULT_SETTINGS_URL}?api_key=${encodeURIComponent(this.apiKey)}`, {\n headers: { Accept: \"application/json\" },\n }),\n DEFAULT_TIMEOUTS.AI_API,\n \"Weglot project settings fetch\",\n );\n\n if (!response.ok) {\n throw new Error(\n `Failed to fetch Weglot project settings (${response.status}). Check that your Weglot project key is valid.`,\n );\n }\n\n const data = (await response.json()) as {\n product?: string;\n api_base_url?: string;\n language_from?: string;\n languages?: {\n language_to: string;\n custom_code?: string | null;\n enabled?: boolean;\n }[];\n translation_engine?: number;\n };\n\n if (data.product !== SUPPORTED_PRODUCT) {\n throw new Error(\n \"@weglot/translate-react does not support the Weglot project this key belongs to. Check that you are using the right project key.\",\n );\n }\n\n if (!data.language_from || !Array.isArray(data.languages)) {\n throw new Error(\n \"Unexpected Weglot project settings format: missing language_from or languages.\",\n );\n }\n\n // Disabled languages are not public, so they are not built.\n const languages = data.languages.filter((lang) => lang.enabled !== false);\n\n return {\n sourceLocale: data.language_from,\n targetLocales: languages.map((lang) => lang.custom_code || lang.language_to),\n apiBaseUrl: (data.api_base_url || DEFAULT_API_BASE_URL).replace(/\\/+$/, \"\"),\n translationEngine: data.translation_engine,\n apiLocales: Object.fromEntries(\n languages.map((lang) => [\n lang.custom_code || lang.language_to,\n lang.language_to,\n ]),\n ),\n };\n }\n}\n"],"mappings":";;;;;;;;AAQA,MAAM,uBAAuB;AAC7B,MAAa,uBAAuB;AACpC,MAAM,oBAAoB;AAE1B,MAAM,iBAAiB,UAAU;AAEjC,MAAM,cAAc;AAEpB,MAAM,aAAa;AACnB,MAAa,wBAAwB;AACrC,MAAa,2BAA2B;A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AAW,mBAAmB,KAAK,OAAO,IAAI,EAC7G,SAAS,EAAE,QAAQ,oBAAoB,EACxC,CAAC,EACF,iBAAiB,QACjB,gCACD;AAED,MAAI,CAAC,SAAS,GACZ,OAAM,IAAI,MACR,4CAA4C,SAAS,OAAO,iDAC7D;EAGH,MAAM,OAAQ,MAAM,SAAS,MAAM;AAYnC,MAAI,KAAK,YAAY,kBACnB,OAAM,IAAI,MACR,mIACD;AAGH,MAAI,CAAC,KAAK,iBAAiB,CAAC,MAAM,QAAQ,KAAK,UAAU,CACvD,OAAM,IAAI,MACR,iFACD;EAIH,MAAM,YAAY,KAAK,UAAU,QAAQ,SAAS,KAAK,YAAY,MAAM;AAEzE,SAAO;GACL,cAAc,KAAK;GACnB,eAAe,UAAU,KAAK,SAAS,KAAK,eAAe,KAAK,YAAY;GAC5E,aAAa,KAAK,gBAAgB,sBAAsB,QAAQ,QAAQ,GAAG;GAC3E,mBAAmB,KAAK;GACxB,YAAY,OAAO,YACjB,UAAU,KAAK,SAAS,CACtB,KAAK,eAAe,KAAK,aACzB,KAAK,YACN,CAAC,CACH;GACF"}
@@ -5,11 +5,8 @@ const require_definitions_generated = require('./definitions/definitions.generat
5
5
  * The engine version and the inline tags it merges: sending a tag it does not
6
6
  * merge gets the segment back untranslated, so the set follows the project.
7
7
  */
8
- /** Keys shorter than this are v1 projects, as connect-edge and weglot-js also detect. */
9
- const V1_KEY_LENGTH = 36;
10
8
  /** connect-edge's default for a modern key. weglot-js still defaults to 2. */
11
9
  const DEFAULT_MODERN_ENGINE = 3;
12
- const LEGACY_ENGINE = 1;
13
10
  /** Fallback tag for a placeholder or unknown element; the name is only a hint,
14
11
  * so the first permitted one wins. */
15
12
  const FALLBACK_TAG_PREFERENCE = [
@@ -18,9 +15,9 @@ const FALLBACK_TAG_PREFERENCE = [
18
15
  "u",
19
16
  "b"
20
17
  ];
21
- function resolveTranslationEngine(apiKey, fromSettings) {
18
+ function resolveTranslationEngine(fromSettings) {
22
19
  if (typeof fromSettings === "number" && Number.isFinite(fromSettings) && fromSettings > 0) return fromSettings;
23
- return apiKey.length < V1_KEY_LENGTH ? LEGACY_ENGINE : DEFAULT_MODERN_ENGINE;
20
+ return DEFAULT_MODERN_ENGINE;
24
21
  }
25
22
  function mergeableTagsFor(engine) {
26
23
  const tags = [];
@@ -5,11 +5,8 @@ import { MERGE_NODES } from "./definitions/definitions.generated.mjs";
5
5
  * The engine version and the inline tags it merges: sending a tag it does not
6
6
  * merge gets the segment back untranslated, so the set follows the project.
7
7
  */
8
- /** Keys shorter than this are v1 projects, as connect-edge and weglot-js also detect. */
9
- const V1_KEY_LENGTH = 36;
10
8
  /** connect-edge's default for a modern key. weglot-js still defaults to 2. */
11
9
  const DEFAULT_MODERN_ENGINE = 3;
12
- const LEGACY_ENGINE = 1;
13
10
  /** Fallback tag for a placeholder or unknown element; the name is only a hint,
14
11
  * so the first permitted one wins. */
15
12
  const FALLBACK_TAG_PREFERENCE = [
@@ -18,9 +15,9 @@ const FALLBACK_TAG_PREFERENCE = [
18
15
  "u",
19
16
  "b"
20
17
  ];
21
- function resolveTranslationEngine(apiKey, fromSettings) {
18
+ function resolveTranslationEngine(fromSettings) {
22
19
  if (typeof fromSettings === "number" && Number.isFinite(fromSettings) && fromSettings > 0) return fromSettings;
23
- return apiKey.length < V1_KEY_LENGTH ? LEGACY_ENGINE : DEFAULT_MODERN_ENGINE;
20
+ return DEFAULT_MODERN_ENGINE;
24
21
  }
25
22
  function mergeableTagsFor(engine) {
26
23
  const tags = [];
@@ -1 +1 @@
1
- {"version":3,"file":"engine.mjs","names":["tags: string[]","INLINE_TAGS: ReadonlySet<string>"],"sources":["../../../src/translators/weglot/engine.ts"],"sourcesContent":["/**\n * The engine version and the inline tags it merges: sending a tag it does not\n * merge gets the segment back untranslated, so the set follows the project.\n */\n\nimport { MERGE_NODES } from \"./definitions/definitions.generated\";\n\n/** Keys shorter than this are v1 projects, as connect-edge and weglot-js also detect. */\nexport const V1_KEY_LENGTH = 36;\n\n/** connect-edge's default for a modern key. weglot-js still defaults to 2. */\nexport const DEFAULT_MODERN_ENGINE = 3;\n\nexport const LEGACY_ENGINE = 1;\n\n/** Fallback tag for a placeholder or unknown element; the name is only a hint,\n * so the first permitted one wins. */\nconst FALLBACK_TAG_PREFERENCE = [\"span\", \"bdi\", \"u\", \"b\"];\n\nexport function resolveTranslationEngine(\n apiKey: string,\n fromSettings?: number | null,\n): number {\n if (typeof fromSettings === \"number\" && Number.isFinite(fromSettings) && fromSettings > 0) {\n return fromSettings;\n }\n return apiKey.length < V1_KEY_LENGTH ? LEGACY_ENGINE : DEFAULT_MODERN_ENGINE;\n}\n\nexport function mergeableTagsFor(engine: number): ReadonlySet<string> {\n const tags: string[] = [];\n if (engine >= 2) tags.push(...MERGE_NODES.v2);\n if (engine > 2) tags.push(...MERGE_NODES.v3);\n return new Set(tags.map((tag) => tag.toLowerCase()));\n}\n\n/** Undefined on engine 1, which merges nothing and so permits no tag at all. */\nexport function fallbackWireTagFor(\n tags: ReadonlySet<string>,\n): string | undefined {\n return FALLBACK_TAG_PREFERENCE.find((tag) => tags.has(tag));\n}\n\n/**\n * Every inline tag any engine merges. Fixed rather than per-project: the hash\n * follows the stored text, so a remote setting would re-hash on every change.\n */\nexport const INLINE_TAGS: ReadonlySet<string> = new Set(\n Object.values(MERGE_NODES)\n .flat()\n .map((tag) => tag.toLowerCase()),\n);\n"],"mappings":";;;;;;;;AAQA,MAAa,gBAAgB;;AAG7B,MAAa,wBAAwB;AAErC,MAAa,gBAAgB;;;AAI7B,MAAM,0BAA0B;CAAC;CAAQ;CAAO;CAAK;CAAI;AAEzD,SAAgB,yBACd,QACA,cACQ;AACR,KAAI,OAAO,iBAAiB,YAAY,OAAO,SAAS,aAAa,IAAI,eAAe,EACtF,QAAO;AAET,QAAO,OAAO,SAAS,gBAAgB,gBAAgB;;AAGzD,SAAgB,iBAAiB,QAAqC;CACpE,MAAMA,OAAiB,EAAE;AACzB,KAAI,UAAU,EAAG,MAAK,KAAK,GAAG,YAAY,GAAG;AAC7C,KAAI,SAAS,EAAG,MAAK,KAAK,GAAG,YAAY,GAAG;AAC5C,QAAO,IAAI,IAAI,KAAK,KAAK,QAAQ,IAAI,aAAa,CAAC,CAAC;;;AAItD,SAAgB,mBACd,MACoB;AACpB,QAAO,wBAAwB,MAAM,QAAQ,KAAK,IAAI,IAAI,CAAC;;;;;;AAO7D,MAAaC,cAAmC,IAAI,IAClD,OAAO,OAAO,YAAY,CACvB,MAAM,CACN,KAAK,QAAQ,IAAI,aAAa,CAAC,CACnC"}
1
+ {"version":3,"file":"engine.mjs","names":["tags: string[]","INLINE_TAGS: ReadonlySet<string>"],"sources":["../../../src/translators/weglot/engine.ts"],"sourcesContent":["/**\n * The engine version and the inline tags it merges: sending a tag it does not\n * merge gets the segment back untranslated, so the set follows the project.\n */\n\nimport { MERGE_NODES } from \"./definitions/definitions.generated\";\n\n/** connect-edge's default for a modern key. weglot-js still defaults to 2. */\nexport const DEFAULT_MODERN_ENGINE = 3;\n\n/** Fallback tag for a placeholder or unknown element; the name is only a hint,\n * so the first permitted one wins. */\nconst FALLBACK_TAG_PREFERENCE = [\"span\", \"bdi\", \"u\", \"b\"];\n\nexport function resolveTranslationEngine(fromSettings?: number | null): number {\n if (typeof fromSettings === \"number\" && Number.isFinite(fromSettings) && fromSettings > 0) {\n return fromSettings;\n }\n return DEFAULT_MODERN_ENGINE;\n}\n\nexport function mergeableTagsFor(engine: number): ReadonlySet<string> {\n const tags: string[] = [];\n if (engine >= 2) tags.push(...MERGE_NODES.v2);\n if (engine > 2) tags.push(...MERGE_NODES.v3);\n return new Set(tags.map((tag) => tag.toLowerCase()));\n}\n\n/** Undefined on engine 1, which merges nothing and so permits no tag at all. */\nexport function fallbackWireTagFor(\n tags: ReadonlySet<string>,\n): string | undefined {\n return FALLBACK_TAG_PREFERENCE.find((tag) => tags.has(tag));\n}\n\n/**\n * Every inline tag any engine merges. Fixed rather than per-project: the hash\n * follows the stored text, so a remote setting would re-hash on every change.\n */\nexport const INLINE_TAGS: ReadonlySet<string> = new Set(\n Object.values(MERGE_NODES)\n .flat()\n .map((tag) => tag.toLowerCase()),\n);\n"],"mappings":";;;;;;;;AAQA,MAAa,wBAAwB;;;AAIrC,MAAM,0BAA0B;CAAC;CAAQ;CAAO;CAAK;CAAI;AAEzD,SAAgB,yBAAyB,cAAsC;AAC7E,KAAI,OAAO,iBAAiB,YAAY,OAAO,SAAS,aAAa,IAAI,eAAe,EACtF,QAAO;AAET,QAAO;;AAGT,SAAgB,iBAAiB,QAAqC;CACpE,MAAMA,OAAiB,EAAE;AACzB,KAAI,UAAU,EAAG,MAAK,KAAK,GAAG,YAAY,GAAG;AAC7C,KAAI,SAAS,EAAG,MAAK,KAAK,GAAG,YAAY,GAAG;AAC5C,QAAO,IAAI,IAAI,KAAK,KAAK,QAAQ,IAAI,aAAa,CAAC,CAAC;;;AAItD,SAAgB,mBACd,MACoB;AACpB,QAAO,wBAAwB,MAAM,QAAQ,KAAK,IAAI,IAAI,CAAC;;;;;;AAO7D,MAAaC,cAAmC,IAAI,IAClD,OAAO,OAAO,YAAY,CACvB,MAAM,CACN,KAAK,QAAQ,IAAI,aAAa,CAAC,CACnC"}