@weglot/translate-react 0.2.1 → 0.2.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +22 -3
- package/build/metadata/manager.cjs +18 -5
- package/build/metadata/manager.mjs +17 -5
- package/build/metadata/manager.mjs.map +1 -1
- package/build/plugin/next-compiler-loader.cjs +1 -4
- package/build/plugin/next-compiler-loader.mjs +2 -5
- package/build/plugin/next-compiler-loader.mjs.map +1 -1
- package/build/plugin/next-traces.cjs +38 -0
- package/build/plugin/next-traces.mjs +36 -0
- package/build/plugin/next-traces.mjs.map +1 -0
- package/build/plugin/next.cjs +30 -10
- package/build/plugin/next.d.cts.map +1 -1
- package/build/plugin/next.d.mts.map +1 -1
- package/build/plugin/next.mjs +28 -11
- package/build/plugin/next.mjs.map +1 -1
- package/build/plugin/transform/process-file.cjs +9 -0
- package/build/plugin/transform/process-file.mjs +9 -0
- package/build/plugin/transform/process-file.mjs.map +1 -1
- package/build/plugin/unplugin.cjs +3 -5
- package/build/plugin/unplugin.mjs +4 -6
- package/build/plugin/unplugin.mjs.map +1 -1
- package/build/react/server/ServerWeglotProvider.d.cts +2 -2
- package/build/react/server/ServerWeglotProvider.d.mts +2 -2
- package/build/react/shared/LocaleSwitcher.d.mts +2 -2
- package/build/react/shared/WeglotContext.cjs +18 -2
- package/build/react/shared/WeglotContext.d.cts +1 -0
- package/build/react/shared/WeglotContext.d.cts.map +1 -1
- package/build/react/shared/WeglotContext.d.mts +1 -0
- package/build/react/shared/WeglotContext.d.mts.map +1 -1
- package/build/react/shared/WeglotContext.mjs +18 -2
- package/build/react/shared/WeglotContext.mjs.map +1 -1
- package/build/react/shared/WeglotProvider.cjs +4 -0
- package/build/react/shared/WeglotProvider.d.cts +2 -2
- package/build/react/shared/WeglotProvider.d.cts.map +1 -1
- package/build/react/shared/WeglotProvider.d.mts +2 -2
- package/build/react/shared/WeglotProvider.d.mts.map +1 -1
- package/build/react/shared/WeglotProvider.mjs +4 -0
- package/build/react/shared/WeglotProvider.mjs.map +1 -1
- package/build/types.d.cts +7 -1
- package/build/types.d.cts.map +1 -1
- package/build/types.d.mts +7 -1
- package/build/types.d.mts.map +1 -1
- package/build/utils/package-version.cjs +12 -0
- package/build/utils/package-version.mjs +12 -0
- package/build/utils/package-version.mjs.map +1 -0
- package/package.json +4 -2
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"WeglotProvider.mjs","names":["missingHashes: string[]","missingHashes"],"sources":["../../../src/react/shared/WeglotProvider.tsx"],"sourcesContent":["\"use client\";\n\nimport {\n type PropsWithChildren,\n useCallback,\n useEffect,\n useRef,\n useState,\n} from \"react\";\nimport { logger } from \"../../utils/logger\";\nimport { fetchTranslations } from \"./utils\";\nimport { serverUrl, sourceLocale } from \"@weglot/translate-react/virtual/config\";\nimport {\n getClientLocale,\n persistLocale,\n} from \"@weglot/translate-react/virtual/locale/client\";\nimport { WeglotContext } from \"./WeglotContext\";\nimport type { LocaleCode } from \"../../locale\";\n\nconst noop = () => {};\n\n/**\n * Translation provider props\n */\nexport type WeglotProviderProps = PropsWithChildren<{\n /**\n * Initial locale to use\n */\n initialLocale?: LocaleCode;\n\n /**\n * Initial translations (pre-loaded)\n */\n initialTranslations?: Record<string, string>;\n\n /**\n * Optional router instance for Next.js integration\n * If provided, calls router.refresh() after locale change\n * This ensures Server Components re-render with new locale\n */\n router?: { refresh: () => void };\n}>;\n\nconst IS_DEV = process.env.NODE_ENV === \"development\";\nconst BATCH_DELAY = 200;\n\n/**\n * Translation Provider Component\n *\n * Wraps your app to provide translation context to all components.\n * Handles locale switching and on-demand translation loading.\n *\n * @example\n * ```tsx\n * // In your root layout\n * import { WeglotProvider } from '@weglot/translate-react/react';\n *\n * export default function RootLayout({ children }) {\n * return (\n * <html>\n * <body>\n * <WeglotProvider initialLocale=\"en\">\n * {children}\n * </WeglotProvider>\n * </body>\n * </html>\n * );\n * }\n * ```\n */\n// Export the appropriate provider directly\nexport const WeglotProvider = IS_DEV ? WeglotProvider__Dev : WeglotProvider__Prod;\n\nfunction WeglotProvider__Prod({\n initialLocale,\n initialTranslations = {},\n router,\n children,\n}: WeglotProviderProps) {\n // Use client locale detection if no initialLocale provided\n const [locale, setLocaleState] = useState<LocaleCode>(() => {\n if (initialLocale) return initialLocale;\n // Only detect on client-side (not during SSR)\n if (typeof window !== \"undefined\") {\n return getClientLocale();\n }\n return sourceLocale;\n });\n const [translations, setTranslations] =\n useState<Record<string, string>>(initialTranslations);\n const [isLoading, setIsLoading] = useState(false);\n\n logger.debug(\n `WeglotProvider initialized with locale: ${locale}`,\n initialTranslations,\n );\n\n /**\n * Update HTML lang attribute when locale changes\n * This ensures screen readers and SEO understand the page language\n */\n useEffect(() => {\n if (typeof document !== \"undefined\") {\n document.documentElement.lang = locale;\n }\n }, [locale]);\n\n /**\n * Load translations from public/translations/{locale}.json\n * Lazy loads on-demand for SPAs\n */\n const loadTranslations = useCallback(\n async (targetLocale: LocaleCode) => {\n // If we already have initialTranslations (Next.js SSR), don't fetch\n if (Object.keys(initialTranslations).length > 0) {\n return;\n }\n\n setIsLoading(true);\n try {\n const response = await fetch(`/translations/${targetLocale}.json`);\n if (!response.ok) {\n throw new Error(\n `Failed to load translations for ${targetLocale}: ${response.statusText}`,\n );\n }\n\n const data = await response.json();\n // Translation files have format: { version, locale, entries: {...} }\n setTranslations(data.entries || data);\n logger.debug(\n `Loaded translations for ${targetLocale}:`,\n Object.keys(data.entries || data).length,\n );\n } catch (error) {\n logger.error(`Failed to load translations for ${targetLocale}:`, error);\n // Fallback to empty translations\n setTranslations({});\n } finally {\n setIsLoading(false);\n }\n },\n [initialTranslations],\n );\n\n // Load translations on mount if not provided via initialTranslations\n useEffect(() => {\n if (Object.keys(initialTranslations).length === 0) {\n loadTranslations(locale);\n }\n }, []); // Only run on mount\n\n useEffect(() => {\n // TODO (AleksandrSl 08/12/2025): More elegant solution required.\n // This is used to update the client part when next app changes locale\n if (router) {\n setTranslations(initialTranslations);\n }\n }, [initialTranslations, router]);\n\n /**\n * Change locale\n * - For Next.js SSR: triggers server re-render via router.refresh()\n * - For SPAs: lazy loads translations from /translations/{locale}.json\n */\n const setLocale = useCallback(\n async (newLocale: LocaleCode) => {\n // 1. Persist to cookie so server can read it on next render\n persistLocale(newLocale);\n\n // 2. Update local state for immediate UI feedback\n setLocaleState(newLocale);\n\n // 3a. Next.js pattern: Trigger server re-render\n if (router) {\n router.refresh();\n }\n // 3b. SPA pattern: Lazy load translations\n else {\n await loadTranslations(newLocale);\n }\n },\n [router, loadTranslations],\n );\n\n return (\n <WeglotContext.Provider\n value={{\n locale,\n setLocale,\n translations,\n registerHashes: noop,\n isLoading,\n sourceLocale,\n }}\n >\n {children}\n </WeglotContext.Provider>\n );\n}\n\nfunction WeglotProvider__Dev({\n initialLocale,\n initialTranslations = {},\n router,\n children,\n}: WeglotProviderProps) {\n // Use client locale detection if no initialLocale provided\n const [locale, setLocaleState] = useState(() => {\n if (initialLocale) {\n return initialLocale;\n }\n return getClientLocale();\n });\n const [translations, setTranslations] =\n useState<Record<string, string>>(initialTranslations);\n const [isLoading, setIsLoading] = useState(false);\n\n const [allSeenHashes, setAllSeenHashes] = useState<Set<string>>(new Set());\n const registeredHashesRef = useRef<Set<string>>(new Set());\n const pendingHashesRef = useRef<Set<string>>(new Set());\n const erroredHashesRef = useRef<Set<string>>(new Set());\n const batchTimerRef = useRef<NodeJS.Timeout | null>(null);\n\n // Use ref to track translations to avoid stale closures\n const translationsRef = useRef<Record<string, string>>(initialTranslations);\n const localeRef = useRef(locale);\n\n useEffect(() => {\n translationsRef.current = translations;\n }, [translations]);\n\n useEffect(() => {\n localeRef.current = locale;\n }, [locale]);\n\n /**\n * Update HTML lang attribute when locale changes\n * This ensures screen readers and SEO understand the page language\n */\n useEffect(() => {\n if (typeof document !== \"undefined\") {\n document.documentElement.lang = locale;\n }\n }, [locale]);\n\n /**\n * Register a hash as being used in a component\n * Called during render - must not trigger state updates immediately\n */\n const registerHashes = useCallback((hashes: string[]) => {\n let wasNew = false;\n hashes.forEach((hash) => {\n wasNew = wasNew || !registeredHashesRef.current.has(hash);\n registeredHashesRef.current.add(hash);\n });\n\n logger.debug(\n `Registering hashes: ${hashes.join(\", \")}. Registered hashes: ${registeredHashesRef.current.values()}. wasNew: ${wasNew}`,\n );\n\n // Schedule a state update for the next tick to track all hashes\n if (wasNew) {\n setAllSeenHashes((prev) => {\n const next = prev.union(new Set(hashes));\n // TODO (AleksandrSl 25/11/2025): Should be a cheaper solution\n logger.debug(`New allSeenHashes: ${[...next.values()]}`);\n return next;\n });\n }\n }, []);\n\n /**\n * Check for missing translations and request them (batched)\n * This runs when allSeenHashes changes (hot reload or new components mount)\n */\n useEffect(() => {\n logger.debug(\n `WeglotProvider checking translations for locale ${locale}, seen hashes: ${allSeenHashes.size}`,\n );\n\n // The source locale has no dictionary; asking would mark every hash failed\n // and stop it being fetched for later locales.\n if (locale === sourceLocale) {\n return;\n }\n\n // Find hashes that are seen but not translated and not already pending\n const missingHashes: string[] = [];\n logger.debug(\n \"allSeenHashes: \",\n [...allSeenHashes.values()],\n [...pendingHashesRef.current.values()],\n );\n for (const hash of allSeenHashes) {\n if (\n !translations[hash] &&\n !pendingHashesRef.current.has(hash) &&\n !erroredHashesRef.current.has(hash)\n ) {\n missingHashes.push(hash);\n pendingHashesRef.current.add(hash);\n }\n }\n logger.debug(\"Missing hashes: \", missingHashes.join(\",\"));\n\n // If no missing hashes, nothing to do\n if (missingHashes.length === 0 && localeRef.current == locale) return;\n\n logger.debug(\n `Requesting translations for ${missingHashes.length} hashes in locale ${locale}`,\n );\n\n // Cancel existing timer\n if (batchTimerRef.current) {\n clearTimeout(batchTimerRef.current);\n }\n\n // Batch the request\n batchTimerRef.current = setTimeout(async () => {\n const hashesToFetch = Array.from(pendingHashesRef.current);\n pendingHashesRef.current.clear();\n\n logger.debug(`Fetching translations for ${hashesToFetch.length} hashes`);\n if (hashesToFetch.length === 0) return;\n\n setIsLoading(true);\n try {\n const newTranslations = await fetchTranslations(\n localeRef.current,\n hashesToFetch,\n serverUrl,\n );\n\n logger.debug(\n `Fetched translations for ${hashesToFetch.length} hashes:`,\n newTranslations,\n );\n\n const receivedHashes = new Set(Object.keys(newTranslations));\n const missingHashes = hashesToFetch.filter(\n (hash) => !receivedHashes.has(hash),\n );\n\n if (missingHashes.length > 0) {\n logger.warn(\n `Server did not return translations for ${missingHashes.length} hashes: ${missingHashes.join(\", \")}`,\n );\n for (const hash of missingHashes) {\n erroredHashesRef.current.add(hash);\n }\n }\n\n setTranslations((prev) => ({ ...prev, ...newTranslations }));\n for (const hash of hashesToFetch) {\n registeredHashesRef.current.add(hash);\n }\n } catch (error) {\n logger.warn(\n `Failed to fetch translations from translation server: ${error}.`,\n );\n // Remove from pending so they can be retried\n for (const hash of hashesToFetch) {\n pendingHashesRef.current.delete(hash);\n erroredHashesRef.current.add(hash);\n }\n } finally {\n setIsLoading(false);\n }\n }, BATCH_DELAY);\n }, [allSeenHashes, locale, translations]);\n\n /**\n * Clear batch timer on unmount\n */\n useEffect(() => {\n return () => {\n if (batchTimerRef.current) {\n clearTimeout(batchTimerRef.current);\n }\n };\n }, []);\n\n /**\n * Change locale and load translations dynamically\n */\n const setLocale = useCallback(\n async (newLocale: LocaleCode) => {\n // 1. Persist to cookie (unless disabled)\n persistLocale(newLocale);\n\n // 2. Update state\n setLocaleState(newLocale);\n\n // 3. Reload Server Components (if router provided)\n if (router) {\n router.refresh();\n }\n\n setIsLoading(true);\n const startTime = performance.now();\n\n try {\n logger.info(\n `Fetching translations for locale: ${newLocale}. Server url: ${serverUrl}`,\n );\n\n // Everything on the page in one request; later mounts go through batching.\n const hashes = [...registeredHashesRef.current];\n pendingHashesRef.current.clear();\n // A hash that failed for one locale may well exist for the next.\n erroredHashesRef.current.clear();\n\n const newTranslations = hashes.length\n ? await fetchTranslations(newLocale, hashes, serverUrl)\n : {};\n\n const endTime = performance.now();\n logger.info(\n `Translation fetch complete for ${newLocale} in ${(endTime - startTime).toFixed(2)}ms`,\n );\n\n logger.debug(`Translations loaded for ${newLocale}:`, newTranslations);\n\n // Replace rather than merge: entries of the previous locale must go.\n setTranslations(newTranslations);\n } catch (error) {\n logger.error(`Failed to load translations for ${newLocale}:`, error);\n // Clear translations on error - components will request individually\n setTranslations({});\n } finally {\n setIsLoading(false);\n }\n },\n [router],\n );\n\n // TODO (AleksandrSl 24/11/2025): Should I memo the value?\n return (\n <WeglotContext.Provider\n value={{\n locale,\n setLocale,\n translations,\n registerHashes,\n isLoading,\n sourceLocale,\n }}\n >\n {children}\n </WeglotContext.Provider>\n );\n}\n"],"mappings":";;;;;;;;;;;AAmBA,MAAM,aAAa;AAwBnB,MAAM,SAAS,QAAQ,IAAI,aAAa;AACxC,MAAM,cAAc;;;;;;;;;;;;;;;;;;;;;;;;;AA2BpB,MAAa,iBAAiB,SAAS,sBAAsB;AAE7D,SAAS,qBAAqB,EAC5B,eACA,sBAAsB,EAAE,EACxB,QACA,YACsB;CAEtB,MAAM,CAAC,QAAQ,kBAAkB,eAA2B;AAC1D,MAAI,cAAe,QAAO;AAE1B,MAAI,OAAO,WAAW,YACpB,QAAO,iBAAiB;AAE1B,SAAO;GACP;CACF,MAAM,CAAC,cAAc,mBACnB,SAAiC,oBAAoB;CACvD,MAAM,CAAC,WAAW,gBAAgB,SAAS,MAAM;AAEjD,QAAO,MACL,2CAA2C,UAC3C,oBACD;;;;;AAMD,iBAAgB;AACd,MAAI,OAAO,aAAa,YACtB,UAAS,gBAAgB,OAAO;IAEjC,CAAC,OAAO,CAAC;;;;;CAMZ,MAAM,mBAAmB,YACvB,OAAO,iBAA6B;AAElC,MAAI,OAAO,KAAK,oBAAoB,CAAC,SAAS,EAC5C;AAGF,eAAa,KAAK;AAClB,MAAI;GACF,MAAM,WAAW,MAAM,MAAM,iBAAiB,aAAa,OAAO;AAClE,OAAI,CAAC,SAAS,GACZ,OAAM,IAAI,MACR,mCAAmC,aAAa,IAAI,SAAS,aAC9D;GAGH,MAAM,OAA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QAAO,SAAS;AAGlB,eAAa,KAAK;EAClB,MAAM,YAAY,YAAY,KAAK;AAEnC,MAAI;AACF,UAAO,KACL,qCAAqC,UAAU,gBAAgB,YAChE;GAGD,MAAM,SAAS,CAAC,GAAG,oBAAoB,QAAQ;AAC/C,oBAAiB,QAAQ,OAAO;AAEhC,oBAAiB,QAAQ,OAAO;GAEhC,MAAM,kBAAkB,OAAO,SAC3B,MAAM,kBAAkB,WAAW,QAAQ,UAAU,GACrD,EAAE;GAEN,MAAM,UAAU,YAAY,KAAK;AACjC,UAAO,KACL,kCAAkC,UAAU,OAAO,UAAU,WAAW,QAAQ,EAAE,CAAC,IACpF;AAED,UAAO,MAAM,2BAA2B,UAAU,IAAI,gBAAgB;AAGtE,mBAAgB,gBAAgB;WACzB,OAAO;AACd,UAAO,MAAM,mCAAmC,UAAU,IAAI,MAAM;AAEpE,mBAAgB,EAAE,CAAC;YACX;AACR,gBAAa,MAAM;;IAGvB,CAAC,OAAO,CACT;AAGD,QACE,oBAAC,cAAc;EACb,OAAO;GACL;GACA;GACA;GACA;GACA;GACA;GACD;EAEA;GACsB"}
|
|
1
|
+
{"version":3,"file":"WeglotProvider.mjs","names":["missingHashes: string[]","missingHashes"],"sources":["../../../src/react/shared/WeglotProvider.tsx"],"sourcesContent":["\"use client\";\n\nimport {\n type PropsWithChildren,\n useCallback,\n useEffect,\n useRef,\n useState,\n} from \"react\";\nimport { logger } from \"../../utils/logger\";\nimport { fetchTranslations } from \"./utils\";\nimport { serverUrl, sourceLocale } from \"@weglot/translate-react/virtual/config\";\nimport {\n getClientLocale,\n persistLocale,\n} from \"@weglot/translate-react/virtual/locale/client\";\nimport { WeglotContext } from \"./WeglotContext\";\nimport type { LocaleCode } from \"../../locale\";\n\nconst noop = () => {};\n\n/**\n * Translation provider props\n */\nexport type WeglotProviderProps = PropsWithChildren<{\n /**\n * Initial locale to use\n */\n initialLocale?: LocaleCode;\n\n /**\n * Initial translations (pre-loaded)\n */\n initialTranslations?: Record<string, string>;\n\n /**\n * Optional router instance for Next.js integration\n * If provided, calls router.refresh() after locale change\n * This ensures Server Components re-render with new locale\n */\n router?: { refresh: () => void };\n}>;\n\nconst IS_DEV = process.env.NODE_ENV === \"development\";\nconst BATCH_DELAY = 200;\n\n/**\n * Translation Provider Component\n *\n * Wraps your app to provide translation context to all components.\n * Handles locale switching and on-demand translation loading.\n *\n * @example\n * ```tsx\n * // In your root layout\n * import { WeglotProvider } from '@weglot/translate-react/react';\n *\n * export default function RootLayout({ children }) {\n * return (\n * <html>\n * <body>\n * <WeglotProvider initialLocale=\"en\">\n * {children}\n * </WeglotProvider>\n * </body>\n * </html>\n * );\n * }\n * ```\n */\n// Export the appropriate provider directly\nexport const WeglotProvider = IS_DEV ? WeglotProvider__Dev : WeglotProvider__Prod;\n\nfunction WeglotProvider__Prod({\n initialLocale,\n initialTranslations = {},\n router,\n children,\n}: WeglotProviderProps) {\n // Use client locale detection if no initialLocale provided\n const [locale, setLocaleState] = useState<LocaleCode>(() => {\n if (initialLocale) return initialLocale;\n // Only detect on client-side (not during SSR)\n if (typeof window !== \"undefined\") {\n return getClientLocale();\n }\n return sourceLocale;\n });\n const [translations, setTranslations] =\n useState<Record<string, string>>(initialTranslations);\n const [isLoading, setIsLoading] = useState(false);\n\n logger.debug(\n `WeglotProvider initialized with locale: ${locale}`,\n initialTranslations,\n );\n\n /**\n * Update HTML lang attribute when locale changes\n * This ensures screen readers and SEO understand the page language\n */\n useEffect(() => {\n if (typeof document !== \"undefined\") {\n document.documentElement.lang = locale;\n }\n }, [locale]);\n\n /**\n * Load translations from public/translations/{locale}.json\n * Lazy loads on-demand for SPAs\n */\n const loadTranslations = useCallback(\n async (targetLocale: LocaleCode) => {\n // If we already have initialTranslations (Next.js SSR), don't fetch\n if (Object.keys(initialTranslations).length > 0) {\n return;\n }\n\n if (targetLocale === sourceLocale) {\n setTranslations({});\n return;\n }\n\n setIsLoading(true);\n try {\n const response = await fetch(`/translations/${targetLocale}.json`);\n if (!response.ok) {\n throw new Error(\n `Failed to load translations for ${targetLocale}: ${response.statusText}`,\n );\n }\n\n const data = await response.json();\n // Translation files have format: { version, locale, entries: {...} }\n setTranslations(data.entries || data);\n logger.debug(\n `Loaded translations for ${targetLocale}:`,\n Object.keys(data.entries || data).length,\n );\n } catch (error) {\n logger.error(`Failed to load translations for ${targetLocale}:`, error);\n // Fallback to empty translations\n setTranslations({});\n } finally {\n setIsLoading(false);\n }\n },\n [initialTranslations],\n );\n\n // Load translations on mount if not provided via initialTranslations\n useEffect(() => {\n if (Object.keys(initialTranslations).length === 0) {\n loadTranslations(locale);\n }\n }, []); // Only run on mount\n\n useEffect(() => {\n // TODO (AleksandrSl 08/12/2025): More elegant solution required.\n // This is used to update the client part when next app changes locale\n if (router) {\n setTranslations(initialTranslations);\n }\n }, [initialTranslations, router]);\n\n /**\n * Change locale\n * - For Next.js SSR: triggers server re-render via router.refresh()\n * - For SPAs: lazy loads translations from /translations/{locale}.json\n */\n const setLocale = useCallback(\n async (newLocale: LocaleCode) => {\n // 1. Persist to cookie so server can read it on next render\n persistLocale(newLocale);\n\n // 2. Update local state for immediate UI feedback\n setLocaleState(newLocale);\n\n // 3a. Next.js pattern: Trigger server re-render\n if (router) {\n router.refresh();\n }\n // 3b. SPA pattern: Lazy load translations\n else {\n await loadTranslations(newLocale);\n }\n },\n [router, loadTranslations],\n );\n\n return (\n <WeglotContext.Provider\n value={{\n locale,\n setLocale,\n translations,\n registerHashes: noop,\n isLoading,\n sourceLocale,\n }}\n >\n {children}\n </WeglotContext.Provider>\n );\n}\n\nfunction WeglotProvider__Dev({\n initialLocale,\n initialTranslations = {},\n router,\n children,\n}: WeglotProviderProps) {\n // Use client locale detection if no initialLocale provided\n const [locale, setLocaleState] = useState(() => {\n if (initialLocale) {\n return initialLocale;\n }\n return getClientLocale();\n });\n const [translations, setTranslations] =\n useState<Record<string, string>>(initialTranslations);\n const [isLoading, setIsLoading] = useState(false);\n\n const [allSeenHashes, setAllSeenHashes] = useState<Set<string>>(new Set());\n const registeredHashesRef = useRef<Set<string>>(new Set());\n const pendingHashesRef = useRef<Set<string>>(new Set());\n const erroredHashesRef = useRef<Set<string>>(new Set());\n const batchTimerRef = useRef<NodeJS.Timeout | null>(null);\n\n // Use ref to track translations to avoid stale closures\n const translationsRef = useRef<Record<string, string>>(initialTranslations);\n const localeRef = useRef(locale);\n\n useEffect(() => {\n translationsRef.current = translations;\n }, [translations]);\n\n useEffect(() => {\n localeRef.current = locale;\n }, [locale]);\n\n /**\n * Update HTML lang attribute when locale changes\n * This ensures screen readers and SEO understand the page language\n */\n useEffect(() => {\n if (typeof document !== \"undefined\") {\n document.documentElement.lang = locale;\n }\n }, [locale]);\n\n /**\n * Register a hash as being used in a component\n * Called during render - must not trigger state updates immediately\n */\n const registerHashes = useCallback((hashes: string[]) => {\n let wasNew = false;\n hashes.forEach((hash) => {\n wasNew = wasNew || !registeredHashesRef.current.has(hash);\n registeredHashesRef.current.add(hash);\n });\n\n logger.debug(\n `Registering hashes: ${hashes.join(\", \")}. Registered hashes: ${registeredHashesRef.current.values()}. wasNew: ${wasNew}`,\n );\n\n // Schedule a state update for the next tick to track all hashes\n if (wasNew) {\n setAllSeenHashes((prev) => {\n const next = prev.union(new Set(hashes));\n // TODO (AleksandrSl 25/11/2025): Should be a cheaper solution\n logger.debug(`New allSeenHashes: ${[...next.values()]}`);\n return next;\n });\n }\n }, []);\n\n /**\n * Check for missing translations and request them (batched)\n * This runs when allSeenHashes changes (hot reload or new components mount)\n */\n useEffect(() => {\n logger.debug(\n `WeglotProvider checking translations for locale ${locale}, seen hashes: ${allSeenHashes.size}`,\n );\n\n // The source locale has no dictionary; asking would mark every hash failed\n // and stop it being fetched for later locales.\n if (locale === sourceLocale) {\n return;\n }\n\n // Find hashes that are seen but not translated and not already pending\n const missingHashes: string[] = [];\n logger.debug(\n \"allSeenHashes: \",\n [...allSeenHashes.values()],\n [...pendingHashesRef.current.values()],\n );\n for (const hash of allSeenHashes) {\n if (\n !translations[hash] &&\n !pendingHashesRef.current.has(hash) &&\n !erroredHashesRef.current.has(hash)\n ) {\n missingHashes.push(hash);\n pendingHashesRef.current.add(hash);\n }\n }\n logger.debug(\"Missing hashes: \", missingHashes.join(\",\"));\n\n // If no missing hashes, nothing to do\n if (missingHashes.length === 0 && localeRef.current == locale) return;\n\n logger.debug(\n `Requesting translations for ${missingHashes.length} hashes in locale ${locale}`,\n );\n\n // Cancel existing timer\n if (batchTimerRef.current) {\n clearTimeout(batchTimerRef.current);\n }\n\n // Batch the request\n batchTimerRef.current = setTimeout(async () => {\n const hashesToFetch = Array.from(pendingHashesRef.current);\n pendingHashesRef.current.clear();\n\n logger.debug(`Fetching translations for ${hashesToFetch.length} hashes`);\n if (hashesToFetch.length === 0) return;\n\n setIsLoading(true);\n try {\n const newTranslations = await fetchTranslations(\n localeRef.current,\n hashesToFetch,\n serverUrl,\n );\n\n logger.debug(\n `Fetched translations for ${hashesToFetch.length} hashes:`,\n newTranslations,\n );\n\n const receivedHashes = new Set(Object.keys(newTranslations));\n const missingHashes = hashesToFetch.filter(\n (hash) => !receivedHashes.has(hash),\n );\n\n if (missingHashes.length > 0) {\n logger.warn(\n `Server did not return translations for ${missingHashes.length} hashes: ${missingHashes.join(\", \")}`,\n );\n for (const hash of missingHashes) {\n erroredHashesRef.current.add(hash);\n }\n }\n\n setTranslations((prev) => ({ ...prev, ...newTranslations }));\n for (const hash of hashesToFetch) {\n registeredHashesRef.current.add(hash);\n }\n } catch (error) {\n logger.warn(\n `Failed to fetch translations from translation server: ${error}.`,\n );\n // Remove from pending so they can be retried\n for (const hash of hashesToFetch) {\n pendingHashesRef.current.delete(hash);\n erroredHashesRef.current.add(hash);\n }\n } finally {\n setIsLoading(false);\n }\n }, BATCH_DELAY);\n }, [allSeenHashes, locale, translations]);\n\n /**\n * Clear batch timer on unmount\n */\n useEffect(() => {\n return () => {\n if (batchTimerRef.current) {\n clearTimeout(batchTimerRef.current);\n }\n };\n }, []);\n\n /**\n * Change locale and load translations dynamically\n */\n const setLocale = useCallback(\n async (newLocale: LocaleCode) => {\n // 1. Persist to cookie (unless disabled)\n persistLocale(newLocale);\n\n // 2. Update state\n setLocaleState(newLocale);\n\n // 3. Reload Server Components (if router provided)\n if (router) {\n router.refresh();\n }\n\n setIsLoading(true);\n const startTime = performance.now();\n\n try {\n logger.info(\n `Fetching translations for locale: ${newLocale}. Server url: ${serverUrl}`,\n );\n\n // Everything on the page in one request; later mounts go through batching.\n const hashes = [...registeredHashesRef.current];\n pendingHashesRef.current.clear();\n // A hash that failed for one locale may well exist for the next.\n erroredHashesRef.current.clear();\n\n const newTranslations = hashes.length\n ? await fetchTranslations(newLocale, hashes, serverUrl)\n : {};\n\n const endTime = performance.now();\n logger.info(\n `Translation fetch complete for ${newLocale} in ${(endTime - startTime).toFixed(2)}ms`,\n );\n\n logger.debug(`Translations loaded for ${newLocale}:`, newTranslations);\n\n // Replace rather than merge: entries of the previous locale must go.\n setTranslations(newTranslations);\n } catch (error) {\n logger.error(`Failed to load translations for ${newLocale}:`, error);\n // Clear translations on error - components will request individually\n setTranslations({});\n } finally {\n setIsLoading(false);\n }\n },\n [router],\n );\n\n // TODO (AleksandrSl 24/11/2025): Should I memo the value?\n return (\n <WeglotContext.Provider\n value={{\n locale,\n setLocale,\n translations,\n registerHashes,\n isLoading,\n sourceLocale,\n }}\n >\n {children}\n </WeglotContext.Provider>\n );\n}\n"],"mappings":";;;;;;;;;;;AAmBA,MAAM,aAAa;AAwBnB,MAAM,SAAS,QAAQ,IAAI,aAAa;AACxC,MAAM,cAAc;;;;;;;;;;;;;;;;;;;;;;;;;AA2BpB,MAAa,iBAAiB,SAAS,sBAAsB;AAE7D,SAAS,qBAAqB,EAC5B,eACA,sBAAsB,EAAE,EACxB,QACA,YACsB;CAEtB,MAAM,CAAC,QAAQ,kBAAkB,eAA2B;AAC1D,MAAI,cAAe,QAAO;AAE1B,MAAI,OAAO,WAAW,YACpB,QAAO,iBAAiB;AAE1B,SAAO;GACP;CACF,M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EA;GACsB"}
|
package/build/types.d.cts
CHANGED
|
@@ -29,7 +29,7 @@ type LocalePersistenceConfig = {
|
|
|
29
29
|
* Fields that are resolved internally (from the Weglot project settings or the
|
|
30
30
|
* environment) rather than provided by users.
|
|
31
31
|
*/
|
|
32
|
-
type WeglotInternalFields = "environment" | "cacheType" | "sourceLocale" | "targetLocales" | "apiLocales" | "translationEngine" | "apiBaseUrl" | "weglotDir";
|
|
32
|
+
type WeglotInternalFields = "environment" | "cacheType" | "sourceLocale" | "targetLocales" | "apiLocales" | "translationEngine" | "apiBaseUrl" | "weglotDir" | "metadataDir";
|
|
33
33
|
/**
|
|
34
34
|
* Configuration for @weglot/translate-react
|
|
35
35
|
*/
|
|
@@ -56,6 +56,12 @@ type WeglotConfig = {
|
|
|
56
56
|
* @internal
|
|
57
57
|
*/
|
|
58
58
|
weglotDir: string;
|
|
59
|
+
/**
|
|
60
|
+
* Overrides where the metadata database lives.
|
|
61
|
+
*
|
|
62
|
+
* @internal
|
|
63
|
+
*/
|
|
64
|
+
metadataDir?: string;
|
|
59
65
|
/**
|
|
60
66
|
* Environment mode
|
|
61
67
|
* Determines metadata file naming and translator behavior
|
package/build/types.d.cts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.d.cts","names":[],"sources":["../src/types.ts"],"sourcesContent":[],"mappings":";;;;AA2BA;AAMA;
|
|
1
|
+
{"version":3,"file":"types.d.cts","names":[],"sources":["../src/types.ts"],"sourcesContent":[],"mappings":";;;;AA2BA;AAMA;AAcA;AACO,UAvCU,YAAA,CAuCV;EAAc;;;;EADa,IAAA,EAAA,MAAA;EAAO;AAMzC;AAKA;;EAoDgB,MAAA,EAAA,MAAA;;;;;;AAkE4B,KArJhC,uBAAA,GAqJgC;;UArJoB;;;;;;KAMpD,oBAAA;;;;KAcA,mBAAA,GAAsB,QAChC,KAAK,cAAc;OACZ,QAAQ;;KAIL,iBAAA;;;;KAKA,YAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;eAiCG;;;;;;;;;;;;;;;;;gBAmBC;;;;;;;;iBASC;;;cAIH,eAAe;;;;;;;;;;;;;;;;;;;;;;0BA2BH;;;;;;;;;;;;;;;;;;;;;;;qBA0BL"}
|
package/build/types.d.mts
CHANGED
|
@@ -29,7 +29,7 @@ type LocalePersistenceConfig = {
|
|
|
29
29
|
* Fields that are resolved internally (from the Weglot project settings or the
|
|
30
30
|
* environment) rather than provided by users.
|
|
31
31
|
*/
|
|
32
|
-
type WeglotInternalFields = "environment" | "cacheType" | "sourceLocale" | "targetLocales" | "apiLocales" | "translationEngine" | "apiBaseUrl" | "weglotDir";
|
|
32
|
+
type WeglotInternalFields = "environment" | "cacheType" | "sourceLocale" | "targetLocales" | "apiLocales" | "translationEngine" | "apiBaseUrl" | "weglotDir" | "metadataDir";
|
|
33
33
|
/**
|
|
34
34
|
* Configuration for @weglot/translate-react
|
|
35
35
|
*/
|
|
@@ -56,6 +56,12 @@ type WeglotConfig = {
|
|
|
56
56
|
* @internal
|
|
57
57
|
*/
|
|
58
58
|
weglotDir: string;
|
|
59
|
+
/**
|
|
60
|
+
* Overrides where the metadata database lives.
|
|
61
|
+
*
|
|
62
|
+
* @internal
|
|
63
|
+
*/
|
|
64
|
+
metadataDir?: string;
|
|
59
65
|
/**
|
|
60
66
|
* Environment mode
|
|
61
67
|
* Determines metadata file naming and translator behavior
|
package/build/types.d.mts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.d.mts","names":[],"sources":["../src/types.ts"],"sourcesContent":[],"mappings":";;;;AA2BA;AAMA;
|
|
1
|
+
{"version":3,"file":"types.d.mts","names":[],"sources":["../src/types.ts"],"sourcesContent":[],"mappings":";;;;AA2BA;AAMA;AAcA;AACO,UAvCU,YAAA,CAuCV;EAAc;;;;EADa,IAAA,EAAA,MAAA;EAAO;AAMzC;AAKA;;EAoDgB,MAAA,EAAA,MAAA;;;;;;AAkE4B,KArJhC,uBAAA,GAqJgC;;UArJoB;;;;;;KAMpD,oBAAA;;;;KAcA,mBAAA,GAAsB,QAChC,KAAK,cAAc;OACZ,QAAQ;;KAIL,iBAAA;;;;KAKA,YAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;eAiCG;;;;;;;;;;;;;;;;;gBAmBC;;;;;;;;iBASC;;;cAIH,eAAe;;;;;;;;;;;;;;;;;;;;;;0BA2BH;;;;;;;;;;;;;;;;;;;;;;;qBA0BL"}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
const require_rolldown_runtime = require('../_virtual/rolldown_runtime.cjs');
|
|
2
|
+
let node_fs = require("node:fs");
|
|
3
|
+
|
|
4
|
+
//#region src/utils/package-version.ts
|
|
5
|
+
let version;
|
|
6
|
+
function packageVersion() {
|
|
7
|
+
version ??= JSON.parse((0, node_fs.readFileSync)(new URL("../../package.json", require("url").pathToFileURL(__filename).href), "utf8")).version;
|
|
8
|
+
return version;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
//#endregion
|
|
12
|
+
exports.packageVersion = packageVersion;
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { readFileSync } from "node:fs";
|
|
2
|
+
|
|
3
|
+
//#region src/utils/package-version.ts
|
|
4
|
+
let version;
|
|
5
|
+
function packageVersion() {
|
|
6
|
+
version ??= JSON.parse(readFileSync(new URL("../../package.json", import.meta.url), "utf8")).version;
|
|
7
|
+
return version;
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
//#endregion
|
|
11
|
+
export { packageVersion };
|
|
12
|
+
//# sourceMappingURL=package-version.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"package-version.mjs","names":["version: string | undefined"],"sources":["../../src/utils/package-version.ts"],"sourcesContent":["import { readFileSync } from \"node:fs\";\n\nlet version: string | undefined;\n\nexport function packageVersion(): string {\n version ??= JSON.parse(\n readFileSync(new URL(\"../../package.json\", import.meta.url), \"utf8\"),\n ).version as string;\n return version;\n}\n"],"mappings":";;;AAEA,IAAIA;AAEJ,SAAgB,iBAAyB;AACvC,aAAY,KAAK,MACf,aAAa,IAAI,IAAI,sBAAsB,OAAO,KAAK,IAAI,EAAE,OAAO,CACrE,CAAC;AACF,QAAO"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@weglot/translate-react",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.2",
|
|
4
4
|
"description": "Automatic Weglot translation for React and Next.js apps, detected from your JSX at build time",
|
|
5
5
|
"sideEffects": false,
|
|
6
6
|
"type": "module",
|
|
@@ -190,9 +190,10 @@
|
|
|
190
190
|
"scripts": {
|
|
191
191
|
"dev": "tsdown --watch",
|
|
192
192
|
"build": "pnpm typecheck && tsdown",
|
|
193
|
-
"typecheck": "tsc --noEmit",
|
|
193
|
+
"typecheck": "tsc --noEmit && tsc -p e2e/tsconfig.json",
|
|
194
194
|
"clean": "rm -rf build",
|
|
195
195
|
"test": "vitest --run",
|
|
196
|
+
"test:e2e": "vitest --run --config vitest.e2e.config.ts",
|
|
196
197
|
"sync-definitions": "node scripts/sync-definitions.ts",
|
|
197
198
|
"check-definitions": "node scripts/sync-definitions.ts --check",
|
|
198
199
|
"test:watch": "vitest -w",
|
|
@@ -232,6 +233,7 @@
|
|
|
232
233
|
"@types/react-dom": "19.2.3",
|
|
233
234
|
"jsdom": "30.0.1",
|
|
234
235
|
"next": "16.2.9",
|
|
236
|
+
"playwright": "1.64.1",
|
|
235
237
|
"tsdown": "0.18.2",
|
|
236
238
|
"typescript": "5.9.3",
|
|
237
239
|
"vitest": "4.1.0"
|