From 5e9c1145f70c9d3f2d58afd0d6385a255d984185 Mon Sep 17 00:00:00 2001 From: rubinbasha Date: Mon, 9 Nov 2026 18:37:47 +0100 Subject: [PATCH] feat: target the published ReRune SDK 1.9.0 Every example moves from @rerune/* 1.8.0 to 1.9.0. React and Expo call the synchronous ReRune.setup at module scope with the default cache store and render ReRuneProvider at once; Angular registers ReRune.setup (renamed from ReRune.provide) and imports no type from the internal @rerune/core, which angular-shared no longer declares. The Angular apps drop the variant save and staging error alerts that 1.9.0 made unreachable. Expo adds the @formatjs/intl-pluralrules polyfill that the 1.9.0 notes ask for on Hermes, and its first screen waits for the remembered-language read. Partial refresh feedback shows no empty language list, the consumer and browser tests follow 1.9.0 behavior, and the READMEs and CONTRIBUTING describe the 1.9.0 API. Co-Authored-By: Claude Opus 5.5 --- CONTRIBUTING.md | 8 +- README.md | 18 +- examples/angular-ngx-translate/README.md | 30 +-- examples/angular-ngx-translate/package.json | 2 +- examples/angular-ngx-translate/src/app.html | 2 - examples/angular-ngx-translate/src/app.ts | 2 +- examples/angular-shared/package.json | 3 +- examples/angular-shared/presentation.ts | 25 +-- examples/angular-transloco/README.md | 30 +-- examples/angular-transloco/package.json | 2 +- examples/angular-transloco/src/app.html | 2 - examples/angular-transloco/src/app.ts | 2 +- examples/react-native-expo/App.tsx | 34 ++-- examples/react-native-expo/README.md | 51 +++--- examples/react-native-expo/index.ts | 12 ++ examples/react-native-expo/package.json | 3 +- examples/react-native-expo/src/Chapter.tsx | 15 +- examples/react-native-expo/src/i18n.ts | 14 +- examples/react-web-vite/README.md | 39 ++-- examples/react-web-vite/package.json | 2 +- examples/react-web-vite/src/App.tsx | 12 +- examples/react-web-vite/src/i18n.ts | 6 +- examples/react-web-vite/src/main.tsx | 17 +- examples/shared/messages.ts | 5 - examples/shared/refresh.ts | 14 +- pnpm-lock.yaml | 94 ++++++---- scripts/refresh.test.mjs | 10 + scripts/sdk-consumer.test.mjs | 191 +++++++++++++++----- tests/browser/ota.spec.ts | 23 ++- 29 files changed, 403 insertions(+), 265 deletions(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 2d67690..289bee6 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -17,7 +17,7 @@ CI=true EXPO_NO_TELEMETRY=1 pnpm export:android CI=true EXPO_NO_TELEMETRY=1 pnpm export:ios ``` -`check:dependencies` verifies the public SDK registry versions and lockfile integrity, rejects local SDK links and source aliases, and checks that app dependencies, imports, and asset paths resolve inside the checkout. It needs access to public npm. The Node tests protect dependency boundaries, refresh-result classification, and the installed SDK's late-resource and cache-write behavior. Expo's `typecheck` and Android/iOS exports are separate from native device testing. +`check:dependencies` verifies the public SDK registry versions and lockfile integrity, rejects local SDK links and source aliases, and checks that app dependencies, imports, and asset paths resolve inside the checkout. It needs access to public npm. The Node tests protect dependency boundaries, refresh-result classification against the installed SDK's update results (including removed and renamed languages), synchronous setup and its native-initialization order, and the installed SDK's late-resource and default-store cache-write behavior. Expo's `typecheck` and Android/iOS exports are separate from native device testing. ## Browser tests @@ -35,15 +35,15 @@ The TypeScript suites live in `tests/browser/`. Playwright starts and stops Vite Use `pnpm exec playwright test --project=browser --grep "ngx"` for a focused run. The root `pnpm typecheck` also checks the tests and runner configuration. -The browser suite uses the installed SDK and native translation engines. Request interception supplies deterministic manifests and locale records. It covers bundled startup, OTA rendering, locale changes, Main/vip persistence, staging request parameters and mode switches, interpolation, cardinal plurals, failed-request cache restoration, partial updates, unchanged content with a failed locale, reading-state retention, duplicate refresh guards, and the fixed interpolation date. Angular-specific checks include native MessageFormat, late application writes, and restoring bundled copy after OTA removal. +The browser suite uses the installed SDK and native translation engines. Request interception supplies deterministic manifests and locale records. It covers bundled startup, OTA rendering, checks limited to the shown language and its fallback, locale changes that download without a manifest request, Main/vip persistence, staging request parameters and mode switches, interpolation, cardinal plurals, failed-request cache restoration, partial updates, unchanged content with a failed locale, reading-state retention, duplicate refresh guards, and the fixed interpolation date. Angular-specific checks include native MessageFormat, late application writes, and restoring bundled copy after OTA removal. The parity suite blocks hosted requests and compares React with both Angular adapters on English/German library, Discover, Saved, settings, both chapters, and completion screens. It checks rendered text, selected styles, and geometry within one CSS pixel at 1440x1050 and 390x844. The interaction suite additionally checks 320px widths, 150% German text, all five bundled languages, direct reader links, and scroll retention. Review screenshots as well. These checks do not prove native, Safari, or Firefox behavior. ## Sharing assets and status logic -The apps share example-owned catalogs, story state, reading CSS, fonts, and brand assets under `examples/shared/`. No app imports another app's source. Web, Angular, and Expo share stable story IDs and the pure session reducer; covers are SVG in the browser and native SVG views in Expo. Keep those relative paths aligned. Web builds and Expo exports copy both font license notices into their output; Angular copies them through its asset configuration. `angular-shared` converts bundled interpolation and plurals into native MessageFormat syntax; its private workspace manifest resolves Angular decorators and the exact public core SDK. Its tsconfig extends the repository base and enables Angular legacy decorators. `examples/shared/refresh.ts` contains only application-owned check status text and result classification. Expo's Metro configuration explicitly watches that shared source folder. These are example assets and UI helpers; the SDK implementation comes entirely from npm. +The apps share example-owned catalogs, story state, reading CSS, fonts, and brand assets under `examples/shared/`. No app imports another app's source. Web, Angular, and Expo share stable story IDs and the pure session reducer; covers are SVG in the browser and native SVG views in Expo. Keep those relative paths aligned. Web builds and Expo exports copy both font license notices into their output; Angular copies them through its asset configuration. `angular-shared` converts bundled interpolation and plurals into native MessageFormat syntax; its private workspace manifest resolves Angular decorators; it imports no SDK package, because `@rerune/core` is internal since 1.9.0. Its tsconfig extends the repository base and enables Angular legacy decorators. `examples/shared/refresh.ts` contains only application-owned check status text and result classification. Expo's Metro configuration explicitly watches that shared source folder. These are example assets and UI helpers; the SDK implementation comes entirely from npm. -Keep asynchronous `ReRune.setup(otaOptions, i18nOptions)` and one `ReRuneProvider` for React/React Native. Keep engine-specific `ReRune.provide(otaOptions, nativeOptions)` for Angular, with separate plugin providers in their native order. Do not add SDK transport, response normalization, runtime shims, or framework abstractions to these apps. +Keep one synchronous `ReRune.setup(otaOptions, i18nOptions)` call at module scope and one `ReRuneProvider` for React/React Native, without a translation loading gate (Expo's first screen waits only for its fonts and the remembered-language read); Expo keeps its setup in its own module because React Native setup starts the cache restore and update check at once. Keep engine-specific `ReRune.setup(otaOptions, nativeOptions)` in the Angular root providers, with separate plugin providers in their native order. Use the SDK's default cache stores, and import SDK APIs and types from the framework packages, not `@rerune/core`. Do not add SDK transport, response normalization, runtime shims, or framework abstractions to these apps. Angular's native build cache is disabled in both apps. CI-mode production builds were verified. Cache-enabled LMDB operation remains unverified. The existing MessageFormat CommonJS and Angular/Vite development-tool peer warnings do not establish a runtime failure. diff --git a/README.md b/README.md index bc9abd1..73a30fc 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # ReRune examples -A standalone consumer repository for trying ReRune OTA translations in React, React Native, and Angular. Clone this repository and install its npm dependencies; no other ReRune repository is needed. Each app consumes the public **1.8.0** npm packages and preserves its translation engine's normal rendering APIs. +A standalone consumer repository for trying ReRune OTA translations in React, React Native, and Angular. Clone this repository and install its npm dependencies; no other ReRune repository is needed. Each app consumes the public **1.9.0** npm packages and preserves its translation engine's normal rendering APIs. ## Choose an app @@ -34,11 +34,11 @@ The commands above work without a `.env` file, ReRune account, project creation, After installation, the apps can display bundled copy when the OTA service is unreachable. Live updates need internet access. Each app guide describes optional overrides for your own publishable read ID; console logging defaults to `off`. Expo also needs an SDK 54-compatible client or native development build, as described in its guide. -## Integration in 1.8.0 +## Integration in 1.9.0 -React and React Native await `ReRune.setup(otaOptions, i18nOptions)` and render one `ReRuneProvider`. Native resources and language configuration stay in i18next. Angular uses `ReRune.provide(otaOptions, nativeOptions)` to compose its root engine provider, preserving native loaders and plugins. +React and React Native call `ReRune.setup(otaOptions, i18nOptions)` once at module scope. It returns the client synchronously, and the app renders one `ReRuneProvider` at once, without a translation loading screen. Native resources and language configuration stay in i18next. React web setup reads no storage and sends no requests; `ReRuneProvider` starts the cache restore and the startup check after its first commit. React Native setup starts both right away, so Expo creates its client in its own module. Angular uses `ReRune.setup(otaOptions, nativeOptions)` in its root providers, where it returns `EnvironmentProviders` and composes the root engine provider, preserving native loaders and plugins. In 1.8.0 the Angular call was named `ReRune.provide(...)`. -Since 1.5.1, React and React Native can create an isolated i18next instance from the supplied native options. Apps with plugins can still pass their own instance. Angular keeps its existing combined provider API. Each app guide compares **Before ReRune**, **After ReRune**, and **Removing ReRune**, using the same native configuration and translation calls. +Since 1.5.1, React and React Native can create an isolated i18next instance from the supplied native options. Apps with plugins can still pass their own instance. No app imports `@rerune/core`, which 1.9.0 makes an internal package; APIs and types come from each framework package. The Expo app installs AsyncStorage itself, because 1.9.0 requires it as a peer dependency. Each app guide compares **Before ReRune**, **After ReRune**, and **Removing ReRune**, using the same native configuration and translation calls. ## What to try @@ -46,20 +46,20 @@ ReRune includes My library, Discover with genre filters, Saved stories, and thre Reading settings contains the Main/`vip` edition switch, an SDK staging-mode switch, a fixed date interpolation example, and cardinal plurals under the logical key `plural_sample`. Staging mode previews enabled draft translations when project staging is enabled and keeps its cache separate from published content. Refresh from the library, reader, or settings. Angular's adapter diagnostics remain available through `?tools=1`. -Bookmarks, progress, filters, tabs, and scroll stay in the app session through language and live-text changes. SDK translation data and the edition selection are cached persistently. Each app also remembers the language picked in its language picker, System default included, under `rerune-example-language` (browser `localStorage`, or AsyncStorage in Expo) and starts in it next time; the app does this, not the SDK. With nothing saved, or when storage fails, an app starts in English. The date in settings is a fixed example, not a synchronization timestamp. Refresh feedback distinguishes changed, unchanged, partially updated, and failed checks; partial results name the updated locales. +Bookmarks, progress, filters, tabs, and scroll stay in the app session through language and live-text changes. SDK translation data and the edition selection are cached persistently. Each app also remembers the language picked in its language picker, System default included, under `rerune-example-language` (browser `localStorage`, or AsyncStorage in Expo) and starts in it next time; the app does this, not the SDK. With nothing saved, or when storage fails, an app starts in English. The date in settings is a fixed example, not a synchronization timestamp. Refresh feedback distinguishes changed, unchanged, partially updated, and failed checks; partial results name the languages whose text changed. A removed or renamed language also counts as a change. -SDK **1.8.0** serves OTA from `https://cdn.rerune.io/api/ota//manifest.json`, with the publish ID in the URL path and no identity header. It applies a locale version only when every remote value is compatible with the placeholders, plurals, and formats the app ships; otherwise the previous copy stays in use. Staging previews and hosted cardinal plurals with an omitted offset or explicit numeric `offset: 0` are unchanged. The examples consume the published packages and unchanged OTA payloads. +SDK **1.9.0** serves OTA from `https://cdn.rerune.io/api/ota//manifest.json`, with the publish ID in the URL path and no identity header. It applies a locale version only when every remote value is compatible with the placeholders, plurals, and formats the app ships; otherwise the previous copy stays in use. Staging previews and hosted cardinal plurals with an omitted offset or explicit numeric `offset: 0` are unchanged. The examples consume the published packages and unchanged OTA payloads. ## Boundaries - Reactive translation consumers update. Previously saved strings, static pages, and prerendered output need recalculation or rebuilding. -- Updates are asynchronous checks while the app runs, not push delivery or OS background work. All manifest languages are considered; a failed language can retain older copy. +- Updates are asynchronous checks while the app runs: at startup, on refresh, every 24 hours, and when the app returns to the foreground. They are not push delivery or OS background work. A check covers the shown language and its fallback languages; another published language loads from the cache or downloads when the app shows it, without a manifest request. A failed language can retain older copy. - Variants select among delivered project resources. They are not access controls. - OTA supports plain text, declared interpolation, and one cardinal plural. A bundled engine's MessageFormat support does not expand OTA grammar. -- Built-in caches retain updates in session memory if persistence fails. Read the chosen app's guide for cache behavior. +- If persistence fails, an update still applies for the current session; a restart starts from the last successful write. The React and Expo apps now use the SDK's default cache keys, so a browser or device that ran their 1.8.0 build downloads translations once more and starts at the Main edition. Read the chosen app's guide for cache behavior. ## Packages and documentation -[ReRune](https://rerune.io) · [Developer guide](https://rerune.io/developer-localization-platform) · [Core](https://www.npmjs.com/package/@rerune/core) · [React](https://www.npmjs.com/package/@rerune/react) · [React Native](https://www.npmjs.com/package/@rerune/react-native) · [Angular](https://www.npmjs.com/package/@rerune/angular) +[ReRune](https://rerune.io) · [Developer guide](https://rerune.io/developer-localization-platform) · [React](https://www.npmjs.com/package/@rerune/react) · [React Native](https://www.npmjs.com/package/@rerune/react-native) · [Angular](https://www.npmjs.com/package/@rerune/angular) For checks, CI, screenshots, and shared-asset maintenance, see [Contributing](CONTRIBUTING.md). Code and vector artwork use the [MIT notice](LICENSE). Instrument Sans and Lora include their SIL Open Font License notices in [the shared font directory](examples/shared/fonts/). diff --git a/examples/angular-ngx-translate/README.md b/examples/angular-ngx-translate/README.md index 57e9e91..85f3db9 100644 --- a/examples/angular-ngx-translate/README.md +++ b/examples/angular-ngx-translate/README.md @@ -1,6 +1,6 @@ # Angular with ngx-translate -A runnable ReRune reading app using [@rerune/angular 1.8.0](https://www.npmjs.com/package/@rerune/angular), the public [ReRune service](https://rerune.io), and [SDK documentation](https://www.npmjs.com/package/@rerune/angular#readme). +A runnable ReRune reading app using [@rerune/angular 1.9.0](https://www.npmjs.com/package/@rerune/angular), the public [ReRune service](https://rerune.io), and [SDK documentation](https://www.npmjs.com/package/@rerune/angular#readme). ## Run @@ -25,9 +25,9 @@ Console logging is `off`. A publishable read ID is sufficient; no administration ## Integration -The checkout already installs `@rerune/angular@1.8.0`. In an existing native app, install `@rerune/angular@1.8.0` with your package manager and retain its native engine dependencies. +The checkout already installs `@rerune/angular@1.9.0`. In an existing native app, install `@rerune/angular@1.9.0` with your package manager and retain its native engine dependencies. -SDK 1.8.0 keeps the same combined Angular provider API, including staging configuration. Adoption replaces one native root provider in [src/app.ts](src/app.ts). The comparisons follow the [SDK guide](https://www.npmjs.com/package/@rerune/angular#readme); **Before ReRune** uses the native engine without the SDK. +SDK 1.9.0 renames the combined Angular provider from `ReRune.provide(...)` to `ReRune.setup(...)`, with the same arguments, including staging configuration. Adoption replaces one native root provider in [src/app.ts](src/app.ts). The comparisons follow the [SDK guide](https://www.npmjs.com/package/@rerune/angular#readme); **Before ReRune** uses the native engine without the SDK. The snippets show the root provider comparison; in this checkout the provider list is exported as `appConfig` from `src/app.ts`, and `src/main.ts` bootstraps it. Both alternatives keep the existing `App`, `DemoLoader`, `messages`, and publishable `publishId` from this app. Keep the loader in place; it returns bundled messages using `of(messages[lang] ?? {}).pipe(delay(200))`. Do not move translations or add another bootstrap helper. @@ -59,7 +59,7 @@ import { ReRune } from '@rerune/angular/ngx-translate' bootstrapApplication(App, { providers: [ - ReRune.provide({ + ReRune.setup({ otaPublishId: publishId, staging, supportedLocales: Object.keys(messages), @@ -74,19 +74,25 @@ bootstrapApplication(App, { }).catch(error => console.error(error)) ``` -Replace the native provider import and call with `ReRune.provide(...)`. Register exactly one combined provider at the root; do not retain a separate `provideTranslateService(...)` registration. Its native configuration moves unchanged into the second argument, including loader, fallback, and compiler/plugin behavior. Preserve other root providers and startup error handling. +Replace the native provider import and call with `ReRune.setup(...)`. It returns Angular `EnvironmentProviders`. Register exactly one combined provider at the root; do not retain a separate `provideTranslateService(...)` registration. In route, lazy-loaded, or child injector providers it throws `ReRune.setup must be registered at the application root.` Its native configuration moves unchanged into the second argument, including loader, fallback, and compiler/plugin behavior. Preserve other root providers and startup error handling. The `supportedLocales` hint includes all five bundled languages before the lazy root loader registers it with ngx-translate. It preserves recognition of app-owned languages; it does not replace native language settings. Keep the MessageFormat compiler in the native options. -The optional `staging` boolean comes from `?staging=true` in this example and defaults to false. The settings switch calls `ReRuneService.setStaging(boolean)`. Production and staging snapshots are cached separately, and `ReRuneService.isStaging()` reports the active mode. +The optional `staging` boolean comes from `?staging=true` in this example and defaults to false. The settings switch calls `ReRuneService.setStaging(boolean)`, which switches at once and resolves with the `ReRuneUpdateResult` of the check it runs in the new mode. It never rejects. Production and staging snapshots are cached separately, and `ReRuneService.isStaging()` reports the active mode. + +The edition switch calls `ReRuneService.setVariant({ variant, persist: true })`. The edition applies at once. When the save fails, it stays for this session and the call still resolves; the SDK logs the failure at log level `error` and above. ### Native translation calls [src/app.html](src/app.html) keeps the native `translate` pipe. Language switching still calls `TranslateService.use(locale)`. Keep native service calls, interpolation, and MessageFormat. OTA covers the root/default catalog only; feature scopes, child catalogs, and Angular localize are outside its support. +### From SDK 1.8.0 + +Replace `ReRune.provide(...)` with `ReRune.setup(...)`; 1.9.0 keeps no alias. Import ReRune types, such as `ReRuneState` or `ReRuneUpdateResult`, from `@rerune/angular/ngx-translate`; `@rerune/core` is now an internal package. `ReRuneService.client` is private, so use the `ReRuneService` methods. A type that declares `setStaging(...)` as `Promise` must accept the result, for example `Promise`. `ready()`, `checkForUpdates()`, and `setStaging(...)` never reject, and a failed variant save no longer rejects `setVariant(...)`, so this app shows no variant save or staging error alert. + ### Removing ReRune -Restore the **Before ReRune** provider with the same native options, loader, compiler, and plugin order. Remove ReRune-only refresh, diagnostics, and edition controls, their imports, and `ReRuneService` injection. The shared `ChapterPage` also contains SDK state and actions; remove those members and derive the language list from bundled messages while retaining the pure story reducer. Remove `@rerune/core` from `angular-shared` when both Angular apps no longer use the SDK. Then run from the repository root: +Restore the **Before ReRune** provider with the same native options, loader, compiler, and plugin order. Remove ReRune-only refresh, diagnostics, edition, and staging controls, their imports, and `ReRuneService` injection. The shared `ChapterPage` also contains SDK state and actions; remove those members and derive the language list from bundled messages while retaining the pure story reducer. Then run from the repository root: ```bash pnpm --dir examples/angular-ngx-translate remove @rerune/angular @@ -96,7 +102,7 @@ Keep `@ngx-translate/core` and its MessageFormat dependencies, pipes, and native ### Advanced: an existing root provider -If the native root engine is already registered elsewhere, attach ReRune by omitting its second argument. Preserve that existing native registration and plugin ordering. Use this only for an app-owned root provider; the primary setup above already registers the engine. +If the native root engine is already registered at the root, add `ReRune.setup({ otaPublishId: publishId })` once to the same root providers, without a second argument. Preserve that existing native registration and plugin ordering. Use this only for an app-owned root provider; the primary setup above already registers the engine. ## Manual OTA check @@ -104,20 +110,20 @@ If the native root engine is already registered elsewhere, attach ReRune by omit 2. Switch between English, German, Spanish, Italian, and Portuguese while reading. Additional SDK locales appear alongside bundled languages. Chapter progress, bookmarks, filters, tabs, and scroll remain in this session. 3. Open Reading settings for the Main/`vip` edition switch, staging-mode switch, fixed `14.07.2026` interpolation sample, and `plural_sample` cardinal plural. Turn staging on to preview enabled drafts and off to restore published content. A banner stays visible while staging is active. Refresh from the library, reader, or settings. 4. Configure your own publishable OTA ID. Publish a root translation or a distinct `vip` value, then refresh. Edition choice, the picked language, and SDK translation caches persist across reloads; reading state does not. A remembered bundled language is the start language in the provider configuration; a remembered dashboard-only language is applied once `ReRuneService.ready()` resolves, like a picker change, so English stays visible while it downloads. -5. Block the OTA service or one locale request and refresh again. Partial results identify updated languages; failures retain existing text. Repeated taps start one check at a time. +5. Block the OTA service or one locale request and refresh again. A check covers only the shown language and its English fallback, so show another language, such as German, to see a partial result. Partial results identify updated languages; failures retain existing text. Repeated taps start one check at a time. The date in settings is a fixed interpolation example. Refresh feedback describes the last manual check and remains visible until the next one. -This example pins the released SDK **1.8.0**, including CDN delivery from `cdn.rerune.io`, remote value compatibility checks against the shipped copy, isolated production and staging caches, and hosted cardinal plurals with explicit numeric `offset: 0`. OTA payloads are consumed unchanged. +This example pins the released SDK **1.9.0**, including CDN delivery from `cdn.rerune.io`, remote value compatibility checks against the shipped copy, isolated production and staging caches, and hosted cardinal plurals with explicit numeric `offset: 0`. OTA payloads are consumed unchanged. ## Runtime boundaries -Checks are asynchronous while the app runs, not push delivery or OS background execution. All manifest languages are considered, and languages can retain different versions after a failure. Variants share access to the delivered project resources; they do not restrict access. Reactive consumers update; strings saved in variables and static output require recalculation. +Checks are asynchronous while the app runs: at startup, every 24 hours, when the page becomes visible again, and on refresh. They are not push delivery or OS background execution. ReRune loads only the languages the app shows and their fallback languages; another published language loads from the cache or downloads when the app shows it. Languages can retain different versions after a failure. Variants share access to the delivered project resources; they do not restrict access. Reactive consumers update; strings saved in variables and static output require recalculation. OTA grammar is plain text, declared interpolation, and one cardinal plural. Native bundled MessageFormat support does not add general ICU support to OTA messages. ## Translation cache -The built-in browser cache retains updates in session memory when localStorage is unavailable or a write fails. Newer session values take precedence over older stored copy. Session memory is lost on reload; a later successful write persists the current value. +When localStorage is unavailable or a write fails, an update still applies for the current session. A reload starts from the last successful write; a later successful write persists the current value. A failed write logs one warning at log level `error` and above; this example uses `off`. See [Contributing](../../CONTRIBUTING.md) for automated checks and the [MIT notice](../../LICENSE) for code and artwork licensing. The bundled Instrument Sans and Lora fonts include their own SIL Open Font License notices in [the font directory](../shared/fonts/). diff --git a/examples/angular-ngx-translate/package.json b/examples/angular-ngx-translate/package.json index 87a22fc..168cc48 100644 --- a/examples/angular-ngx-translate/package.json +++ b/examples/angular-ngx-translate/package.json @@ -9,7 +9,7 @@ "typecheck": "ngc -p tsconfig.app.json --noEmit" }, "dependencies": { - "@rerune/angular": "1.8.0", + "@rerune/angular": "1.9.0", "@angular/common": "18.2.14", "@angular/compiler": "18.2.14", "@angular/core": "18.2.14", diff --git a/examples/angular-ngx-translate/src/app.html b/examples/angular-ngx-translate/src/app.html index c485b6f..bbf1342 100644 --- a/examples/angular-ngx-translate/src/app.html +++ b/examples/angular-ngx-translate/src/app.html @@ -90,12 +90,10 @@

{{ 'reading_settings' | translate }}

{{ 'settings - @if (variantError()) {

{{ 'variant_save_error' | translate }}

} @if (stagingActive()) {

{{ 'staging_mode_active' | translate }}

} - @if (stagingError()) {

{{ 'staging_change_error' | translate }}

}

{{ 'publish_date' | translate: { publish_date: date } }}

{{ 'plural_sample' | translate: { count: 1 } }}
{{ 'plural_sample' | translate: { count: 2 } }}

{{ 'session_note' | translate }}

diff --git a/examples/angular-ngx-translate/src/app.ts b/examples/angular-ngx-translate/src/app.ts index 3acdabe..15b0f1e 100644 --- a/examples/angular-ngx-translate/src/app.ts +++ b/examples/angular-ngx-translate/src/app.ts @@ -33,7 +33,7 @@ export class App extends ChapterPage { export const appConfig = { providers: [ - ReRune.provide({ + ReRune.setup({ otaPublishId: publishId, staging, supportedLocales: Object.keys(messages), diff --git a/examples/angular-shared/package.json b/examples/angular-shared/package.json index d277bc6..4bff87d 100644 --- a/examples/angular-shared/package.json +++ b/examples/angular-shared/package.json @@ -3,7 +3,6 @@ "private": true, "type": "module", "dependencies": { - "@angular/core": "18.2.14", - "@rerune/core": "1.8.0" + "@angular/core": "18.2.14" } } diff --git a/examples/angular-shared/presentation.ts b/examples/angular-shared/presentation.ts index 57bea80..19a6563 100644 --- a/examples/angular-shared/presentation.ts +++ b/examples/angular-shared/presentation.ts @@ -1,20 +1,20 @@ import { classifyCheck, refreshText, type RefreshPhase } from '../shared/refresh' import { Directive, HostListener, ViewChild, computed, signal } from '@angular/core' import type { AfterViewChecked, ElementRef, OnInit, Signal } from '@angular/core' -import type { ReRuneSetVariantOptions, ReRuneState, ReRuneUpdateResult } from '@rerune/core' import { initialReadingState, readingReducer, stories, storyIds } from '../shared/stories' import type { LibraryTab, StoryId } from '../shared/stories' import { initialLanguage, messages, publishId, restoredLanguage, saveLanguage, savedLanguage, systemLanguage } from './messages' -// Both examples keep their own native translation service and pipe. +// Both examples keep their own native translation service and pipe. Each +// injects ReRuneService from its engine entry point, which fits this shape. @Directive() export abstract class ChapterPage implements AfterViewChecked, OnInit { abstract readonly rerune: { - state: Signal + state: Signal<{ variant: string; availableLocales: readonly string[] }> ready(): Promise - checkForUpdates(): Promise - setVariant(value: string | ReRuneSetVariantOptions): Promise - setStaging(staging: boolean): Promise + checkForUpdates(): Promise<{ hasUpdates: boolean; hasErrors: boolean; updatedLocales: readonly string[] }> + setVariant(value: { variant: string; persist: boolean }): Promise + setStaging(staging: boolean): Promise isStaging(): boolean } abstract locale(): string @@ -40,9 +40,7 @@ export abstract class ChapterPage implements AfterViewChecked, OnInit { readonly updatedLocales = signal([]) readonly refreshText = refreshText readonly savingVariant = signal(false) - readonly variantError = signal(false) readonly requestedStaging = signal(null) - readonly stagingError = signal(false) readonly systemLocale = signal(savedLanguage === 'system') readonly availableLocales = computed(() => [...new Set([...Object.keys(messages), ...this.rerune.state().availableLocales])]) readonly nativeNames: Record = { en: 'English', de: 'Deutsch', es: 'Español', it: 'Italiano', pt: 'Português' } @@ -131,21 +129,16 @@ export abstract class ChapterPage implements AfterViewChecked, OnInit { async toggleVariant() { if (this.savingVariant()) return this.savingVariant.set(true) - this.variantError.set(false) - try { - const variant = this.rerune.state().variant === 'Main' ? 'vip' : 'Main' - await this.rerune.setVariant(variant) - await this.rerune.setVariant({ variant, persist: true }) - } catch { this.variantError.set(true) } + // The edition applies at once. A failed save keeps it for this session and resolves; the SDK logs it at log level error and above. + try { await this.rerune.setVariant({ variant: this.rerune.state().variant === 'Main' ? 'vip' : 'Main', persist: true }) } finally { this.savingVariant.set(false) } } async toggleStaging() { if (this.requestedStaging() !== null) return const staging = !this.stagingActive() this.requestedStaging.set(staging) - this.stagingError.set(false) + // The mode switches at once. The call never rejects; a failed check of the new mode is in its result. try { await this.rerune.setStaging(staging) } - catch { this.stagingError.set(true) } finally { this.requestedStaging.set(null) } } stagingActive() { return this.requestedStaging() ?? this.rerune.isStaging() } diff --git a/examples/angular-transloco/README.md b/examples/angular-transloco/README.md index 44139c2..6466168 100644 --- a/examples/angular-transloco/README.md +++ b/examples/angular-transloco/README.md @@ -1,6 +1,6 @@ # Angular with Transloco -A runnable ReRune reading app using [@rerune/angular 1.8.0](https://www.npmjs.com/package/@rerune/angular), the public [ReRune service](https://rerune.io), and [SDK documentation](https://www.npmjs.com/package/@rerune/angular#readme). +A runnable ReRune reading app using [@rerune/angular 1.9.0](https://www.npmjs.com/package/@rerune/angular), the public [ReRune service](https://rerune.io), and [SDK documentation](https://www.npmjs.com/package/@rerune/angular#readme). ## Run @@ -25,9 +25,9 @@ Console logging is `off`. A publishable read ID is sufficient; no administration ## Integration -The checkout already installs `@rerune/angular@1.8.0`. In an existing native app, install `@rerune/angular@1.8.0` with your package manager and retain its native engine dependencies. +The checkout already installs `@rerune/angular@1.9.0`. In an existing native app, install `@rerune/angular@1.9.0` with your package manager and retain its native engine dependencies. -SDK 1.8.0 keeps the same combined Angular provider API, including staging configuration. Adoption replaces one native root provider in [src/app.ts](src/app.ts). The comparisons follow the [SDK guide](https://www.npmjs.com/package/@rerune/angular#readme); **Before ReRune** uses the native engine without the SDK. +SDK 1.9.0 renames the combined Angular provider from `ReRune.provide(...)` to `ReRune.setup(...)`, with the same arguments, including staging configuration. Adoption replaces one native root provider in [src/app.ts](src/app.ts). The comparisons follow the [SDK guide](https://www.npmjs.com/package/@rerune/angular#readme); **Before ReRune** uses the native engine without the SDK. The snippets show the root provider comparison; in this checkout the provider list is exported as `appConfig` from `src/app.ts`, and `src/main.ts` bootstraps it. Both alternatives keep the existing `App`, `DemoLoader`, `messages`, and publishable `publishId` from this app. Keep the loader in place; it returns bundled messages using `of(messages[lang] ?? {}).pipe(delay(200))`. Do not move translations or add another bootstrap helper. @@ -58,7 +58,7 @@ import { ReRune } from '@rerune/angular/transloco' bootstrapApplication(App, { providers: [ - ReRune.provide({ + ReRune.setup({ otaPublishId: publishId, staging, logLevel: 'off', @@ -72,19 +72,25 @@ bootstrapApplication(App, { }).catch(error => console.error(error)) ``` -Replace the native provider import and call with `ReRune.provide(...)`. Register exactly one combined provider at the root; do not retain a separate `provideTransloco(...)` registration. Its native configuration moves unchanged into the second argument, including loader, fallback, and compiler/plugin behavior. Preserve other root providers and startup error handling. +Replace the native provider import and call with `ReRune.setup(...)`. It returns Angular `EnvironmentProviders`. Register exactly one combined provider at the root; do not retain a separate `provideTransloco(...)` registration. In route, lazy-loaded, or child injector providers it throws `ReRune.setup must be registered at the application root.` Its native configuration moves unchanged into the second argument, including loader, fallback, and compiler/plugin behavior. Preserve other root providers and startup error handling. Transloco exposes languages through its native `availableLangs`; no extra ReRune locale list is needed. Keep `provideTranslocoMessageformat()` after the combined provider, in the same order as before adoption. -The optional `staging` boolean comes from `?staging=true` in this example and defaults to false. The settings switch calls `ReRuneService.setStaging(boolean)`. Production and staging snapshots are cached separately, and `ReRuneService.isStaging()` reports the active mode. +The optional `staging` boolean comes from `?staging=true` in this example and defaults to false. The settings switch calls `ReRuneService.setStaging(boolean)`, which switches at once and resolves with the `ReRuneUpdateResult` of the check it runs in the new mode. It never rejects. Production and staging snapshots are cached separately, and `ReRuneService.isStaging()` reports the active mode. + +The edition switch calls `ReRuneService.setVariant({ variant, persist: true })`. The edition applies at once. When the save fails, it stays for this session and the call still resolves; the SDK logs the failure at log level `error` and above. ### Native translation calls [src/app.html](src/app.html) keeps the native `transloco` pipe. Language switching still calls `TranslocoService.setActiveLang(locale)`. Keep native service calls, interpolation, and MessageFormat. OTA covers the root/default catalog only; feature scopes, child catalogs, and Angular localize are outside its support. +### From SDK 1.8.0 + +Replace `ReRune.provide(...)` with `ReRune.setup(...)`; 1.9.0 keeps no alias. Import ReRune types, such as `ReRuneState` or `ReRuneUpdateResult`, from `@rerune/angular/transloco`; `@rerune/core` is now an internal package. `ReRuneService.client` is private, so use the `ReRuneService` methods. A type that declares `setStaging(...)` as `Promise` must accept the result, for example `Promise`. `ready()`, `checkForUpdates()`, and `setStaging(...)` never reject, and a failed variant save no longer rejects `setVariant(...)`, so this app shows no variant save or staging error alert. + ### Removing ReRune -Restore the **Before ReRune** provider with the same native options, loader, compiler, and plugin order. Remove ReRune-only refresh, diagnostics, and edition controls, their imports, and `ReRuneService` injection. The shared `ChapterPage` also contains SDK state and actions; remove those members and derive the language list from bundled messages while retaining the pure story reducer. Remove `@rerune/core` from `angular-shared` when both Angular apps no longer use the SDK. Then run from the repository root: +Restore the **Before ReRune** provider with the same native options, loader, compiler, and plugin order. Remove ReRune-only refresh, diagnostics, edition, and staging controls, their imports, and `ReRuneService` injection. The shared `ChapterPage` also contains SDK state and actions; remove those members and derive the language list from bundled messages while retaining the pure story reducer. Then run from the repository root: ```bash pnpm --dir examples/angular-transloco remove @rerune/angular @@ -94,7 +100,7 @@ Keep `@jsverse/transloco` and its MessageFormat dependencies, pipes, and native ### Advanced: an existing root provider -If the native root engine is already registered elsewhere, attach ReRune by omitting its second argument. Preserve that existing native registration and plugin ordering. Use this only for an app-owned root provider; the primary setup above already registers the engine. +If the native root engine is already registered at the root, add `ReRune.setup({ otaPublishId: publishId })` once to the same root providers, without a second argument. Preserve that existing native registration and plugin ordering. Use this only for an app-owned root provider; the primary setup above already registers the engine. ## Manual OTA check @@ -102,20 +108,20 @@ If the native root engine is already registered elsewhere, attach ReRune by omit 2. Switch between English, German, Spanish, Italian, and Portuguese while reading. Additional SDK locales appear alongside bundled languages. Chapter progress, bookmarks, filters, tabs, and scroll remain in this session. 3. Open Reading settings for the Main/`vip` edition switch, staging-mode switch, fixed `14.07.2026` interpolation sample, and `plural_sample` cardinal plural. Turn staging on to preview enabled drafts and off to restore published content. A banner stays visible while staging is active. Refresh from the library, reader, or settings. 4. Configure your own publishable OTA ID. Publish a root translation or a distinct `vip` value, then refresh. Edition choice, the picked language, and SDK translation caches persist across reloads; reading state does not. A remembered bundled language is the start language in the provider configuration; a remembered dashboard-only language is applied once `ReRuneService.ready()` resolves, like a picker change, so English stays visible while it downloads. -5. Block the OTA service or one locale request and refresh again. Partial results identify updated languages; failures retain existing text. Repeated taps start one check at a time. +5. Block the OTA service or one locale request and refresh again. A check covers only the shown language and its English fallback, so show another language, such as German, to see a partial result. Partial results identify updated languages; failures retain existing text. Repeated taps start one check at a time. The date in settings is a fixed interpolation example. Refresh feedback describes the last manual check and remains visible until the next one. -This example pins the released SDK **1.8.0**, including CDN delivery from `cdn.rerune.io`, remote value compatibility checks against the shipped copy, isolated production and staging caches, and hosted cardinal plurals with explicit numeric `offset: 0`. OTA payloads are consumed unchanged. +This example pins the released SDK **1.9.0**, including CDN delivery from `cdn.rerune.io`, remote value compatibility checks against the shipped copy, isolated production and staging caches, and hosted cardinal plurals with explicit numeric `offset: 0`. OTA payloads are consumed unchanged. ## Runtime boundaries -Checks are asynchronous while the app runs, not push delivery or OS background execution. All manifest languages are considered, and languages can retain different versions after a failure. Variants share access to the delivered project resources; they do not restrict access. Reactive consumers update; strings saved in variables and static output require recalculation. +Checks are asynchronous while the app runs: at startup, every 24 hours, when the page becomes visible again, and on refresh. They are not push delivery or OS background execution. ReRune loads only the languages the app shows and their fallback languages; another published language loads from the cache or downloads when the app shows it. Languages can retain different versions after a failure. Variants share access to the delivered project resources; they do not restrict access. Reactive consumers update; strings saved in variables and static output require recalculation. OTA grammar is plain text, declared interpolation, and one cardinal plural. Native bundled MessageFormat support does not add general ICU support to OTA messages. ## Translation cache -The built-in browser cache retains updates in session memory when localStorage is unavailable or a write fails. Newer session values take precedence over older stored copy. Session memory is lost on reload; a later successful write persists the current value. +When localStorage is unavailable or a write fails, an update still applies for the current session. A reload starts from the last successful write; a later successful write persists the current value. A failed write logs one warning at log level `error` and above; this example uses `off`. See [Contributing](../../CONTRIBUTING.md) for automated checks and the [MIT notice](../../LICENSE) for code and artwork licensing. The bundled Instrument Sans and Lora fonts include their own SIL Open Font License notices in [the font directory](../shared/fonts/). diff --git a/examples/angular-transloco/package.json b/examples/angular-transloco/package.json index 2b84160..5799eb0 100644 --- a/examples/angular-transloco/package.json +++ b/examples/angular-transloco/package.json @@ -9,7 +9,7 @@ "typecheck": "ngc -p tsconfig.app.json --noEmit" }, "dependencies": { - "@rerune/angular": "1.8.0", + "@rerune/angular": "1.9.0", "@angular/common": "18.2.14", "@angular/compiler": "18.2.14", "@angular/core": "18.2.14", diff --git a/examples/angular-transloco/src/app.html b/examples/angular-transloco/src/app.html index c32fd29..862c87f 100644 --- a/examples/angular-transloco/src/app.html +++ b/examples/angular-transloco/src/app.html @@ -90,12 +90,10 @@

{{ 'reading_settings' | transloco }}

{{ 'settings - @if (variantError()) {

{{ 'variant_save_error' | transloco }}

} @if (stagingActive()) {

{{ 'staging_mode_active' | transloco }}

} - @if (stagingError()) {

{{ 'staging_change_error' | transloco }}

}

{{ 'publish_date' | transloco: { publish_date: date } }}

{{ 'plural_sample' | transloco: { count: 1 } }}
{{ 'plural_sample' | transloco: { count: 2 } }}

{{ 'session_note' | transloco }}

diff --git a/examples/angular-transloco/src/app.ts b/examples/angular-transloco/src/app.ts index b9486a9..e4baef4 100644 --- a/examples/angular-transloco/src/app.ts +++ b/examples/angular-transloco/src/app.ts @@ -33,7 +33,7 @@ export class App extends ChapterPage { export const appConfig = { providers: [ - ReRune.provide({ + ReRune.setup({ otaPublishId: publishId, staging, logLevel: 'off', diff --git a/examples/react-native-expo/App.tsx b/examples/react-native-expo/App.tsx index 344c289..024bcf5 100644 --- a/examples/react-native-expo/App.tsx +++ b/examples/react-native-expo/App.tsx @@ -5,8 +5,7 @@ import * as NavigationBar from 'expo-navigation-bar' import { useFonts } from 'expo-font' import AsyncStorage from '@react-native-async-storage/async-storage' import { ReRune, ReRuneProvider } from '@rerune/react-native' -import type { ReRuneI18nextClient } from '@rerune/react-native' -import { startup } from './src/i18n' +import { client } from './src/i18n' import { ChapterExperience, LANGUAGE_KEY, systemLanguage } from './src/Chapter' import { COLORS, styles } from './src/theme' import instrumentSans from '../shared/fonts/InstrumentSans-Regular.ttf' @@ -17,9 +16,8 @@ const configuredTestVariant = process.env.EXPO_PUBLIC_RERUNE_VARIANT?.trim() const TEST_VARIANT = configuredTestVariant && configuredTestVariant !== ReRune.Main ? configuredTestVariant : 'vip' export default function App() { - const [client, setClient] = useState(null) - const [startupError, setStartupError] = useState(null) const [savedSystem, setSavedSystem] = useState(false) + const [languageRead, setLanguageRead] = useState(false) const [fontsReady, fontError] = useFonts({ InstrumentSans: instrumentSans, InstrumentSansBold: instrumentSansBold, @@ -27,27 +25,23 @@ export default function App() { }) useEffect(() => { if (Platform.OS === 'android') NavigationBar.setStyle('dark') }, []) useEffect(() => { - let mounted = true - // The app, not the SDK, remembers the picked language. It is read during - // startup and applied before the first screen; a failed read starts in English. - const saved = Promise.resolve().then(() => AsyncStorage.getItem(LANGUAGE_KEY)).catch(() => null) - void Promise.all([startup, saved]).then(([result, language]) => { - if (!mounted) return - if (language && result.client) { - if (language === 'system') setSavedSystem(true) - void result.client.i18n.changeLanguage(language === 'system' ? systemLanguage() : language) - } - setClient(result.client) - setStartupError(result.error) + // The app, not the SDK, remembers the picked language. The first screen waits + // for this read (and the fonts), so it opens in the remembered language; a + // failed read starts in English. + void Promise.resolve().then(() => AsyncStorage.getItem(LANGUAGE_KEY)).catch(() => null).then(language => { + if (language === 'system') setSavedSystem(true) + if (language) void client.i18n.changeLanguage(language === 'system' ? systemLanguage() : language) + setLanguageRead(true) }) - return () => { mounted = false } }, []) return - {startupError || fontError ? {fontError ? 'Could not load reading fonts.' : 'Could not initialize translations.'} - : client && fontsReady ? - : } + + {fontError ? Could not load reading fonts. + : fontsReady && languageRead ? + : } + } diff --git a/examples/react-native-expo/README.md b/examples/react-native-expo/README.md index 31c955d..5b712eb 100644 --- a/examples/react-native-expo/README.md +++ b/examples/react-native-expo/README.md @@ -1,6 +1,6 @@ # React Native with Expo -A runnable ReRune reading app using [@rerune/react-native 1.8.0](https://www.npmjs.com/package/@rerune/react-native), the public [ReRune service](https://rerune.io), and [SDK documentation](https://www.npmjs.com/package/@rerune/react-native#readme). +A runnable ReRune reading app using [@rerune/react-native 1.9.0](https://www.npmjs.com/package/@rerune/react-native), the public [ReRune service](https://rerune.io), and [SDK documentation](https://www.npmjs.com/package/@rerune/react-native#readme). ## Run @@ -15,9 +15,9 @@ pnpm dev:expo The app uses Expo **54.0.37**, React Native **0.81.5**, React **19.1.0**, and Hermes. Open it in an Expo SDK 54-compatible client or a development build that includes AsyncStorage. -Tap the current locale to open the language dropdown, then choose a language. The selected locale has a checkmark. The app saves the choice, System default included, in AsyncStorage (`@react-native-async-storage/async-storage`, declared by the app) and restores it during startup, before the first screen. Tap the selector again or press Android Back to dismiss the menu. Pull down in the library or reader to refresh, or use the refresh control in the library, reader, or Reading settings. +Tap the current locale to open the language dropdown, then choose a language. The selected locale has a checkmark. The app saves the choice, System default included, in AsyncStorage (`@react-native-async-storage/async-storage`, declared by the app) and restores it on the next start: the first screen waits for that read and the reading fonts, so it opens in the remembered language. With nothing saved, or when AsyncStorage fails, the app starts in English. Tap the selector again or press Android Back to dismiss the menu. Pull down in the library or reader to refresh, or use the refresh control in the library, reader, or Reading settings. -The background fills the screen edge-to-edge. `react-native-safe-area-context` keeps library, reader, sheets, loading, and error content clear of status bars, display cutouts, Android navigation bars, and the iOS home indicator, including in landscape. Status-bar icons are light; `expo-navigation-bar` and the Android app configuration keep three-button navigation legible on the dark background. See Expo's [safe-area guide](https://docs.expo.dev/versions/v54.0.0/sdk/safe-area-context/) and [navigation-bar API](https://docs.expo.dev/versions/v54.0.0/sdk/navigation-bar/). +The background fills the screen edge-to-edge. `react-native-safe-area-context` keeps library, reader, sheets, and the font loading and error content clear of status bars, display cutouts, Android navigation bars, and the iOS home indicator, including in landscape. Status-bar icons are light; `expo-navigation-bar` and the Android app configuration keep three-button navigation legible on the dark background. See Expo's [safe-area guide](https://docs.expo.dev/versions/v54.0.0/sdk/safe-area-context/) and [navigation-bar API](https://docs.expo.dev/versions/v54.0.0/sdk/navigation-bar/). Restart Metro after updating dependencies. The reading UI adds `expo-font` **14.0.12** and `react-native-svg` **15.12.1** to Expo **54.0.37** / React Native **0.81.5**. Existing custom development clients require a native rebuild to include the new modules; restarting JavaScript does not apply native build settings. @@ -41,9 +41,9 @@ Console logging is `off`. A publishable read ID is sufficient; no administration ## Integration -The checkout already installs `@rerune/react-native@1.8.0`. In an existing native app, install `@rerune/react-native@1.8.0` with your package manager and retain its native engine dependencies. +The checkout already installs `@rerune/react-native@1.9.0` and AsyncStorage **2.2.0**. In an existing native app, install `@rerune/react-native@1.9.0` with your package manager and retain its native engine dependencies. Since 1.9.0, AsyncStorage is a required peer dependency that your app installs, and ReRune uses that copy for its cache. In an Expo project, run `npx expo install @react-native-async-storage/async-storage`, which picks the version of your Expo SDK (2.2.0 for SDK 54), then rebuild a development build; Expo Go needs no rebuild. -SDK 1.8.0 can create the i18next instance for this bundled-resource app. Adoption replaces initialization and the root translation provider. The comparisons follow the [SDK guide](https://www.npmjs.com/package/@rerune/react-native#readme); **Before ReRune** uses native i18next without the SDK. +SDK 1.9.0 can create the i18next instance for this bundled-resource app. Adoption replaces initialization and the root translation provider. The comparisons follow the [SDK guide](https://www.npmjs.com/package/@rerune/react-native#readme); **Before ReRune** uses native i18next without the SDK. ### Native options @@ -65,7 +65,7 @@ const i18nOptions = { } satisfies InitOptions ``` -Place imports at module scope and awaited initialization in the existing startup flow. `otaPublishId` below is the existing publishable ID from the configuration above. `staging` is the optional boolean derived from `EXPO_PUBLIC_RERUNE_STAGING`; it defaults to false. `Welcome` is the native translation component shown below; keep your application's existing screens and mount timing. +Place imports at module scope. The native version awaits initialization in the existing startup flow; the ReRune version is one synchronous call at module scope. `otaPublishId` below is the existing publishable ID from the configuration above. `staging` is the optional boolean derived from `EXPO_PUBLIC_RERUNE_STAGING`; it defaults to false. `Welcome` is the native translation component shown below; keep your application's existing screens. ### Before ReRune @@ -91,20 +91,21 @@ import { I18nextProvider } from 'react-i18next' ### After ReRune -Replace initialization with the single shared setup promise: +Replace initialization with one setup call at module scope in its own module, [src/i18n.ts](src/i18n.ts). It returns the client synchronously: ```ts -import { ReRune, createReRuneAsyncStorageCacheStore } from '@rerune/react-native' +import { ReRune } from '@rerune/react-native' -const client = await ReRune.setup({ +export const client = ReRune.setup({ otaPublishId, staging, logLevel: 'off', - cacheStore: createReRuneAsyncStorageCacheStore({ prefix: 'rerune-rn-example' }), updatePolicy: { checkOnStart: true, periodicIntervalInHours: 24 }, }, i18nOptions) ``` +Without a `cacheStore` option, ReRune keeps its cache in AsyncStorage. + Replace the root translation provider: ```tsx @@ -115,7 +116,9 @@ import { ReRuneProvider } from '@rerune/react-native' ``` -[App.tsx](App.tsx) keeps its loading and error states, consumes the handled `startup` result, and mounts the provider after native translation initialization and font loading. Font failures also render the startup error state. `ReRuneProvider` includes `I18nextProvider`; register only the replacement and preserve any existing `defaultNS`. Setup waits for native initialization. Cache restoration and OTA delivery continue asynchronously. Keep the client stable across renders and handle setup rejection. +[App.tsx](App.tsx) imports `client` and renders `ReRuneProvider` directly; there is no translation loading screen. With inline bundled resources, i18next has finished initializing when setup returns, so the first render already has the bundled copy. Inside the provider the app waits only for its reading fonts, and a font failure shows an error. `ReRuneProvider` includes `I18nextProvider`; register only the replacement and preserve any existing `defaultNS`. + +React Native setup restores the AsyncStorage cache and starts the startup check right away, and cached and OTA copy replace the bundled copy when they arrive. Create the client only once, outside components: a `useState` initializer under StrictMode or Fast Refresh can create a second client that also reads storage and checks for updates. Setup throws for programming errors such as an empty publish ID, which the fallback to the demo ID rules out here. `client.ready` resolves when native initialization has finished; it is already settled for inline resources, so this app does not wait for it. Await it only where your startup loads translations asynchronously, for example with a backend loader. ### Native translation calls @@ -131,44 +134,50 @@ function Welcome() { } ``` -Language switching still uses `i18n.changeLanguage(locale)` on the instance from `useTranslation()`. Non-component consumers obtain that same instance from `client.i18n` after setup resolves. There is no separate global singleton. OTA targets the `translation` namespace; later native resource writes remain beneath OTA overrides, and removing an override restores the latest application value. +Language switching still uses `i18n.changeLanguage(locale)` on the instance from `useTranslation()`. Non-component consumers use that same instance as `client.i18n`; App.tsx applies the remembered language through it. There is no separate global singleton. OTA targets the `translation` namespace; later native resource writes remain beneath OTA overrides, and removing an override restores the latest application value. + +The staging switch calls `client.setStaging(boolean)`, which switches at once and resolves with the result of the check it runs in the selected mode. Production and staging snapshots are cached separately, and `client.isStaging()` reports the active mode. The mode itself is selected again from configuration on application startup. -The settings switch calls `client.setStaging(boolean)`. Production and staging snapshots are cached separately, and `client.isStaging()` reports the active mode. The mode itself is selected again from configuration on application startup. +The edition switch calls `client.setVariant({ variant, persist: true })` once. The edition applies at once and is then saved; a failed save keeps it for this run only and does not reject, so the app shows no save error. ### Removing ReRune -Restore both **Before ReRune** blocks with the same options and resource files. Replace any non-component `client.i18n` use with the restored native instance. Remove ReRune-only refresh, status, and variant controls and their imports, then run from the repository root: +Restore both **Before ReRune** blocks with the same options and resource files, and render the app after the awaited initialization. Replace the non-component `client.i18n` use in App.tsx with the restored native instance. Remove ReRune-only refresh, status, staging, and variant controls and their imports, then run from the repository root: ```bash pnpm --dir examples/react-native-expo remove @rerune/react-native ``` -Keep `i18next`, `react-i18next`, and the native translation calls. Ensure bundled messages or native loaders cover every required language. OTA delivery, ReRune cache restoration, and variant selection stop. Removal is a source change followed by an app restart; unmounting or disposing a client is not a live rollback. +Keep `i18next`, `react-i18next`, and the native translation calls. Keep `@react-native-async-storage/async-storage` too, because the app remembers the picked language with it. Ensure bundled messages or native loaders cover every required language. OTA delivery, ReRune cache restoration, and variant selection stop. Removal is a source change followed by an app restart; unmounting or disposing a client is not a live rollback. ### Advanced: existing instances and plugins -If your app owns `.use(...)` plugins or depends on a global instance, keep that instance and pass `i18n` in the first setup argument. Keep the same native options as the second argument. For an already initialized instance, await its native initialization first and omit setup's second argument. This example has no such consumers and lets ReRune create the instance. +If your app owns `.use(...)` plugins or depends on a global instance, keep that instance and pass `i18n` in the first setup argument. Keep the same native options as the second argument. For an instance that is already initialized, or whose own `i18n.init(...)` is still running, omit setup's second argument. A backend loader or an asynchronous language detector makes native initialization asynchronous: setup still returns at once, and the app awaits `client.ready` where it used to await `i18n.init(...)`. This example has no such consumers and lets ReRune create the instance. ## Manual OTA check 1. Explore My library, Discover's genre filters, and the empty Saved shelf. Bookmark stories, read both chapters of each story, finish, and restart. -2. Switch between English, German, Spanish, Italian, and Portuguese while reading. Additional SDK locales appear alongside bundled languages. Chapter progress, bookmarks, filters, tabs, and scroll remain in this session. +2. Switch between English, German, Spanish, Italian, and Portuguese while reading. Additional SDK locales appear alongside bundled languages. Chapter progress, bookmarks, filters, tabs, and scroll remain in this session. Reload the app: it starts in the language you picked last, System default included. 3. Open Reading settings for the Main/`vip` edition switch, staging-mode switch, fixed `14.07.2026` interpolation sample, and `plural_sample` cardinal plural. Turn staging on to preview enabled drafts and off to restore published content. A banner stays visible while staging is active. Refresh from the library, reader, or settings. 4. Configure your own publishable OTA ID. Publish a root translation or a distinct `vip` value, then refresh. Edition choice and SDK translation caches persist across reloads; reading state does not. -5. Block the OTA service or one locale request and refresh again. Partial results identify updated languages; failures retain existing text. Repeated taps start one check at a time. +5. Block the OTA service or one locale request and refresh again. A check covers only the shown language and its English fallback, so show another language, such as German, to see a partial result. Partial results identify updated languages; failures retain existing text. Repeated taps start one check at a time. The date in settings is a fixed interpolation example. Refresh feedback describes the last manual check and remains visible until the next one. -This example pins the released SDK **1.8.0**, including CDN delivery from `cdn.rerune.io`, remote value compatibility checks against the shipped copy, isolated production and staging caches, and hosted cardinal plurals with explicit numeric `offset: 0`. OTA payloads are consumed unchanged. +This example pins the released SDK **1.9.0**, including CDN delivery from `cdn.rerune.io`, remote value compatibility checks against the shipped copy, isolated production and staging caches, and hosted cardinal plurals with explicit numeric `offset: 0`. OTA payloads are consumed unchanged. ## Runtime boundaries -Checks are asynchronous while the app runs, not push delivery or OS background execution. All manifest languages are considered, and languages can retain different versions after a failure. Variants share access to the delivered project resources; they do not restrict access. Reactive consumers update; strings saved in variables and static output require recalculation. +Checks are asynchronous while the app runs, not push delivery or OS background execution. Besides the startup check and the 24-hour interval, ReRune checks when the app returns to the foreground from the background. A check covers the languages the app shows and their fallback languages; another published language loads from the cache or downloads when the app shows it, and the picker lists every published language. Languages can retain different versions after a failure. Variants share access to the delivered project resources; they do not restrict access. Reactive consumers update; strings saved in variables and static output require recalculation. OTA grammar is plain text, declared interpolation, and one cardinal plural. Native bundled MessageFormat support does not add general ICU support to OTA messages. +The [SDK guide](https://www.npmjs.com/package/@rerune/react-native#plural-rules-on-hermes) recommends the `@formatjs/intl-pluralrules` polyfill on Hermes, with the data of every language the app or the dashboard publishes. This example does not include it. Without plural rules, i18next selects only the `one` and `other` forms, which covers the `plural_sample` counts of 1 and 2 shown in Reading settings. `logLevel: 'off'` also silences the SDK's development report about missing plural rules. + ## Translation cache -Cached OTA copy and bundled resources can provide text offline. If an AsyncStorage write fails, the built-in cache retains the update in session memory and allows it to activate. Newer session values take precedence over older stored copy. Session memory is lost on restart; a later successful write persists the current value. +Cached OTA copy and bundled resources can provide text offline. If an AsyncStorage write fails, the update still applies for the current run. A restart starts from the last successful write; a later successful write persists the current value. + +The default store uses ReRune's own AsyncStorage keys. With SDK 1.8.0 this example used the key prefix `rerune-rn-example`, so on a device that ran that build, the first start after the upgrade downloads the languages again, the old keys stay unused, and a saved `vip` edition returns to Main until you switch it again. The remembered language has its own key and stays. See [Contributing](../../CONTRIBUTING.md) for automated checks and the [MIT notice](../../LICENSE) for code and artwork licensing. The bundled Instrument Sans and Lora fonts include their own SIL Open Font License notices in [the font directory](../shared/fonts/). diff --git a/examples/react-native-expo/index.ts b/examples/react-native-expo/index.ts index 9f60ac4..c6af4a4 100644 --- a/examples/react-native-expo/index.ts +++ b/examples/react-native-expo/index.ts @@ -1,3 +1,15 @@ +// Hermes, the React Native engine, has no Intl.PluralRules, which i18next needs +// to pick plural forms. Load the polyfill and the data of every language the +// app or the ReRune dashboard publishes before anything uses i18next. +import '@formatjs/intl-pluralrules/polyfill.js' +import '@formatjs/intl-pluralrules/locale-data/de.js' +import '@formatjs/intl-pluralrules/locale-data/en.js' +import '@formatjs/intl-pluralrules/locale-data/es.js' +import '@formatjs/intl-pluralrules/locale-data/fr.js' +import '@formatjs/intl-pluralrules/locale-data/it.js' +import '@formatjs/intl-pluralrules/locale-data/pt.js' +import '@formatjs/intl-pluralrules/locale-data/sq.js' +import '@formatjs/intl-pluralrules/locale-data/zh.js' import { registerRootComponent } from 'expo' import App from './App' diff --git a/examples/react-native-expo/package.json b/examples/react-native-expo/package.json index ddd7fbc..f4e8616 100644 --- a/examples/react-native-expo/package.json +++ b/examples/react-native-expo/package.json @@ -9,8 +9,9 @@ "lint": "eslint App.tsx index.ts src --ext .ts,.tsx" }, "dependencies": { + "@formatjs/intl-pluralrules": "6.3.16", "@react-native-async-storage/async-storage": "2.2.0", - "@rerune/react-native": "1.8.0", + "@rerune/react-native": "1.9.0", "expo": "54.0.37", "expo-font": "14.0.12", "expo-navigation-bar": "~5.0.10", diff --git a/examples/react-native-expo/src/Chapter.tsx b/examples/react-native-expo/src/Chapter.tsx index a6ed9e4..8eb9152 100644 --- a/examples/react-native-expo/src/Chapter.tsx +++ b/examples/react-native-expo/src/Chapter.tsx @@ -29,7 +29,6 @@ export function ChapterExperience({ testVariant, savedSystem = false }: { testVa const [refreshing, setRefreshing] = useState(false) const [feedback, setFeedback] = useState(null) const [savingVariant, setSavingVariant] = useState(false) - const [variantError, setVariantError] = useState(false) const [requestedStaging, setRequestedStaging] = useState(null) const [stagingError, setStagingError] = useState(false) const [updatedLocales, setUpdatedLocales] = useState([]) @@ -56,6 +55,8 @@ export function ChapterExperience({ testVariant, savedSystem = false }: { testVa }) return () => subscription.remove() }, [reader, settings]) + // A saved System default that is read after the chapter appeared. + useEffect(() => { if (savedSystem) setSystemLocale(true) }, [savedSystem]) useEffect(() => { if (!systemLocale) return const update = () => { void i18n.changeLanguage(systemLanguage()) } @@ -81,13 +82,11 @@ export function ChapterExperience({ testVariant, savedSystem = false }: { testVa if (variantInFlight.current) return variantInFlight.current = true setSavingVariant(true) - setVariantError(false) try { - const variant = sdk.variant === ReRune.Main ? testVariant : ReRune.Main - await client.setVariant(variant) - await client.setVariant({ variant, persist: true }) - } catch { setVariantError(true) } - finally { variantInFlight.current = false; setSavingVariant(false) } + // The edition applies at once and is then saved. A failed save keeps it for + // this run only; the SDK logs it at log level error and above. + await client.setVariant({ variant: sdk.variant === ReRune.Main ? testVariant : ReRune.Main, persist: true }) + } finally { variantInFlight.current = false; setSavingVariant(false) } } async function toggleStaging(staging: boolean) { if (stagingInFlight.current) return @@ -204,7 +203,7 @@ export function ChapterExperience({ testVariant, savedSystem = false }: { testVa {t('reading_settings')}{t('settings_description')} {t('translation_variant')}{sdk.variant} void toggleVariant()} trackColor={{ false: COLORS.border, true: COLORS.accent }} thumbColor={COLORS.text} /> - {variantError && {t('variant_save_error')}} + {stagingActive && {t('staging_mode_active')}} {t('staging_mode')}{t(stagingActive ? 'staging_mode_on' : 'staging_mode_off')} void toggleStaging(value)} trackColor={{ false: COLORS.border, true: COLORS.accent }} thumbColor={COLORS.text} /> diff --git a/examples/react-native-expo/src/i18n.ts b/examples/react-native-expo/src/i18n.ts index 6ed1151..2ce31cb 100644 --- a/examples/react-native-expo/src/i18n.ts +++ b/examples/react-native-expo/src/i18n.ts @@ -1,4 +1,4 @@ -import { ReRune, createReRuneAsyncStorageCacheStore } from '@rerune/react-native' +import { ReRune } from '@rerune/react-native' import type { InitOptions } from 'i18next' import { resourcesByLocale } from '../../shared/messages' @@ -24,16 +24,12 @@ const otaPublishId = process.env.EXPO_PUBLIC_RERUNE_OTA_PUBLISH_ID?.trim() || DEFAULT_OTA_PUBLISH_ID const staging = process.env.EXPO_PUBLIC_RERUNE_STAGING === 'true' -const reruneCacheStore = createReRuneAsyncStorageCacheStore({ prefix: 'rerune-rn-example' }) -const clientReady = ReRune.setup({ +// Set up once, at module scope in this module. React Native setup restores the +// AsyncStorage cache and starts the startup check right away, so a component +// must not create the client. The default store keeps the cache in AsyncStorage. +export const client = ReRune.setup({ otaPublishId, staging, logLevel: 'off', - cacheStore: reruneCacheStore, updatePolicy: { checkOnStart: true, periodicIntervalInHours: 24 }, }, i18nOptions) -// Keep startup rejection handled even before the root effect mounts. -export const startup = clientReady.then( - client => ({ client, error: null }), - error => ({ client: null, error: error instanceof Error ? error : new Error(String(error)) }), -) diff --git a/examples/react-web-vite/README.md b/examples/react-web-vite/README.md index ae4e9c5..631c23f 100644 --- a/examples/react-web-vite/README.md +++ b/examples/react-web-vite/README.md @@ -1,6 +1,6 @@ # React web with i18next -A runnable ReRune reading app using [@rerune/react 1.8.0](https://www.npmjs.com/package/@rerune/react), the public [ReRune service](https://rerune.io), and [SDK documentation](https://www.npmjs.com/package/@rerune/react#readme). +A runnable ReRune reading app using [@rerune/react 1.9.0](https://www.npmjs.com/package/@rerune/react), the public [ReRune service](https://rerune.io), and [SDK documentation](https://www.npmjs.com/package/@rerune/react#readme). ## Run @@ -31,9 +31,9 @@ Console logging is `off`. A publishable read ID is sufficient; no administration ## Integration -The checkout already installs `@rerune/react@1.8.0`. In an existing native app, install `@rerune/react@1.8.0` with your package manager and retain its native engine dependencies. +The checkout already installs `@rerune/react@1.9.0`. In an existing native app, install `@rerune/react@1.9.0` with your package manager and retain its native engine dependencies. -SDK 1.8.0 can create the i18next instance for this bundled-resource app. Adoption replaces initialization and the root translation provider. The comparisons follow the [SDK guide](https://www.npmjs.com/package/@rerune/react#readme); **Before ReRune** uses native i18next without the SDK. +SDK 1.9.0 can create the i18next instance for this bundled-resource app. Adoption replaces initialization and the root translation provider. The comparisons follow the [SDK guide](https://www.npmjs.com/package/@rerune/react#readme); **Before ReRune** uses native i18next without the SDK. ### Native options @@ -55,7 +55,7 @@ const i18nOptions = { } satisfies InitOptions ``` -Place imports at module scope and awaited initialization in the existing startup flow. `otaPublishId` below is the existing publishable ID from the configuration above. `staging` is the optional boolean derived from `VITE_RERUNE_STAGING` or `?staging=true`; it defaults to false. `Welcome` is the native translation component shown below; keep your application's existing screens and mount timing. +Place imports at module scope. The native initialization below is awaited in the existing startup flow; ReRune's setup returns the client at once, so it runs at module scope instead. `otaPublishId` below is the existing publishable ID from the configuration above. `staging` is the optional boolean derived from `VITE_RERUNE_STAGING` or `?staging=true`; it defaults to false. `Welcome` is the native translation component shown below; keep your application's existing screens and mount timing. ### Before ReRune @@ -81,16 +81,15 @@ import { I18nextProvider } from 'react-i18next' ### After ReRune -Replace initialization with the single shared setup promise: +Replace initialization with one setup call at module scope. It returns the client synchronously: ```ts -import { ReRune, createReRuneBrowserCacheStore } from '@rerune/react' +import { ReRune } from '@rerune/react' -const client = await ReRune.setup({ +export const client = ReRune.setup({ otaPublishId, staging, logLevel: 'off', - cacheStore: createReRuneBrowserCacheStore({ prefix: 'rerune-web-example' }), updatePolicy: { checkOnStart: true, periodicIntervalInHours: 24 }, }, i18nOptions) ``` @@ -105,7 +104,9 @@ import { ReRuneProvider } from '@rerune/react' ``` -[src/main.tsx](src/main.tsx) awaits setup before rendering. `ReRuneProvider` includes `I18nextProvider`; register only the replacement and preserve any existing `defaultNS`. Setup waits for native initialization. Cache restoration and OTA delivery continue asynchronously. Keep the client stable across renders and handle setup rejection. +[src/main.tsx](src/main.tsx) renders at once, without a loading screen. `ReRuneProvider` includes `I18nextProvider`; register only the replacement and preserve any existing `defaultNS`. With inline resources, i18next has finished initializing when setup returns, so the first render already shows the bundled copy, in the remembered language when that language is bundled. Setup reads no storage and sends no requests. After its first commit, `ReRuneProvider` restores the cached translations and runs the startup check, so after a reload the bundled copy can show for a moment before the cached OTA copy replaces it. Without the provider, ReRune does not start. + +Create the client once, at module scope, as [src/i18n.ts](src/i18n.ts) does. Setup throws at once for programming errors, such as an invalid publish ID. `client.ready` resolves when native initialization has finished; it is already settled for inline resources, so this app does not await it. Await it only where your startup awaited `i18n.init(...)`, for example with a backend loader. ### Native translation calls @@ -120,13 +121,15 @@ function Welcome() { } ``` -Language switching still uses `i18n.changeLanguage(locale)` on the instance from `useTranslation()`. Non-component consumers obtain that same instance from `client.i18n` after setup resolves. There is no separate global singleton. OTA targets the `translation` namespace; later native resource writes remain beneath OTA overrides, and removing an override restores the latest application value. +Language switching still uses `i18n.changeLanguage(locale)` on the instance from `useTranslation()`. Non-component consumers use that same instance through `client.i18n`. There is no separate global singleton. OTA targets the `translation` namespace; later native resource writes remain beneath OTA overrides, and removing an override restores the latest application value. + +The edition switch calls `client.setVariant({ variant, persist: true })`. The edition applies at once and is then saved; if saving fails, it still applies for this session and the SDK logs the failure at log level `error` and above (this example uses `off`), so the app shows no error for it. -The settings switch calls `client.setStaging(boolean)`. Production and staging snapshots are cached separately, and `client.isStaging()` reports the active mode. The mode itself is selected again from configuration on application startup. +The staging switch calls `client.setStaging(boolean)`, which resolves with the result of the check it runs in the selected mode. Production and staging snapshots are cached separately, and `client.isStaging()` reports the active mode. The mode itself is selected again from configuration on application startup. ### Removing ReRune -Restore both **Before ReRune** blocks with the same options and resource files. Replace any non-component `client.i18n` use with the restored native instance. Remove ReRune-only refresh, status, and variant controls and their imports, then run from the repository root: +Restore both **Before ReRune** blocks with the same options and resource files, and render once native initialization completes. Replace any non-component `client.i18n` use with the restored native instance. Remove ReRune-only refresh, status, variant, and staging controls and their imports, then run from the repository root: ```bash pnpm --dir examples/react-web-vite remove @rerune/react @@ -136,7 +139,7 @@ Keep `i18next`, `react-i18next`, and the native translation calls. Ensure bundle ### Advanced: existing instances and plugins -If your app owns `.use(...)` plugins or depends on a global instance, keep that instance and pass `i18n` in the first setup argument. Keep the same native options as the second argument. For an already initialized instance, await its native initialization first and omit setup's second argument. This example has no such consumers and lets ReRune create the instance. +If your app owns `.use(...)` plugins or depends on a global instance, keep that instance and pass `i18n` in the first setup argument. Keep the same native options as the second argument. For an instance that is already initialized, or whose own initialization is still running, omit setup's second argument. A backend loader or an asynchronous language detector makes native initialization asynchronous: setup still returns the client at once, and the app awaits `client.ready` where it awaited `i18n.init(...)` before. This example has no such consumers and lets ReRune create the instance. ## Manual OTA check @@ -144,20 +147,22 @@ If your app owns `.use(...)` plugins or depends on a global instance, keep that 2. Switch between English, German, Spanish, Italian, and Portuguese while reading. Additional SDK locales appear alongside bundled languages. Chapter progress, bookmarks, filters, tabs, and scroll remain in this session. 3. Open Reading settings for the Main/`vip` edition switch, staging-mode switch, fixed `14.07.2026` interpolation sample, and `plural_sample` cardinal plural. Turn staging on to preview enabled drafts and off to restore published content. A banner stays visible while staging is active. Refresh from the library, reader, or settings. 4. Configure your own publishable OTA ID. Publish a root translation or a distinct `vip` value, then refresh. Edition choice, the picked language, and SDK translation caches persist across reloads; reading state does not. `src/i18n.ts` reads the remembered language before `ReRune.setup(...)`, so the first render is already in it. -5. Block the OTA service or one locale request and refresh again. Partial results identify updated languages; failures retain existing text. Repeated taps start one check at a time. +5. Block the OTA service or one locale request and refresh again. A check covers only the shown language and its English fallback, so show another language, such as German, to see a partial result. Partial results identify updated languages; failures retain existing text. Repeated taps start one check at a time. The date in settings is a fixed interpolation example. Refresh feedback describes the last manual check and remains visible until the next one. -This example pins the released SDK **1.8.0**, including CDN delivery from `cdn.rerune.io`, remote value compatibility checks against the shipped copy, isolated production and staging caches, and hosted cardinal plurals with explicit numeric `offset: 0`. OTA payloads are consumed unchanged. +This example pins the released SDK **1.9.0**, including CDN delivery from `cdn.rerune.io`, remote value compatibility checks against the shipped copy, isolated production and staging caches, and hosted cardinal plurals with explicit numeric `offset: 0`. OTA payloads are consumed unchanged. ## Runtime boundaries -Checks are asynchronous while the app runs, not push delivery or OS background execution. All manifest languages are considered, and languages can retain different versions after a failure. Variants share access to the delivered project resources; they do not restrict access. Reactive consumers update; strings saved in variables and static output require recalculation. +Checks run at startup, when the page becomes visible again, on manual refresh, and every 24 hours while the page is open. They are asynchronous, not push delivery or OS background execution. A check covers the shown language and its English fallback; other published languages load when the app shows them, and a language change sends no manifest request. Languages can retain different versions after a failure. Variants share access to the delivered project resources; they do not restrict access. Reactive consumers update; strings saved in variables and static output require recalculation. OTA grammar is plain text, declared interpolation, and one cardinal plural. Native bundled MessageFormat support does not add general ICU support to OTA messages. ## Translation cache -The built-in browser cache retains updates in session memory when localStorage is unavailable or a write fails. Newer session values take precedence over older stored copy. Session memory is lost on reload; a later successful write persists the current value. +The app passes no `cacheStore`, so ReRune uses its default browser store. Versions of this app on SDK 1.8.0 stored their cache under a `rerune-web-example` prefix, which 1.9.0 no longer reads: after the upgrade, translations download again once and the edition switch starts at Main. + +When localStorage is unavailable or a write fails, an update still applies for the current session. A reload starts from the last successful write; a later successful write persists the current value. See [Contributing](../../CONTRIBUTING.md) for automated checks and the [MIT notice](../../LICENSE) for code and artwork licensing. The bundled Instrument Sans and Lora fonts include their own SIL Open Font License notices in [the font directory](../shared/fonts/). diff --git a/examples/react-web-vite/package.json b/examples/react-web-vite/package.json index 1c282c6..f85a481 100644 --- a/examples/react-web-vite/package.json +++ b/examples/react-web-vite/package.json @@ -9,7 +9,7 @@ "lint": "eslint src --ext .ts,.tsx" }, "dependencies": { - "@rerune/react": "1.8.0", + "@rerune/react": "1.9.0", "i18next": "^25.0.0", "react": "19.1.0", "react-dom": "19.1.0", diff --git a/examples/react-web-vite/src/App.tsx b/examples/react-web-vite/src/App.tsx index 9db6458..5f84f91 100644 --- a/examples/react-web-vite/src/App.tsx +++ b/examples/react-web-vite/src/App.tsx @@ -67,7 +67,6 @@ function ChapterExperience({ testVariant }: { testVariant: string }) { const [updatedLocales, setUpdatedLocales] = useState([]) const inFlight = useRef(false) const [savingVariant, setSavingVariant] = useState(false) - const [variantError, setVariantError] = useState(false) const [requestedStaging, setRequestedStaging] = useState(null) const [stagingError, setStagingError] = useState(false) const stagingInFlight = useRef(false) @@ -130,14 +129,10 @@ function ChapterExperience({ testVariant }: { testVariant: string }) { async function toggleVariant() { if (savingVariant) return setSavingVariant(true) - setVariantError(false) try { - // Retain the current session's selection if persistence fails. - const variant = sdk.variant === ReRune.Main ? testVariant : ReRune.Main - await client.setVariant(variant) - await client.setVariant({ variant, persist: true }) - } catch { setVariantError(true) } - finally { setSavingVariant(false) } + // A failed save keeps the edition for this session; the SDK logs it. + await client.setVariant({ variant: sdk.variant === ReRune.Main ? testVariant : ReRune.Main, persist: true }) + } finally { setSavingVariant(false) } } async function toggleStaging() { if (stagingInFlight.current) return @@ -241,7 +236,6 @@ function ChapterExperience({ testVariant }: { testVariant: string }) {

{t('reading_settings')}

{t('settings_description')}

- {variantError &&

{t('variant_save_error')}

} {stagingActive &&

{t('staging_mode_active')}

} diff --git a/examples/react-web-vite/src/i18n.ts b/examples/react-web-vite/src/i18n.ts index df216bc..6df4710 100644 --- a/examples/react-web-vite/src/i18n.ts +++ b/examples/react-web-vite/src/i18n.ts @@ -1,4 +1,4 @@ -import { ReRune, createReRuneBrowserCacheStore } from '@rerune/react' +import { ReRune } from '@rerune/react' import type { InitOptions } from 'i18next' import { resourcesByLocale } from '../../shared/messages' @@ -37,11 +37,11 @@ const otaPublishId = const staging = import.meta.env.VITE_RERUNE_STAGING === 'true' || new URLSearchParams(window.location.search).get('staging') === 'true' -export const clientReady = ReRune.setup({ +// Setup returns the client at once and reads no storage. ReRuneProvider starts it after the first render. +export const client = ReRune.setup({ otaPublishId, staging, logLevel: 'off', - cacheStore: createReRuneBrowserCacheStore({ prefix: 'rerune-web-example' }), updatePolicy: { checkOnStart: true, periodicIntervalInHours: 24, diff --git a/examples/react-web-vite/src/main.tsx b/examples/react-web-vite/src/main.tsx index 781ee22..a191d0d 100644 --- a/examples/react-web-vite/src/main.tsx +++ b/examples/react-web-vite/src/main.tsx @@ -3,18 +3,13 @@ import { ReRune } from '@rerune/react' import ReactDOM from 'react-dom/client' import { App } from './App' -import { clientReady } from './i18n' +import { client } from './i18n' const configuredTestVariant = import.meta.env.VITE_RERUNE_VARIANT?.trim() const testVariant = configuredTestVariant && configuredTestVariant !== ReRune.Main ? configuredTestVariant : 'vip' -void clientReady.then(client => { - ReactDOM.createRoot(document.getElementById('root')!).render( - - - - ) -}).catch(error => { - console.error('Localization startup failed', error) - document.getElementById('root')!.textContent = 'Could not initialize translations.' -}) +ReactDOM.createRoot(document.getElementById('root')!).render( + + + +) diff --git a/examples/shared/messages.ts b/examples/shared/messages.ts index 75751b6..1a5f94a 100644 --- a/examples/shared/messages.ts +++ b/examples/shared/messages.ts @@ -50,7 +50,6 @@ export const resourcesByLocale = { "staging_mode_off": "Published translations", "staging_change_error": "Could not change staging mode. Try again.", "translation_variant": "VIP edition", - "variant_save_error": "This edition changed, but could not be saved for next time.", "session_note": "Bookmarks and reading progress stay with you during this app session.", "back_library": "Back to library", "next_chapter": "Next chapter", @@ -129,7 +128,6 @@ export const resourcesByLocale = { "staging_mode_off": "Veröffentlichte Übersetzungen", "staging_change_error": "Der Staging-Modus konnte nicht geändert werden. Versuche es erneut.", "translation_variant": "VIP-Ausgabe", - "variant_save_error": "Die Ausgabe wurde geändert, konnte aber nicht gespeichert werden.", "session_note": "Lesezeichen und Lesefortschritt bleiben während dieser Sitzung erhalten.", "back_library": "Zurück zur Bibliothek", "next_chapter": "Nächstes Kapitel", @@ -211,7 +209,6 @@ export const resourcesByLocale = { "staging_mode_off": "Traducciones publicadas", "staging_change_error": "No se pudo cambiar el modo de staging. Inténtalo de nuevo.", "translation_variant": "Edición VIP", - "variant_save_error": "La edición cambió, pero no se pudo guardar para la próxima vez.", "session_note": "Los marcadores y el progreso se conservan durante esta sesión.", "back_library": "Volver a la biblioteca", "next_chapter": "Siguiente capítulo", @@ -292,7 +289,6 @@ export const resourcesByLocale = { "staging_mode_off": "Traduzioni pubblicate", "staging_change_error": "Impossibile cambiare la modalità staging. Riprova.", "translation_variant": "Edizione VIP", - "variant_save_error": "L'edizione è cambiata, ma non è stato possibile salvarla.", "session_note": "Segnalibri e progressi restano disponibili durante questa sessione.", "back_library": "Torna alla biblioteca", "next_chapter": "Prossimo capitolo", @@ -373,7 +369,6 @@ export const resourcesByLocale = { "staging_mode_off": "Traduções publicadas", "staging_change_error": "Não foi possível alterar o modo de staging. Tente novamente.", "translation_variant": "Edição VIP", - "variant_save_error": "A edição mudou, mas não foi possível guardá-la para a próxima vez.", "session_note": "Os marcadores e o progresso ficam disponíveis durante esta sessão.", "back_library": "Voltar à biblioteca", "next_chapter": "Próximo capítulo", diff --git a/examples/shared/refresh.ts b/examples/shared/refresh.ts index 6c4007d..9f386c0 100644 --- a/examples/shared/refresh.ts +++ b/examples/shared/refresh.ts @@ -1,6 +1,7 @@ export type RefreshPhase = 'success' | 'current' | 'partial' | 'error' -// Classify transport/update outcomes from the public result flags. +// Classify transport/update outcomes from the public result flags. Since SDK 1.9.0, +// hasUpdates is also true for removed or renamed languages, and checks resolve on failure. export function classifyCheck(result: { hasErrors: boolean; hasUpdates: boolean }): RefreshPhase { if (result.hasErrors) return result.hasUpdates ? 'partial' : 'error' return result.hasUpdates ? 'success' : 'current' @@ -8,11 +9,12 @@ export function classifyCheck(result: { hasErrors: boolean; hasUpdates: boolean // Application-owned feedback stays accurate when OTA copy changes. export function refreshText(phase: RefreshPhase, locale: string, updatedLocales: readonly string[] = []): string { - const languages = updatedLocales.join(', ') + // A partial result whose changes are only removals or new names has no language to name. + const languages = updatedLocales.length ? `: ${updatedLocales.join(', ')}` : '' const localized: Record> = { - es: { success: 'Actualizado correctamente', current: 'Ya está actualizado', partial: `Actualizado parcialmente: ${languages}`, error: 'La comprobación falló; se conserva el texto anterior' }, - it: { success: 'Aggiornamento completato', current: 'Già aggiornato', partial: `Aggiornamento parziale: ${languages}`, error: 'Controllo non riuscito; il testo precedente è conservato' }, - pt: { success: 'Atualizado com sucesso', current: 'Já está atualizado', partial: `Atualizado parcialmente: ${languages}`, error: 'A verificação falhou; o texto anterior foi mantido' }, + es: { success: 'Actualizado correctamente', current: 'Ya está actualizado', partial: `Actualizado parcialmente${languages}`, error: 'La comprobación falló; se conserva el texto anterior' }, + it: { success: 'Aggiornamento completato', current: 'Già aggiornato', partial: `Aggiornamento parziale${languages}`, error: 'Controllo non riuscito; il testo precedente è conservato' }, + pt: { success: 'Atualizado com sucesso', current: 'Já está atualizado', partial: `Atualizado parcialmente${languages}`, error: 'A verificação falhou; o texto anterior foi mantido' }, } const translated = localized[locale.toLowerCase().split('-')[0] ?? 'en'] if (translated) return translated[phase] @@ -20,7 +22,7 @@ export function refreshText(phase: RefreshPhase, locale: string, updatedLocales: switch (phase) { case 'success': return de ? 'Erfolgreich aktualisiert' : 'Updated successfully' case 'current': return de ? 'Bereits aktuell' : 'Already up to date' - case 'partial': return de ? `Teilweise aktualisiert: ${languages}` : `Partially updated: ${languages}` + case 'partial': return de ? `Teilweise aktualisiert${languages}` : `Partially updated${languages}` case 'error': return de ? 'Prüfung fehlgeschlagen; bisherige Texte bleiben erhalten' : 'Check failed; retained previous copy' } } diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 7eaa1f8..a59866f 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -77,8 +77,8 @@ importers: specifier: 18.0.0 version: 18.0.0(@angular/common@18.2.14(@angular/core@18.2.14(rxjs@7.8.2)(zone.js@0.14.10))(rxjs@7.8.2))(@angular/core@18.2.14(rxjs@7.8.2)(zone.js@0.14.10))(rxjs@7.8.2) '@rerune/angular': - specifier: 1.8.0 - version: 1.8.0(@angular/common@18.2.14(@angular/core@18.2.14(rxjs@7.8.2)(zone.js@0.14.10))(rxjs@7.8.2))(@angular/core@18.2.14(rxjs@7.8.2)(zone.js@0.14.10))(@jsverse/transloco@8.4.0(@angular/core@18.2.14(rxjs@7.8.2)(zone.js@0.14.10))(rxjs@7.8.2)(typescript@5.5.4))(@ngx-translate/core@18.0.0(@angular/common@18.2.14(@angular/core@18.2.14(rxjs@7.8.2)(zone.js@0.14.10))(rxjs@7.8.2))(@angular/core@18.2.14(rxjs@7.8.2)(zone.js@0.14.10))(rxjs@7.8.2))(rxjs@7.8.2) + specifier: 1.9.0 + version: 1.9.0(@angular/common@18.2.14(@angular/core@18.2.14(rxjs@7.8.2)(zone.js@0.14.10))(rxjs@7.8.2))(@angular/core@18.2.14(rxjs@7.8.2)(zone.js@0.14.10))(@jsverse/transloco@8.4.0(@angular/core@18.2.14(rxjs@7.8.2)(zone.js@0.14.10))(rxjs@7.8.2)(typescript@5.5.4))(@ngx-translate/core@18.0.0(@angular/common@18.2.14(@angular/core@18.2.14(rxjs@7.8.2)(zone.js@0.14.10))(rxjs@7.8.2))(@angular/core@18.2.14(rxjs@7.8.2)(zone.js@0.14.10))(rxjs@7.8.2))(rxjs@7.8.2) ngx-translate-messageformat-compiler: specifier: 7.3.0 version: 7.3.0(@angular/core@18.2.14(rxjs@7.8.2)(zone.js@0.14.10))(@messageformat/core@3.4.0)(@ngx-translate/core@18.0.0(@angular/common@18.2.14(@angular/core@18.2.14(rxjs@7.8.2)(zone.js@0.14.10))(rxjs@7.8.2))(@angular/core@18.2.14(rxjs@7.8.2)(zone.js@0.14.10))(rxjs@7.8.2)) @@ -110,9 +110,6 @@ importers: '@angular/core': specifier: 18.2.14 version: 18.2.14(rxjs@7.8.2)(zone.js@0.14.10) - '@rerune/core': - specifier: 1.8.0 - version: 1.8.0 examples/angular-transloco: dependencies: @@ -138,8 +135,8 @@ importers: specifier: 1.0.0-beta.5 version: 1.0.0-beta.5 '@rerune/angular': - specifier: 1.8.0 - version: 1.8.0(@angular/common@18.2.14(@angular/core@18.2.14(rxjs@7.8.2)(zone.js@0.14.10))(rxjs@7.8.2))(@angular/core@18.2.14(rxjs@7.8.2)(zone.js@0.14.10))(@jsverse/transloco@8.4.0(@angular/core@18.2.14(rxjs@7.8.2)(zone.js@0.14.10))(rxjs@7.8.2)(typescript@5.5.4))(@ngx-translate/core@18.0.0(@angular/common@18.2.14(@angular/core@18.2.14(rxjs@7.8.2)(zone.js@0.14.10))(rxjs@7.8.2))(@angular/core@18.2.14(rxjs@7.8.2)(zone.js@0.14.10))(rxjs@7.8.2))(rxjs@7.8.2) + specifier: 1.9.0 + version: 1.9.0(@angular/common@18.2.14(@angular/core@18.2.14(rxjs@7.8.2)(zone.js@0.14.10))(rxjs@7.8.2))(@angular/core@18.2.14(rxjs@7.8.2)(zone.js@0.14.10))(@jsverse/transloco@8.4.0(@angular/core@18.2.14(rxjs@7.8.2)(zone.js@0.14.10))(rxjs@7.8.2)(typescript@5.5.4))(@ngx-translate/core@18.0.0(@angular/common@18.2.14(@angular/core@18.2.14(rxjs@7.8.2)(zone.js@0.14.10))(rxjs@7.8.2))(@angular/core@18.2.14(rxjs@7.8.2)(zone.js@0.14.10))(rxjs@7.8.2))(rxjs@7.8.2) rxjs: specifier: 7.8.2 version: 7.8.2 @@ -165,12 +162,15 @@ importers: examples/react-native-expo: dependencies: + '@formatjs/intl-pluralrules': + specifier: 6.3.16 + version: 6.3.16 '@react-native-async-storage/async-storage': specifier: 2.2.0 version: 2.2.0(react-native@0.81.5(@babel/core@7.29.7)(@types/react@19.2.14)(react@19.1.0)) '@rerune/react-native': - specifier: 1.8.0 - version: 1.8.0(i18next@25.10.10(typescript@5.9.3))(react-i18next@15.7.4(i18next@25.10.10(typescript@5.9.3))(react-native@0.81.5(@babel/core@7.29.7)(@types/react@19.2.14)(react@19.1.0))(react@19.1.0)(typescript@5.9.3))(react-native@0.81.5(@babel/core@7.29.7)(@types/react@19.2.14)(react@19.1.0))(react@19.1.0) + specifier: 1.9.0 + version: 1.9.0(@react-native-async-storage/async-storage@2.2.0(react-native@0.81.5(@babel/core@7.29.7)(@types/react@19.2.14)(react@19.1.0)))(i18next@25.10.10(typescript@5.9.3))(react-i18next@15.7.4(i18next@25.10.10(typescript@5.9.3))(react-native@0.81.5(@babel/core@7.29.7)(@types/react@19.2.14)(react@19.1.0))(react@19.1.0)(typescript@5.9.3))(react-native@0.81.5(@babel/core@7.29.7)(@types/react@19.2.14)(react@19.1.0))(react@19.1.0) expo: specifier: 54.0.37 version: 54.0.37(@babel/core@7.29.7)(react-native@0.81.5(@babel/core@7.29.7)(@types/react@19.2.14)(react@19.1.0))(react@19.1.0)(typescript@5.9.3) @@ -202,8 +202,8 @@ importers: examples/react-web-vite: dependencies: '@rerune/react': - specifier: 1.8.0 - version: 1.8.0(i18next@25.10.10(typescript@5.9.3))(react-i18next@15.7.4(i18next@25.10.10(typescript@5.9.3))(react-dom@19.1.0(react@19.1.0))(react@19.1.0)(typescript@5.9.3))(react@19.1.0) + specifier: 1.9.0 + version: 1.9.0(i18next@25.10.10(typescript@5.9.3))(react-i18next@15.7.4(i18next@25.10.10(typescript@5.9.3))(react-dom@19.1.0(react@19.1.0))(react@19.1.0)(typescript@5.9.3))(react@19.1.0) i18next: specifier: ^25.0.0 version: 25.10.10(typescript@5.9.3) @@ -1693,6 +1693,18 @@ packages: resolution: {integrity: sha512-J3eL4n4h5QTwfD0SIz8OIk6/+sOL/hFZAMacgCM07UNlxBQfJipEpIC2AQxvGkbYeStByJ0TVhQAJo+DeNgaSQ==} hasBin: true + '@formatjs/bigdecimal@0.2.7': + resolution: {integrity: sha512-B4+XY/e4u5v261r3a37Kq2ax91gPZSKGyVpx8X5dygAggLlUz+6MeBpmAhaBFGB8WQ4JB1qD+QtKHk9aJkEb9Q==} + + '@formatjs/fast-memoize@3.1.7': + resolution: {integrity: sha512-zXfhLpvA6T7+efdt9JLbBwZ00tT7NsBMDVnDu8rpHeNNv8KfRZAMo2gkG0k9lK/Nzc//3kJ9pImsfuJxk3KhUA==} + + '@formatjs/intl-localematcher@0.9.0': + resolution: {integrity: sha512-Z7TD3ssNry1Av1dVDoq/mzpxGyxqWwU0ClWEo+BB3k0JQTeQvUGmeK9WZGYvlqStS0UqkaKXk3dfjsb6NaHAxw==} + + '@formatjs/intl-pluralrules@6.3.16': + resolution: {integrity: sha512-iOqCpBM2fo7bbbWqno+yN9WioepV01N2q3KawFZhRYADzijpzmIIA6cbFXrriCI1Mt2q5c7mceiKHoQkEFf0/Q==} + '@humanfs/core@0.19.2': resolution: {integrity: sha512-UhXNm+CFMWcbChXywFwkmhqjs3PRCmcSa/hfBgLIb7oQ5HNb1wS0icWsGtSAUNgefHeI+eBrA8I1fxmbHsGdvA==} engines: {node: '>=18.18.0'} @@ -2215,35 +2227,36 @@ packages: '@types/react': optional: true - '@rerune/angular@1.8.0': - resolution: {integrity: sha512-VTKNZARAw98+2uV7f7+PfQDWuHWeivjyIil003nDHYJzROh2cZSVsySs3nX9J5AjifXA50EwkdCEHeI7Y2DzdQ==} + '@rerune/angular@1.9.0': + resolution: {integrity: sha512-sCRDwH0E+t3tLUQlTN/OkrK6WP0QfKsgmUZaT3Js9VT2Ajura+Ot0c+QNNHOajG3Wq9TfHD2oUQ2413Jd5rVPA==} peerDependencies: '@angular/common': '>=18' '@angular/core': '>=18' - '@jsverse/transloco': '>=8 <9' - '@ngx-translate/core': '>=18 <19' - rxjs: '>=7 <8' + '@jsverse/transloco': '>=8' + '@ngx-translate/core': '>=18' + rxjs: '>=7.5.5' peerDependenciesMeta: '@jsverse/transloco': optional: true '@ngx-translate/core': optional: true - '@rerune/core@1.8.0': - resolution: {integrity: sha512-u82FYPy8dYeM6is4lpfiKqZeiFc+ct6VJ75fsDvSCA7UXDJ2QmYrNPQDpWqjiqIonTMvvrhb35WU6lKXYN8Nhg==} + '@rerune/core@1.9.0': + resolution: {integrity: sha512-tn1CEWWi9WOHMeTzz0GliETklj/NMmdc2NtfbQiQZ8COD+so19eQnYrG3ht5I7IVa0WPvjjW8bWp7cYMjI9LiA==} - '@rerune/react-native@1.8.0': - resolution: {integrity: sha512-goGVp7458EVXguYDmG4EmrQWtL6TFM75MdmiR8CANJbAOyvbEmg7j2/ImnvLaRN91DwVsgiHdANVqMPfS2tK2w==} + '@rerune/react-native@1.9.0': + resolution: {integrity: sha512-sLEkPkN+p3vRBXG0D/UAnI0IYJ0C8XVAF6+ARIKbdpAByBXrDxwV7WfbqfisTnR++DdeKozjZv5NT6PBc/J+Zw==} peerDependencies: - i18next: '>=23' + '@react-native-async-storage/async-storage': ^1.23.1 || ^2.1.2 || >=3.1.1 + i18next: '>=23.2.3' react: 19.1.0 react-i18next: '>=14' react-native: 0.81.5 - '@rerune/react@1.8.0': - resolution: {integrity: sha512-GcFKwz6i0M1VnR0tMNV5J7g0/Bxfwd3QCJEQ3Hw0/aVKja/yKrmNKUNIeVBIJzLOPcwUlZVo+Ky6JRKrg2Np3g==} + '@rerune/react@1.9.0': + resolution: {integrity: sha512-an8rXc4exPJhElZPZrmapwBXUUNZ6JO0bdAdxX89h5/A7LkUj9/Eol7xwFsSAePCDmtKcMzRgURV61L1XqDXwg==} peerDependencies: - i18next: '>=23' + i18next: '>=23.2.3' react: 19.1.0 react-i18next: '>=14' @@ -9095,6 +9108,19 @@ snapshots: chalk: 4.1.2 js-yaml: 4.3.2 + '@formatjs/bigdecimal@0.2.7': {} + + '@formatjs/fast-memoize@3.1.7': {} + + '@formatjs/intl-localematcher@0.9.0': + dependencies: + '@formatjs/fast-memoize': 3.1.7 + + '@formatjs/intl-pluralrules@6.3.16': + dependencies: + '@formatjs/bigdecimal': 0.2.7 + '@formatjs/intl-localematcher': 0.9.0 + '@humanfs/core@0.19.2': dependencies: '@humanfs/types': 0.15.0 @@ -9764,41 +9790,41 @@ snapshots: optionalDependencies: '@types/react': 19.2.14 - '@rerune/angular@1.8.0(@angular/common@18.2.14(@angular/core@18.2.14(rxjs@7.8.2)(zone.js@0.14.10))(rxjs@7.8.2))(@angular/core@18.2.14(rxjs@7.8.2)(zone.js@0.14.10))(@jsverse/transloco@8.4.0(@angular/core@18.2.14(rxjs@7.8.2)(zone.js@0.14.10))(rxjs@7.8.2)(typescript@5.5.4))(@ngx-translate/core@18.0.0(@angular/common@18.2.14(@angular/core@18.2.14(rxjs@7.8.2)(zone.js@0.14.10))(rxjs@7.8.2))(@angular/core@18.2.14(rxjs@7.8.2)(zone.js@0.14.10))(rxjs@7.8.2))(rxjs@7.8.2)': + '@rerune/angular@1.9.0(@angular/common@18.2.14(@angular/core@18.2.14(rxjs@7.8.2)(zone.js@0.14.10))(rxjs@7.8.2))(@angular/core@18.2.14(rxjs@7.8.2)(zone.js@0.14.10))(@jsverse/transloco@8.4.0(@angular/core@18.2.14(rxjs@7.8.2)(zone.js@0.14.10))(rxjs@7.8.2)(typescript@5.5.4))(@ngx-translate/core@18.0.0(@angular/common@18.2.14(@angular/core@18.2.14(rxjs@7.8.2)(zone.js@0.14.10))(rxjs@7.8.2))(@angular/core@18.2.14(rxjs@7.8.2)(zone.js@0.14.10))(rxjs@7.8.2))(rxjs@7.8.2)': dependencies: '@angular/common': 18.2.14(@angular/core@18.2.14(rxjs@7.8.2)(zone.js@0.14.10))(rxjs@7.8.2) '@angular/core': 18.2.14(rxjs@7.8.2)(zone.js@0.14.10) - '@rerune/core': 1.8.0 + '@rerune/core': 1.9.0 rxjs: 7.8.2 tslib: 2.8.1 optionalDependencies: '@jsverse/transloco': 8.4.0(@angular/core@18.2.14(rxjs@7.8.2)(zone.js@0.14.10))(rxjs@7.8.2)(typescript@5.5.4) '@ngx-translate/core': 18.0.0(@angular/common@18.2.14(@angular/core@18.2.14(rxjs@7.8.2)(zone.js@0.14.10))(rxjs@7.8.2))(@angular/core@18.2.14(rxjs@7.8.2)(zone.js@0.14.10))(rxjs@7.8.2) - '@rerune/core@1.8.0': + '@rerune/core@1.9.0': dependencies: '@noble/hashes': 1.8.0 - '@rerune/react-native@1.8.0(i18next@25.10.10(typescript@5.9.3))(react-i18next@15.7.4(i18next@25.10.10(typescript@5.9.3))(react-native@0.81.5(@babel/core@7.29.7)(@types/react@19.2.14)(react@19.1.0))(react@19.1.0)(typescript@5.9.3))(react-native@0.81.5(@babel/core@7.29.7)(@types/react@19.2.14)(react@19.1.0))(react@19.1.0)': + '@rerune/react-native@1.9.0(@react-native-async-storage/async-storage@2.2.0(react-native@0.81.5(@babel/core@7.29.7)(@types/react@19.2.14)(react@19.1.0)))(i18next@25.10.10(typescript@5.9.3))(react-i18next@15.7.4(i18next@25.10.10(typescript@5.9.3))(react-native@0.81.5(@babel/core@7.29.7)(@types/react@19.2.14)(react@19.1.0))(react@19.1.0)(typescript@5.9.3))(react-native@0.81.5(@babel/core@7.29.7)(@types/react@19.2.14)(react@19.1.0))(react@19.1.0)': dependencies: '@react-native-async-storage/async-storage': 2.2.0(react-native@0.81.5(@babel/core@7.29.7)(@types/react@19.2.14)(react@19.1.0)) - '@rerune/core': 1.8.0 - '@rerune/react': 1.8.0(i18next@25.10.10(typescript@5.9.3))(react-i18next@15.7.4(i18next@25.10.10(typescript@5.9.3))(react-native@0.81.5(@babel/core@7.29.7)(@types/react@19.2.14)(react@19.1.0))(react@19.1.0)(typescript@5.9.3))(react@19.1.0) + '@rerune/core': 1.9.0 + '@rerune/react': 1.9.0(i18next@25.10.10(typescript@5.9.3))(react-i18next@15.7.4(i18next@25.10.10(typescript@5.9.3))(react-native@0.81.5(@babel/core@7.29.7)(@types/react@19.2.14)(react@19.1.0))(react@19.1.0)(typescript@5.9.3))(react@19.1.0) i18next: 25.10.10(typescript@5.9.3) react: 19.1.0 react-i18next: 15.7.4(i18next@25.10.10(typescript@5.9.3))(react-native@0.81.5(@babel/core@7.29.7)(@types/react@19.2.14)(react@19.1.0))(react@19.1.0)(typescript@5.9.3) react-native: 0.81.5(@babel/core@7.29.7)(@types/react@19.2.14)(react@19.1.0) - '@rerune/react@1.8.0(i18next@25.10.10(typescript@5.9.3))(react-i18next@15.7.4(i18next@25.10.10(typescript@5.9.3))(react-dom@19.1.0(react@19.1.0))(react@19.1.0)(typescript@5.9.3))(react@19.1.0)': + '@rerune/react@1.9.0(i18next@25.10.10(typescript@5.9.3))(react-i18next@15.7.4(i18next@25.10.10(typescript@5.9.3))(react-dom@19.1.0(react@19.1.0))(react@19.1.0)(typescript@5.9.3))(react@19.1.0)': dependencies: - '@rerune/core': 1.8.0 + '@rerune/core': 1.9.0 i18next: 25.10.10(typescript@5.9.3) react: 19.1.0 react-i18next: 15.7.4(i18next@25.10.10(typescript@5.9.3))(react-dom@19.1.0(react@19.1.0))(react@19.1.0)(typescript@5.9.3) - '@rerune/react@1.8.0(i18next@25.10.10(typescript@5.9.3))(react-i18next@15.7.4(i18next@25.10.10(typescript@5.9.3))(react-native@0.81.5(@babel/core@7.29.7)(@types/react@19.2.14)(react@19.1.0))(react@19.1.0)(typescript@5.9.3))(react@19.1.0)': + '@rerune/react@1.9.0(i18next@25.10.10(typescript@5.9.3))(react-i18next@15.7.4(i18next@25.10.10(typescript@5.9.3))(react-native@0.81.5(@babel/core@7.29.7)(@types/react@19.2.14)(react@19.1.0))(react@19.1.0)(typescript@5.9.3))(react@19.1.0)': dependencies: - '@rerune/core': 1.8.0 + '@rerune/core': 1.9.0 i18next: 25.10.10(typescript@5.9.3) react: 19.1.0 react-i18next: 15.7.4(i18next@25.10.10(typescript@5.9.3))(react-native@0.81.5(@babel/core@7.29.7)(@types/react@19.2.14)(react@19.1.0))(react@19.1.0)(typescript@5.9.3) diff --git a/scripts/refresh.test.mjs b/scripts/refresh.test.mjs index 9af0f83..06232f4 100644 --- a/scripts/refresh.test.mjs +++ b/scripts/refresh.test.mjs @@ -14,3 +14,13 @@ test('partial status identifies changed languages without claiming every other l assert.equal(refreshText('partial', 'de-DE', ['en']), 'Teilweise aktualisiert: en') assert.equal(refreshText('error', 'en'), 'Check failed; retained previous copy') }) + +test('partial status without changed texts names no languages', () => { + // Since 1.9.0, a removed language or a renamed one also sets hasUpdates, with no entry in updatedLocales. + assert.equal(classifyCheck({ hasErrors: true, hasUpdates: true }), 'partial') + assert.equal(refreshText('partial', 'en', []), 'Partially updated') + assert.equal(refreshText('partial', 'de', []), 'Teilweise aktualisiert') + assert.equal(refreshText('partial', 'es'), 'Actualizado parcialmente') + assert.equal(refreshText('partial', 'it', []), 'Aggiornamento parziale') + assert.equal(refreshText('partial', 'pt', []), 'Atualizado parcialmente') +}) diff --git a/scripts/sdk-consumer.test.mjs b/scripts/sdk-consumer.test.mjs index 56709f8..86583b8 100644 --- a/scripts/sdk-consumer.test.mjs +++ b/scripts/sdk-consumer.test.mjs @@ -1,12 +1,15 @@ import assert from 'node:assert/strict' import { createRequire } from 'node:module' import test from 'node:test' +import { classifyCheck, refreshText } from '../examples/shared/refresh.ts' // Resolve the public packages installed by the React example, never SDK source. const require = createRequire(new URL('../examples/react-web-vite/package.json', import.meta.url)) -const { ReRune, createReRuneBrowserCacheStore } = require('@rerune/react') +const { ReRune } = require('@rerune/react') const i18next = require('i18next') +const bundled = { lng: 'en', fallbackLng: 'en', resources: { en: { translation: { welcome_title: 'Bundled' } } } } + function storageFixture() { const disk = new Map() return { @@ -20,44 +23,101 @@ function storageFixture() { } } -test('published browser store keeps newer session copy over stale disk after a failed write', async () => { +// The examples use the SDK's default browser store, which reads globalThis.localStorage on every access. +function useLocalStorage(t) { const storage = storageFixture() - const options = { prefix: 'consumer-test', storage } - const store = createReRuneBrowserCacheStore(options) - const old = { payload: '[]', version: 1, minimumDeltaBaseVersion: 1, url: 'https://fixture.invalid/en.json' } - const next = { ...old, version: 2 } - await store.writeLocale('en', old) - await store.writeVariant('Main') - storage.blocked = true - await store.writeLocale('en', next) - await store.writeVariant('vip') - assert.deepEqual(await store.readLocale('en'), next) - assert.equal(await store.readVariant(), 'vip') - const restarted = createReRuneBrowserCacheStore(options) - assert.deepEqual(await restarted.readLocale('en'), old) - assert.equal(await restarted.readVariant(), 'Main') - storage.blocked = false - await store.writeLocale('en', next) - await store.writeVariant('vip') - assert.deepEqual(await restarted.readLocale('en'), next) - assert.equal(await restarted.readVariant(), 'vip') + Object.defineProperty(globalThis, 'localStorage', { configurable: true, value: storage }) + t.after(() => { delete globalThis.localStorage }) + return storage +} + +function memoryStore() { + const values = new Map() + return { + readManifest: async () => values.get('manifest') ?? null, + writeManifest: async value => { values.set('manifest', value) }, + readLocale: async locale => values.get(`locale:${locale}`) ?? null, + writeLocale: async (locale, value) => { values.set(`locale:${locale}`, value) }, + removeLocale: async locale => { values.delete(`locale:${locale}`) }, + } +} + +function hosted(remote) { + return async input => { + if (!remote.online) throw new TypeError('Offline') + if (String(input).includes('manifest')) { + return Response.json({ version: remote.version, main_language: 'en', locales: Object.fromEntries(Object.entries(remote.locales).map(([locale, name]) => [locale, { + name, version: remote.version, minimum_delta_base_version: remote.version, url: `https://fixture.invalid/${locale}.json`, + }])) }) + } + const locale = new URL(String(input)).pathname.slice(1).replace('.json', '') + if (remote.failed.has(locale)) return new Response(null, { status: 503 }) + return Response.json(remote.records ?? [{ key: 'welcome_title', values: [{ lang: locale, value: `Published ${remote.version}` }] }]) + } +} + +test('published default browser store: a failed write keeps the update for the session, a restart reads the last saved copy, and the next write persists', async t => { + const storage = useLocalStorage(t) + const remote = { online: true, version: 1, locales: { en: 'English' }, failed: new Set() } + const start = () => ReRune.setup({ otaPublishId: 'consumer-test', logLevel: 'off', updatePolicy: { checkOnStart: false }, fetch: hosted(remote) }, bundled) + const client = start() + const clients = [client] + try { + await client.initialize() + await client.checkForUpdates() + assert.equal(client.i18n.t('welcome_title'), 'Published 1') + storage.blocked = true + remote.version = 2 + const blocked = await client.checkForUpdates() + assert.equal(blocked.hasErrors, false) + assert.deepEqual(blocked.updatedLocales, ['en']) + // A failed variant save resolves and keeps the variant for this session. + await client.setVariant({ variant: 'vip', persist: true }) + assert.equal(client.getState().variant, 'vip') + assert.equal(client.i18n.t('welcome_title'), 'Published 2') + + remote.online = false + const restarted = start() + clients.push(restarted) + await restarted.initialize() + assert.equal(restarted.i18n.t('welcome_title'), 'Published 1') + assert.equal(restarted.getState().variant, ReRune.Main) + // Checks resolve with their errors instead of rejecting. + const offline = await restarted.checkForUpdates() + assert.equal(classifyCheck(offline), 'error') + + storage.blocked = false + remote.online = true + remote.version = 3 + await client.checkForUpdates() + await client.setVariant({ variant: 'vip', persist: true }) + const again = start() + clients.push(again) + remote.online = false + await again.initialize() + assert.equal(again.i18n.t('welcome_title'), 'Published 3') + assert.equal(again.getState().variant, 'vip') + } finally { + for (const started of clients) started.dispose() + } }) -test('published React setup preserves late i18next writes and activates OTA after cache-write failure', async () => { +test('published React setup preserves late i18next writes and activates OTA after cache-write failure', async t => { + const storage = useLocalStorage(t) const i18n = i18next.createInstance() - const storage = storageFixture() let version = 1 let records = [{ key: 'welcome_title', values: [{ lang: 'en', value: 'Published' }] }] - const client = await ReRune.setup({ - i18n, otaPublishId: 'public-consumer-test', logLevel: 'off', - cacheStore: createReRuneBrowserCacheStore({ storage }), updatePolicy: { checkOnStart: false }, + const client = ReRune.setup({ + i18n, otaPublishId: 'public-consumer-test', logLevel: 'off', updatePolicy: { checkOnStart: false }, fetch: async url => Response.json(String(url).includes('manifest') ? { version, main_language: 'en', locales: { en: { version, minimum_delta_base_version: version, url: 'https://fixture.invalid/en.json' } }, } : records), - }, { lng: 'en', fallbackLng: 'en', resources: { en: { translation: { welcome_title: 'Bundled' } } } }) + }, bundled) try { + // Inline resources initialize i18next synchronously, so the client is ready on return. assert.equal(client.i18n, i18n) assert.equal(i18n.isInitialized, true) + await client.ready await client.initialize() const initial = await client.checkForUpdates() assert.equal(initial.hasErrors, false) @@ -79,12 +139,13 @@ test('published React setup preserves late i18next writes and activates OTA afte } }) -test('native setup waits for the i18next loader without waiting for cache restoration', { timeout: 5000 }, async () => { +test('React setup returns at once, waits for the i18next loader, and reads storage only after ready', { timeout: 5000 }, async () => { const i18n = i18next.createInstance() const nativeRead = Promise.withResolvers() const cacheRead = Promise.withResolvers() + const cacheReads = [] let releaseNative - let resolved = false + let ready = false i18n.use({ type: 'backend', read(_language, _namespace, done) { @@ -92,33 +153,61 @@ test('native setup waits for the i18next loader without waiting for cache restor nativeRead.resolve() }, }) - const pending = ReRune.setup({ + const options = { i18n, otaPublishId: 'native-setup-test', logLevel: 'off', updatePolicy: { checkOnStart: false }, - cacheStore: { - ...createReRuneBrowserCacheStore({ storage: storageFixture() }), - readManifest: () => cacheRead.promise, - }, - }, { lng: 'en', fallbackLng: false }) - void pending.then(() => { resolved = true }) + cacheStore: { ...memoryStore(), readManifest: () => { cacheReads.push('manifest'); return cacheRead.promise } }, + } + const client = ReRune.setup(options, { lng: 'en', fallbackLng: false }) + void client.ready.then(() => { ready = true }) + assert.equal(client.i18n, i18n) + // Setup with the same instance returns the same client instead of initializing again. + assert.equal(ReRune.setup(options, { lng: 'en' }), client) await nativeRead.promise - assert.equal(resolved, false) + const initializing = client.initialize() + await new Promise(resolve => setImmediate(resolve)) + assert.equal(ready, false) + assert(!i18n.isInitialized) + assert.deepEqual(cacheReads, []) releaseNative() - const client = await pending try { - assert.equal(client.i18n, i18n) + await client.ready assert.equal(i18n.isInitialized, true) assert.equal(i18n.t('welcome_title'), 'Native loader copy') - await assert.rejects(ReRune.setup({ i18n, otaPublishId: 'duplicate-init-test' }, { lng: 'en' }), /already initialized/) + await new Promise(resolve => setImmediate(resolve)) + assert.deepEqual(cacheReads, ['manifest']) } finally { cacheRead.resolve(null) - await client.initialize() + await initializing client.dispose() } }) +test('refresh feedback follows published update results, including removed and renamed languages', async () => { + const remote = { online: true, version: 1, locales: { en: 'English', fr: 'French' }, failed: new Set() } + const client = ReRune.setup({ otaPublishId: 'refresh-consumer-test', logLevel: 'off', updatePolicy: { checkOnStart: false }, cacheStore: memoryStore(), fetch: hosted(remote) }, bundled) + const feedback = result => refreshText(classifyCheck(result), 'en', result.updatedLocales) + try { + await client.initialize() + assert.equal(feedback(await client.checkForUpdates()), 'Updated successfully') + assert.equal(feedback(await client.checkForUpdates()), 'Already up to date') + remote.locales.fr = 'Français' + const renamed = await client.checkForUpdates() + assert.deepEqual([renamed.updatedLocales, renamed.updatedLocaleNames], [[], ['fr']]) + assert.equal(feedback(renamed), 'Updated successfully') + remote.version = 2 + delete remote.locales.fr + remote.failed.add('en') + const removed = await client.checkForUpdates() + assert.deepEqual([removed.updatedLocales, removed.removedLocales, removed.hasErrors], [[], ['fr'], true]) + assert.equal(feedback(removed), 'Partially updated') + remote.online = false + assert.equal(feedback(await client.checkForUpdates()), 'Check failed; retained previous copy') + } finally { client.dispose() } +}) + test('published SDK accepts hosted cardinal plurals with explicit numeric offset zero', async () => { - const client = await ReRune.setup({ - otaPublishId: 'zero-offset-consumer-test', logLevel: 'off', updatePolicy: { checkOnStart: false }, + const client = ReRune.setup({ + otaPublishId: 'zero-offset-consumer-test', logLevel: 'off', updatePolicy: { checkOnStart: false }, cacheStore: memoryStore(), fetch: async url => Response.json(String(url).includes('manifest') ? { version: 1, main_language: 'en', locales: { en: { version: 1, minimum_delta_base_version: 1, url: 'https://fixture.invalid/en.json' } }, } : [{ key: 'plural_sample', placeholders: [{ name: 'count', type: 'int' }], values: [{ lang: 'en', @@ -138,7 +227,8 @@ test('published SDK accepts hosted cardinal plurals with explicit numeric offset } finally { client.dispose() } }) -test('published SDK switches between isolated staging and production snapshots', async () => { +test('published SDK switches between isolated staging and production snapshots', async t => { + useLocalStorage(t) const requests = [] const fetch = async (input, init = {}) => { const url = new URL(String(input)) @@ -169,14 +259,13 @@ test('published SDK switches between isolated staging and production snapshots', ], { headers: { ETag: staging ? '"staging-en"' : '"production-en"' } }) } - const client = await ReRune.setup({ + const client = ReRune.setup({ otaPublishId: 'staging-consumer-test', staging: true, logLevel: 'off', updatePolicy: { checkOnStart: false }, - cacheStore: createReRuneBrowserCacheStore({ storage: storageFixture(), prefix: 'staging-consumer' }), fetch, - }, { lng: 'en', fallbackLng: 'en', resources: { en: { translation: { welcome_title: 'Bundled' } } } }) + }, bundled) try { await client.initialize() @@ -193,11 +282,15 @@ test('published SDK switches between isolated staging and production snapshots', assert(firstStagingLocale) assert.equal(firstStagingLocale.url.pathname, '/en.json') - await client.setStaging(false) + // Each switch resolves with the update result of the check it runs. + const production = await client.setStaging(false) + assert.equal(production.hasErrors, false) + assert.deepEqual(production.updatedLocales, ['en']) assert.equal(client.isStaging(), false) assert.equal(client.i18n.t('welcome_title'), 'Published') - await client.setStaging(true) + const draft = await client.setStaging(true) + assert.equal(draft.hasErrors, false) assert.equal(client.isStaging(), true) assert.equal(client.i18n.t('welcome_title'), 'Draft') const stagingLocaleRequests = requests.filter(({ url }) => diff --git a/tests/browser/ota.spec.ts b/tests/browser/ota.spec.ts index e888cae..a580a69 100644 --- a/tests/browser/ota.spec.ts +++ b/tests/browser/ota.spec.ts @@ -83,14 +83,19 @@ for (const [engine, port] of [['react', 15173], ['ngx', 14201], ['transloco', 14 await expect(title).toHaveText('Live en 1') await expect(page.locator('progress')).toHaveAttribute('value', '1') await expect(page.getByTestId('bookmark-atlas')).toHaveAttribute('aria-pressed', 'true') - expect([...requests].sort()).toEqual(['de', 'en', 'fr']) + // A check downloads only the shown language and its fallbacks. + expect([...requests].sort()).toEqual(['en']) await expect(page.locator('select option')).toHaveCount(7) // system + five bundles + remote French + const checked = manifests await page.locator('select').selectOption('fr') await expect(title).toHaveText('Live fr 1') await page.locator('select').selectOption('de') await expect(title).toHaveText('Live de 1') await page.locator('select').selectOption('en') await expect(title).toHaveText('Live en 1') + // A language switch downloads that language without a manifest request. + expect(manifests).toBe(checked) + expect([...requests].sort()).toEqual(['de', 'en', 'fr']) await page.getByRole('button', { name: 'Back to library', exact: true }).click() await settings.click() await expect(sheet.locator('.samples')).toHaveText('Published 14.07.2026One published key2 published keys') @@ -100,7 +105,7 @@ for (const [engine, port] of [['react', 15173], ['ngx', 14201], ['transloco', 14 await expect(page.locator('.staging-banner')).toBeVisible() await close() await expect(title).toHaveText('Draft VIP en 1') - expect([...stagingEndpoints].sort()).toEqual([`/api/ota/${publishId}/manifest.json`, '/de.json', '/en.json', '/fr.json']) + expect([...stagingEndpoints].sort()).toEqual([`/api/ota/${publishId}/manifest.json`, '/en.json']) await settings.click() await sheet.getByRole('switch', { name: 'Staging mode' }).click() await expect(page.locator('.staging-banner')).toHaveCount(0) @@ -132,17 +137,19 @@ for (const [engine, port] of [['react', 15173], ['ngx', 14201], ['transloco', 14 await close() await expect(title).toHaveText('Live en 1') remote.online = true - remote.versions = { en: 2, de: 2, fr: 1 } - remote.failed.add('de') + remote.versions = { en: 2, de: 1, fr: 2 } + remote.failed.add('fr') + // With French shown, a check evaluates French and its English fallback. + await page.locator('select').selectOption('fr') + await expect(title).toHaveText('Live fr 1') await check.click() await expect(feedback).toHaveText('Partially updated: en') - await expect(title).toHaveText('Live en 2') - await page.locator('select').selectOption('de') - await expect(title).toHaveText('Live de 1') - await page.locator('select').selectOption('en') + await expect(title).toHaveText('Live fr 1') await page.screenshot({ path: testInfo.outputPath('partial.png'), animations: 'disabled' }) await check.click() await expect(feedback).toHaveText('Check failed; retained previous copy') + await expect(title).toHaveText('Live fr 1') + await page.locator('select').selectOption('en') await expect(title).toHaveText('Live en 2') remote.online = false await page.getByRole('button', { name: 'Continue reading', exact: true }).click()