Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@tolgee/core

Package Overview
Dependencies
Maintainers
2
Versions
357
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@tolgee/core - npm Package Compare versions

Comparing version 4.9.2 to 5.0.0-rc.0b3e627.0

lib/constants.d.ts

11

lib/index.d.ts
export { Tolgee } from './Tolgee';
export { TolgeeConfig } from './TolgeeConfig';
export { ModifierKey } from './Constants/ModifierKey';
export { TOLGEE_WRAPPED_ONLY_DATA_ATTRIBUTE } from './Constants/Global';
export * from './modules';
export * from './types/DTOs';
export { RESTRICTED_ASCENDANT_ATTRIBUTE, DEVTOOLS_ID, TOLGEE_ATTRIBUTE_NAME, TOLGEE_HIGHLIGHTER_CLASS, TOLGEE_WRAPPED_ONLY_DATA_ATTRIBUTE, } from './constants';
export * from './types';
export * from './Constants/Global';
export * from './helpers/NodeHelper';
export * from './helpers/TextHelper';
export { getTranslateParams } from './TranslateParams';
export { getFallback, getFallbackArray } from './Controller/State/helpers';

@@ -1,68 +0,2 @@

import { TolgeeConfig } from './TolgeeConfig';
import { InstantProps, InstantPropsTags, TolgeeModule, TranslateProps, TranslatePropsTags, TranslationTags, TranslationParams, TranslationParamsTags } from './types';
export declare class Tolgee {
private dependencyService;
private constructor();
get properties(): import("./Properties").Properties;
get lang(): string;
/**
* This sets a new language.
*
* Using this setter can behave buggy when you change languages
* too fast, since it changes the language property before
* translations are actually loaded.
* @deprecated use asynchronous changeLanguage method.
*/
set lang(newLanguage: string);
get defaultLanguage(): string;
get onLangChange(): import("./services/EventEmitter").EventEmitter<string>;
get onTranslationChange(): import("./services/EventEmitter").EventEmitter<import(".").TranslationData>;
/**
* Is emitted when language is loaded for the first time
*/
get onLangLoaded(): import("./services/EventEmitter").EventEmitter<string>;
/**
* True if loading is needed to wait for Tolgee init.
* When translation data are provided statically (using import
* as staticData config property) then there is no need for translation
* fetching so initial loading is not needed at all.
*/
get initialLoading(): boolean;
private get coreService();
static use(module: TolgeeModule): Tolgee;
static init(config: TolgeeConfig): Tolgee;
/**
* Sets the new language.
*
* Emits the onLangChange and onLangChangeAndLoad events after
* the translations are loaded.
*
* @return Promise<void> Resolves when translations are loaded
*/
changeLanguage(newLanguage: string): Promise<void>;
use(module: TolgeeModule): this;
init(config: TolgeeConfig): this;
run(): Promise<void>;
refresh(): Promise<void>;
translate(props: TranslateProps): Promise<string>;
translate<T>(props: TranslatePropsTags<T>): Promise<TranslationTags<T>>;
translate(key: string, params?: TranslationParams, noWrap?: boolean, defaultValue?: string): Promise<string>;
translate<T>(key: string, params?: TranslationParamsTags<T>, noWrap?: boolean, defaultValue?: string): Promise<TranslationTags<T>>;
wrap(key: string, params?: TranslationParams, defaultValue?: string | undefined, translation?: string): string;
wrap<T>(key: string, params?: TranslationTags<T>, defaultValue?: string | undefined, translation?: TranslationTags<T>): TranslationTags<T>;
instant(key: string, params?: TranslationParams, noWrap?: boolean, orEmpty?: boolean, defaultValue?: string): string;
instant<T>(key: string, params?: TranslationParamsTags<T>, noWrap?: boolean, orEmpty?: boolean, defaultValue?: string): TranslationTags<T>;
instant(props: InstantProps): string;
instant<T>(props: InstantPropsTags<T>): TranslationTags<T>;
/**
* Get currently cached translations for all languages
*/
getCachedTranslations(): Map<string, import("./types").Translations>;
/**
* Loads translations for given language or returns them from cache
* @returns Loaded translations
*/
loadTranslations(lang: string): Promise<import("./types").Translations>;
stop: () => void;
private emitLangChangeEvent;
}
import { Options, TolgeeInstance } from './types';
export declare const Tolgee: (options?: Partial<Options>) => TolgeeInstance;

@@ -1,82 +0,199 @@

export interface TextInputElementData {
oldValue: string;
valueInputs: string[];
touched: boolean;
oldPlaceholder: string;
placeholderInputs: string[];
}
export declare type TreeTranslationsData = {
[key: string]: string | TreeTranslationsData;
};
export declare type Translations = Record<string, string>;
export declare type TranslationParams = {
[key: string]: string | number | bigint;
};
export declare type TranslationParamsTags<T> = {
[key: string]: string | number | bigint | ((value: T | T[]) => T);
};
export declare type TranslateProps = {
key: string;
defaultValue?: string;
params?: TranslationParams;
import type { Options } from './Controller/State/initState';
export type { State, Options } from './Controller/State/initState';
export type { EventEmitterType } from './Events/EventEmitter';
export type { EventEmitterSelectiveType } from './Events/EventEmitterSelective';
export declare type FallbackGeneral = undefined | false | string | string[];
export declare type FallbackNS = FallbackGeneral;
export declare type NsType = string;
export declare type KeyType = string;
export declare type FallbackNSTranslation = undefined | NsType | NsType[];
export declare type FallbackLanguage = FallbackGeneral;
export declare type FallbackLanguageObject = Record<string, FallbackLanguage>;
export declare type FallbackLanguageOption = FallbackLanguage | FallbackLanguageObject;
export declare type TranslateOptions<T> = {
ns?: FallbackNSTranslation;
noWrap?: boolean;
orEmpty?: boolean;
params?: TranslateParams<T>;
};
export declare type TranslatePropsTags<T> = {
key: string;
export declare type TranslateProps<T = DefaultParamType> = {
key: KeyType;
defaultValue?: string;
params?: TranslationParamsTags<T>;
noWrap?: boolean;
orEmpty?: boolean;
} & TranslateOptions<T>;
export declare type TranslatePropsInternal = TranslateProps & {
translation?: string;
};
export declare type InstantProps = {
key: string;
defaultValue?: string;
params?: TranslationParams;
noWrap?: boolean;
orEmpty?: boolean;
export declare type TranslationValue = string | undefined | null;
export declare type TranslationsFlat = Map<string, TranslationValue>;
export declare type TreeTranslationsData = {
[key: string]: TranslationValue | TreeTranslationsData;
};
export declare type InstantPropsTags<T> = {
key: string;
defaultValue?: string;
params?: TranslationParamsTags<T>;
noWrap?: boolean;
orEmpty?: boolean;
export declare type CacheAsyncRequests = Map<string, Promise<TreeTranslationsData | undefined> | undefined>;
export declare type CacheDescriptor = {
language: string;
namespace?: string;
};
export declare type CacheDescriptorInternal = {
language: string;
namespace: string;
};
export declare type CacheDescriptorWithKey = CacheDescriptorInternal & {
key?: string;
};
export declare type KeyAndParams = {
key: string;
params: TranslationParams;
params?: TranslateParams;
defaultValue?: string;
ns?: FallbackNSTranslation;
};
export declare type KeyAndParamsTags<T> = {
key: string;
params: TranslationParamsTags<T>;
defaultValue?: string;
export declare type Unwrapped = {
text: string;
keys: KeyAndParams[];
};
export declare type TranslatedWithMetadata = {
translated: string;
key: string;
params: TranslationParams;
defaultValue: string | undefined;
declare type PropType<TObj> = TObj[keyof TObj];
export declare type DefaultParamType = string | number | bigint;
export declare type TranslateParams<T = DefaultParamType> = {
[key: string]: T;
};
export declare type TranslatedWithMetadataTags<T> = {
translated: TranslationTags<T>;
key: string;
params: TranslationParamsTags<T>;
defaultValue: string | undefined;
export declare type CombinedOptions<T> = TranslateOptions<T> & {
[key: string]: T | PropType<TranslateOptions<T>>;
};
export declare type TranslationTags<T> = string | T[];
export declare type NodeWithMeta = Node & {
_tolgee: NodeMeta;
export declare type TFnType<T = DefaultParamType, R = string> = {
(key: string, defaultValue?: string, options?: CombinedOptions<T>): R;
(key: string, options?: CombinedOptions<T>): R;
(props: TranslateProps<T>): R;
};
export declare type NodeWithLock = Node & {
_tolgee: NodeLock;
export declare type WrapperWrapProps = Pick<TranslatePropsInternal, 'key' | 'params' | 'defaultValue' | 'ns' | 'translation'>;
export declare type WrapperWrapFunction = (props: WrapperWrapProps) => string;
export declare type WrapperUnwrapFunction = (text: string) => Unwrapped;
export declare type WrapperAttributeXPathGetter = (props: {
tag: string;
attribute: string;
}) => string;
export declare type WrapperInterface = {
unwrap: WrapperUnwrapFunction;
wrap: WrapperWrapFunction;
getTextXPath: () => string;
getAttributeXPath: WrapperAttributeXPathGetter;
};
export declare type ElementWithMeta = Element & ElementCSSInlineStyle & {
_tolgee: ElementMeta;
export declare type FormatterInterfaceFormatParams = {
translation: string;
language: string;
params: Record<string, any> | undefined;
};
export declare type FormatterInterface = {
format: (props: FormatterInterfaceFormatParams) => string;
};
export declare type FinalFormatterInterface = {
format: (props: FormatterInterfaceFormatParams) => any;
};
export declare type ObserverProps = {
translate: (params: TranslatePropsInternal) => string;
onClick: TranslationOnClick;
};
export declare type HighlightInterface = (key?: string, ns?: FallbackNSTranslation) => {
unhighlight(): void;
};
export declare type ObserverRunProps = {
mouseHighlight: boolean;
};
export declare type ObserverInterface = (props: ObserverProps) => {
unwrap: (text: string) => Unwrapped;
wrap: WrapperWrapFunction;
retranslate: () => void;
stop: () => void;
run: (props: ObserverRunProps) => void;
highlight: HighlightInterface;
outputNotFormattable: boolean;
};
export declare type LanguageDetectorProps = {
availableLanguages: string[];
};
export declare type LanguageDetectorInterface = {
getLanguage: (props: LanguageDetectorProps) => string | undefined | Promise<string | undefined>;
};
export declare type LanguageStorageInterface = {
getLanguage: () => string | undefined | Promise<string | undefined>;
setLanguage: (language: string) => void | Promise<void>;
};
export declare type BackendDevProps = {
apiUrl?: string;
apiKey?: string;
projectId?: number;
};
export declare type BackendGetRecordProps = {
language: string;
namespace?: string;
};
export declare type BackendGetRecord = (data: BackendGetRecordProps) => Promise<TreeTranslationsData | undefined> | undefined;
export interface BackendInterface {
getRecord: BackendGetRecord;
}
export declare type BackendGetDevRecord = (data: BackendGetRecordProps & BackendDevProps) => Promise<TreeTranslationsData | undefined> | undefined;
export declare type BackendDevInterface = {
getRecord: BackendGetDevRecord;
};
export declare type TolgeeEvent = 'pendingLanguage' | 'language' | 'key' | 'loading' | 'fetching' | 'initialLoad' | 'running' | 'cache' | 'keyUpdate';
export declare type TolgeeOn = {
(event: 'pendingLanguage', handler: ListenerHandler<string>): Listener;
(event: 'language', handler: ListenerHandler<string>): Listener;
(event: 'key', handler: ListenerHandler<string>): Listener;
(event: 'loading', handler: ListenerHandler<boolean>): Listener;
(event: 'fetching', handler: ListenerHandler<boolean>): Listener;
(event: 'initialLoad', handler: ListenerHandler<void>): Listener;
(event: 'running', handler: ListenerHandler<boolean>): Listener;
(event: 'keyUpdate', handler: ListenerHandler<void>): Listener;
(event: TolgeeEvent, handler: ListenerHandler<any>): Listener;
};
export declare type TolgeeInstance = Readonly<{
on: TolgeeOn;
onKeyUpdate: (handler: ListenerHandler<void>) => ListenerSelective;
use: (plugin: TolgeePlugin | undefined) => TolgeeInstance;
getLanguage: () => string | undefined;
getPendingLanguage: () => string | undefined;
changeLanguage: (language: string) => Promise<void>;
changeTranslation: ChangeTranslationInterface;
addActiveNs: (ns: FallbackNSTranslation, forget?: boolean) => Promise<void>;
removeActiveNs: (ns: FallbackNSTranslation) => void;
loadRecords: (descriptors: CacheDescriptor[]) => Promise<TranslationsFlat[]>;
loadRecord: (descriptors: CacheDescriptor) => Promise<TranslationsFlat>;
addStaticData: (data: Options['staticData']) => void;
getRecord: (descriptor: CacheDescriptorInternal) => TranslationsFlat | undefined;
getAllRecords: () => CachePublicRecord[];
isInitialLoading: () => boolean;
isLoading: (ns?: FallbackNSTranslation) => boolean;
isLoaded: (ns?: FallbackNSTranslation) => boolean;
isFetching: (ns?: FallbackNSTranslation) => boolean;
isRunning: () => boolean;
highlight: HighlightInterface;
getInitialOptions: () => Options;
isDev: () => boolean;
init: (options: Partial<Options>) => TolgeeInstance;
run: () => Promise<void>;
stop: () => void;
t: (props: TranslatePropsInternal) => string;
wrap: (params: TranslatePropsInternal) => string | undefined;
unwrap: (text: string) => Unwrapped;
}>;
export declare type PluginServicePublic = Readonly<{
setFinalFormatter: (formatter: FinalFormatterInterface | undefined) => void;
addFormatter: (formatter: FormatterInterface | undefined) => void;
setObserver: (observer: ObserverInterface | undefined) => void;
getObserver: () => ReturnType<ObserverInterface> | undefined;
setUi: (ui: UiLibInterface | undefined) => void;
getUi: () => UiConstructor | undefined;
addBackend: (backend: BackendInterface | undefined) => void;
setDevBackend: (backend: BackendInterface | undefined) => void;
setLanguageDetector: (languageDetector: LanguageDetectorInterface | undefined) => void;
setLanguageStorage: (languageStorage: LanguageStorageInterface | undefined) => void;
}>;
export declare type NodeMeta = {
oldTextContent: string;
keys: KeyAndParams[];
keyAttributeOnly?: boolean;
};
export declare type ElementMeta = {
wrappedWithElementOnlyKey?: string;
wrappedWithElementOnlyDefaultHtml?: string;
nodes: Set<NodeWithMeta>;
nodes: Map<Node, NodeMeta>;
highlightEl?: HTMLDivElement;

@@ -97,28 +214,62 @@ highlight?: () => void;

};
export declare type NodeMeta = {
oldTextContent: string;
keys: KeyAndParamsTags<any>[];
} & NodeLock;
export declare type NodeLock = {
locked?: boolean;
export declare type ChangeTranslationInterface = (descriptor: CacheDescriptor, key: string, value: string) => {
revert: () => void;
};
export declare type Scope = 'translations.edit' | 'translations.view' | 'keys.edit' | 'screenshots.upload' | 'screenshots.view' | 'screenshots.delete';
export declare type Mode = 'development' | 'production';
export declare type Unwrapped = {
text: string;
keys: KeyAndParamsTags<any>[];
export declare type UiProps = {
apiUrl: string;
apiKey: string;
highlight: HighlightInterface;
changeTranslation: ChangeTranslationInterface;
};
export interface Formatter {
format: FormatFunction;
export interface UiInterface {
handleElementClick(event: MouseEvent, keysAndDefaults: UiKeyOption[]): Promise<void>;
}
interface FormatterStatic {
type: 'formatter';
new (): Formatter;
}
export declare type TolgeeModule = FormatterStatic;
export declare type FormatFunction = (props: {
translation: string;
params: Record<string, any>;
export declare type UiConstructor = new (props: UiProps) => UiInterface;
export declare type UiLibInterface = {
UI: UiConstructor;
};
export declare type UiType = UiConstructor | UiLibInterface;
export declare type UiKeyOption = {
key: string;
defaultValue?: string;
ns: string[];
translation: string | undefined;
};
export declare type KeyWithDefault = {
key: string;
defaultValue?: string;
ns: FallbackNSTranslation;
};
export declare type TranslationOnClick = (event: MouseEvent, data: {
keysAndDefaults: KeyWithDefault[];
el: Element;
meta: ElementMeta;
}) => void;
export declare type Listener = {
unsubscribe: () => void;
};
export declare type KeyDescriptorInternal = {
key?: string;
ns?: string[] | undefined;
};
export declare type KeyDescriptor = {
key: string;
ns?: string | string[];
};
export declare type ListenerSelective = {
unsubscribe: () => void;
subscribeNs: (ns: FallbackNSTranslation) => ListenerSelective;
unsubscribeNs: (ns: FallbackNSTranslation) => ListenerSelective;
subscribeKey: (descriptor: KeyDescriptor) => ListenerSelective;
unsubscribeKey: (descriptor: KeyDescriptor) => ListenerSelective;
};
export declare type ListenerHandlerEvent<T> = {
value: T;
};
export declare type ListenerHandler<T> = (e: ListenerHandlerEvent<T>) => void;
export declare type TolgeePlugin = (tolgee: TolgeeInstance, tools: PluginServicePublic) => TolgeeInstance;
export declare type CachePublicRecord = {
data: TranslationsFlat;
language: string;
}) => string | any[];
export {};
namespace: string;
};
{
"name": "@tolgee/core",
"version": "4.9.2",
"version": "5.0.0-rc.0b3e627.0",
"description": "Library providing ability to translate messages directly in context of developed application.",
"main": "index.js",
"main": "./dist/tolgee.cjs.js",
"module": "./dist/tolgee.esm.mjs",

@@ -22,2 +22,6 @@ "types": "./lib/index.d.ts",

"declaration": true,
"exports": {
"require": "./dist/tolgee.cjs.js",
"import": "./dist/tolgee.esm.mjs"
},
"directories": {

@@ -28,14 +32,11 @@ "lib": "lib",

"scripts": {
"build": "rollup -c rollup.config.js && tsc --project tsconfig.prod.json",
"clean": "rm -rf build build-e2e dist dist-e2e lib",
"test": "jest --config ./jest.config.js",
"develop": "concurrently \"rollup -c rollup.config.js -w\" \"tsc --watch --preserveWatchOutput --project tsconfig.prod.json\" ",
"schema": "openapi-typescript http://localhost:8080/v3/api-docs/All%20Internal%20-%20for%20Tolgee%20Web%20application --output ./src/types/apiSchema.generated.ts",
"typedoc": "typedoc --entryPointStrategy expand --out docs src/index.ts src/Tolgee.ts src/types.ts src/services/EventEmitter.ts src/services/Subscription.ts",
"tsc": "tsc --noEmit --emitDeclarationOnly false"
"build": "rollup -c rollup.config.js && tsc --declaration --emitDeclarationOnly --project tsconfig.prod.json",
"clean": "rm -rf dist lib",
"test": "jest --collect-coverage",
"develop": "concurrently \"rollup -c rollup.config.js -w\" \"tsc --declaration --emitDeclarationOnly --watch --preserveWatchOutput --project tsconfig.prod.json\" ",
"tsc": "tsc --noEmit"
},
"author": "JanCizmar",
"author": "Tolgee",
"license": "MIT",
"files": [
"index.js",
"lib/**/*",

@@ -47,6 +48,4 @@ "dist/**/*",

"@rollup/plugin-node-resolve": "13.3.0",
"@rollup/plugin-replace": "^4.0.0",
"@rollup/plugin-typescript": "8.3.4",
"@testing-library/dom": "^8.7.1",
"@testing-library/jest-dom": "^5.11.4",
"@testing-library/jest-dom": "^5.16.5",
"@types/jest": "^27.0.2",

@@ -56,23 +55,15 @@ "@types/node": "^17.0.8",

"concurrently": "7.3.0",
"intl-messageformat": "^9.9.1",
"jest": "^27.2.4",
"jest-environment-jsdom": "^27.5.1",
"jest-fetch-mock": "^3.0.3",
"openapi-typescript": "^4.3.0",
"rollup": "^2.78.1",
"rollup": "^2.56.3",
"rollup-plugin-bundle-size": "^1.0.3",
"rollup-plugin-terser": "7.0.2",
"ts-jest": "^27.0.5",
"tslib": "^2.4.0",
"typedoc": "0.22.15",
"typedoc-plugin-markdown": "3.13.2",
"typescript": "4.7.4"
"rollup-plugin-visualizer": "^5.8.0",
"ts-jest": "^27.1.5",
"typescript": "^4.7.4"
},
"exports": {
"require": "./dist/tolgee.cjs.js",
"import": "./dist/tolgee.esm.mjs"
},
"gitHead": "dcbded7f7d158facb5eac126baf2ec1e1dc5699e",
"publishConfig": {
"access": "public"
}
},
"gitHead": "f5584ce9d50b1c54351a66c5b3f03477fadfc09e"
}
export { Tolgee } from './Tolgee';
export { TolgeeConfig } from './TolgeeConfig';
export { ModifierKey } from './Constants/ModifierKey';
export { TOLGEE_WRAPPED_ONLY_DATA_ATTRIBUTE } from './Constants/Global';
export * from './modules';
export * from './types/DTOs';
export {
RESTRICTED_ASCENDANT_ATTRIBUTE,
DEVTOOLS_ID,
TOLGEE_ATTRIBUTE_NAME,
TOLGEE_HIGHLIGHTER_CLASS,
TOLGEE_WRAPPED_ONLY_DATA_ATTRIBUTE,
} from './constants';
export * from './types';
export * from './Constants/Global';
export * from './helpers/NodeHelper';
export * from './helpers/TextHelper';
export { getTranslateParams } from './TranslateParams';
export { getFallback, getFallbackArray } from './Controller/State/helpers';

@@ -1,335 +0,77 @@

import { TolgeeConfig } from './TolgeeConfig';
import {
InstantProps,
InstantPropsTags,
TolgeeModule,
TranslateProps,
TranslatePropsTags,
TranslationTags,
TranslationParams,
TranslationParamsTags,
} from './types';
import { Events } from './Events/Events';
import { Controller } from './Controller/Controller';
import { Options, TolgeeInstance, TolgeePlugin } from './types';
import { EventEmitterImpl } from './services/EventEmitter';
import { DependencyService } from './services/DependencyService';
export const Tolgee = (options?: Partial<Options>): TolgeeInstance => {
const events = Events();
const controller = Controller({
events,
options,
});
export class Tolgee {
private dependencyService: DependencyService;
const pluginTools = Object.freeze({
setFinalFormatter: controller.setFinalFormatter,
addFormatter: controller.addFormatter,
setObserver: controller.setObserver,
getObserver: controller.getObserver,
setUi: controller.setUi,
getUi: controller.getUi,
setDevBackend: controller.setDevBackend,
addBackend: controller.addBackend,
setLanguageDetector: controller.setLanguageDetector,
setLanguageStorage: controller.setLanguageStorage,
});
private constructor() {
this.dependencyService = new DependencyService();
}
const withRestart = (callback: () => void) => {
const wasRunning = controller.isRunning();
wasRunning && controller.stop();
callback();
wasRunning && controller.run();
};
get properties() {
return this.dependencyService.properties;
}
const tolgee: TolgeeInstance = Object.freeze({
// event listeners
on: events.on,
onKeyUpdate: events.onKeyUpdate.listenSome,
public get lang() {
return this.properties.currentLanguage;
}
// state
getLanguage: controller.getLanguage,
getPendingLanguage: controller.getPendingLanguage,
changeLanguage: controller.changeLanguage,
changeTranslation: controller.changeTranslation,
addActiveNs: controller.addActiveNs,
removeActiveNs: controller.removeActiveNs,
loadRecords: controller.loadRecords,
loadRecord: controller.loadRecord,
addStaticData: controller.addStaticData,
getRecord: controller.getRecord,
getAllRecords: controller.getAllRecords,
isLoaded: controller.isLoaded,
isInitialLoading: controller.isInitialLoading,
isLoading: controller.isLoading,
isFetching: controller.isFetching,
isRunning: controller.isRunning,
run: controller.run,
stop: controller.stop,
t: controller.t,
highlight: controller.highlight,
getInitialOptions: controller.getInitialOptions,
isDev: controller.isDev,
wrap: controller.wrap,
unwrap: controller.unwrap,
/**
* This sets a new language.
*
* Using this setter can behave buggy when you change languages
* too fast, since it changes the language property before
* translations are actually loaded.
* @deprecated use asynchronous changeLanguage method.
*/
public set lang(newLanguage) {
this.properties.currentLanguage = newLanguage;
this.dependencyService.translationService
.loadTranslations(newLanguage)
.then(() => {
this.emitLangChangeEvent(newLanguage);
});
}
public get defaultLanguage() {
return this.properties.config.defaultLanguage;
}
public get onLangChange() {
return this.dependencyService.eventService.LANGUAGE_CHANGED;
}
public get onTranslationChange() {
return this.dependencyService.eventService.TRANSLATION_CHANGED;
}
/**
* Is emitted when language is loaded for the first time
*/
public get onLangLoaded() {
return this.dependencyService.eventService.LANGUAGE_LOADED;
}
/**
* True if loading is needed to wait for Tolgee init.
* When translation data are provided statically (using import
* as staticData config property) then there is no need for translation
* fetching so initial loading is not needed at all.
*/
get initialLoading(): boolean {
const currentLang = this.properties.currentLanguage;
const fallbackLang = this.properties.config.fallbackLanguage;
const fallbackPreloading = this.properties.config.preloadFallback;
const isStaticDataProvided = (data?: any) => {
return data !== undefined && typeof data !== 'function';
};
return (
!isStaticDataProvided(this.properties.config.staticData?.[currentLang]) ||
(!!fallbackPreloading &&
!isStaticDataProvided(
this.properties.config.staticData?.[fallbackLang]
))
);
}
private get coreService() {
return this.dependencyService.coreService;
}
static use(module: TolgeeModule) {
return new Tolgee().use(module);
}
static init(config: TolgeeConfig) {
return new Tolgee().init(config);
}
/**
* Sets the new language.
*
* Emits the onLangChange and onLangChangeAndLoad events after
* the translations are loaded.
*
* @return Promise<void> Resolves when translations are loaded
*/
public async changeLanguage(newLanguage: string): Promise<void> {
await this.dependencyService.translationService.loadTranslations(
newLanguage
);
this.properties.currentLanguage = newLanguage;
this.emitLangChangeEvent(newLanguage);
}
use(module: TolgeeModule) {
this.dependencyService.moduleService.addModule(module);
return this;
}
init(config: TolgeeConfig) {
this.dependencyService.init(config);
const { apiKey, apiUrl } = this.dependencyService.properties.config;
this.dependencyService.properties.mode =
apiKey && apiUrl ? 'development' : 'production';
return this;
}
public async run(): Promise<void> {
this.dependencyService.run();
if (this.properties.mode === 'development') {
try {
await this.coreService.loadApiKeyDetails();
} catch (e) {
// eslint-disable-next-line no-console
console.error("Couldn't connect to Tolgee");
// eslint-disable-next-line no-console
console.error(e);
this.properties.mode = 'production';
// plugins
use: (plugin: TolgeePlugin | undefined) => {
if (plugin) {
withRestart(() => plugin(tolgee, pluginTools));
}
}
return tolgee;
},
init: (options: Partial<Options>) => {
withRestart(() => controller.init(options));
return tolgee;
},
});
await this.dependencyService.translationService.loadTranslations();
await this.dependencyService.pluginManager.run();
if (this.properties.config.preloadFallback) {
await this.dependencyService.translationService.loadTranslations(
this.properties.config.fallbackLanguage
);
}
await this.refresh();
if (this.properties.config.watch) {
this.dependencyService.observer.observe();
}
}
public async refresh() {
return this.dependencyService.wrapper.handleSubtree(
this.properties.config.targetElement
);
}
async translate(props: TranslateProps): Promise<string>;
async translate<T>(props: TranslatePropsTags<T>): Promise<TranslationTags<T>>;
async translate(
key: string,
params?: TranslationParams,
noWrap?: boolean,
defaultValue?: string
): Promise<string>;
async translate<T>(
key: string,
params?: TranslationParamsTags<T>,
noWrap?: boolean,
defaultValue?: string
): Promise<TranslationTags<T>>;
async translate(
keyOrProps: string | TranslatePropsTags<any>,
params: TranslationParamsTags<any> = {},
noWrap = false,
defaultValue: string | undefined = undefined
): Promise<TranslationTags<any>> {
const key = typeof keyOrProps === 'string' ? keyOrProps : keyOrProps.key;
let orEmpty = undefined;
if (typeof keyOrProps === 'object') {
const props = keyOrProps as TranslateProps;
// if values are not provided in props object, get them from function
// params defaults
params = props.params !== undefined ? props.params : params;
noWrap = props.noWrap !== undefined ? props.noWrap : noWrap;
defaultValue =
props.defaultValue !== undefined ? props.defaultValue : defaultValue;
orEmpty = props.orEmpty;
}
const translation = await this.dependencyService.textService.translate(
key,
params,
undefined,
orEmpty,
defaultValue
);
if (this.properties.mode === 'development' && !noWrap) {
await this.coreService.loadApiKeyDetails();
return this.dependencyService.wrapper.wrap(
key,
params,
defaultValue,
translation
);
}
return translation;
}
wrap(
key: string,
params?: TranslationParams,
defaultValue?: string | undefined,
translation?: string
): string;
wrap<T>(
key: string,
params?: TranslationTags<T>,
defaultValue?: string | undefined,
translation?: TranslationTags<T>
): TranslationTags<T>;
wrap(
key: string,
params?: any,
defaultValue?: string | undefined,
translation?: TranslationTags<any>
): TranslationTags<any> {
if (this.properties.mode === 'development') {
return this.dependencyService.wrapper.wrap(
key,
params,
defaultValue,
translation
);
} else {
return translation || defaultValue;
}
}
instant(
key: string,
params?: TranslationParams,
noWrap?: boolean,
orEmpty?: boolean,
defaultValue?: string
): string;
instant<T>(
key: string,
params?: TranslationParamsTags<T>,
noWrap?: boolean,
orEmpty?: boolean,
defaultValue?: string
): TranslationTags<T>;
instant(props: InstantProps): string;
instant<T>(props: InstantPropsTags<T>): TranslationTags<T>;
instant(
keyOrProps: string | InstantPropsTags<any>,
params: TranslationParams = {},
noWrap = false,
orEmpty?: boolean,
defaultValue?: string
) {
const key = typeof keyOrProps === 'string' ? keyOrProps : keyOrProps.key;
if (typeof keyOrProps === 'object') {
const props = keyOrProps as InstantProps;
// if values are not provided in props object, get them from function
// params defaults
params = props.params !== undefined ? props.params : params;
noWrap = props.noWrap !== undefined ? props.noWrap : noWrap;
defaultValue =
props.defaultValue !== undefined ? props.defaultValue : defaultValue;
orEmpty = props.orEmpty !== undefined ? props.orEmpty : orEmpty;
}
const translation = this.dependencyService.textService.instant(
key,
params,
undefined,
orEmpty,
defaultValue
);
if (this.properties.mode === 'development' && !noWrap) {
return this.dependencyService.wrapper.wrap(
key,
params,
defaultValue,
translation
);
}
return translation;
}
/**
* Get currently cached translations for all languages
*/
public getCachedTranslations() {
return this.dependencyService.translationService.getCachedTranslations();
}
/**
* Loads translations for given language or returns them from cache
* @returns Loaded translations
*/
public loadTranslations(lang: string) {
return this.dependencyService.translationService.loadTranslations(lang);
}
public stop = () => {
this.dependencyService.stop();
};
private emitLangChangeEvent(value: string) {
const langChangedEmitter = this.onLangChange as EventEmitterImpl<any>;
langChangedEmitter.emit(value);
}
}
return tolgee;
};

@@ -1,94 +0,279 @@

export interface TextInputElementData {
oldValue: string;
valueInputs: string[];
touched: boolean;
oldPlaceholder: string;
placeholderInputs: string[];
}
import type { Options } from './Controller/State/initState';
export type TreeTranslationsData = {
[key: string]: string | TreeTranslationsData;
};
export type { State, Options } from './Controller/State/initState';
export type { EventEmitterType } from './Events/EventEmitter';
export type { EventEmitterSelectiveType } from './Events/EventEmitterSelective';
export type Translations = Record<string, string>;
export type TranslationParams = {
[key: string]: string | number | bigint;
};
export type TranslationParamsTags<T> = {
[key: string]: string | number | bigint | ((value: T | T[]) => T);
};
export type FallbackGeneral = undefined | false | string | string[];
export type TranslateProps = {
key: string;
defaultValue?: string;
params?: TranslationParams;
export type FallbackNS = FallbackGeneral;
export type NsType = string;
export type KeyType = string;
export type FallbackNSTranslation = undefined | NsType | NsType[];
export type FallbackLanguage = FallbackGeneral;
export type FallbackLanguageObject = Record<string, FallbackLanguage>;
export type FallbackLanguageOption = FallbackLanguage | FallbackLanguageObject;
export type TranslateOptions<T> = {
ns?: FallbackNSTranslation;
noWrap?: boolean;
orEmpty?: boolean;
params?: TranslateParams<T>;
};
export type TranslatePropsTags<T> = {
key: string;
export type TranslateProps<T = DefaultParamType> = {
key: KeyType;
defaultValue?: string;
params?: TranslationParamsTags<T>;
noWrap?: boolean;
orEmpty?: boolean;
} & TranslateOptions<T>;
export type TranslatePropsInternal = TranslateProps & {
translation?: string;
};
export type InstantProps = {
key: string;
defaultValue?: string;
params?: TranslationParams;
noWrap?: boolean;
orEmpty?: boolean;
export type TranslationValue = string | undefined | null;
export type TranslationsFlat = Map<string, TranslationValue>;
export type TreeTranslationsData = {
[key: string]: TranslationValue | TreeTranslationsData;
};
export type InstantPropsTags<T> = {
key: string;
defaultValue?: string;
params?: TranslationParamsTags<T>;
noWrap?: boolean;
orEmpty?: boolean;
export type CacheAsyncRequests = Map<
string,
Promise<TreeTranslationsData | undefined> | undefined
>;
export type CacheDescriptor = {
language: string;
namespace?: string;
};
export type CacheDescriptorInternal = {
language: string;
namespace: string;
};
export type CacheDescriptorWithKey = CacheDescriptorInternal & {
key?: string;
};
export type KeyAndParams = {
key: string;
params: TranslationParams;
params?: TranslateParams;
defaultValue?: string;
ns?: FallbackNSTranslation;
};
export type KeyAndParamsTags<T> = {
key: string;
params: TranslationParamsTags<T>;
defaultValue?: string;
export type Unwrapped = { text: string; keys: KeyAndParams[] };
type PropType<TObj> = TObj[keyof TObj];
export type DefaultParamType = string | number | bigint;
export type TranslateParams<T = DefaultParamType> = {
[key: string]: T;
};
export type TranslatedWithMetadata = {
translated: string;
key: string;
params: TranslationParams;
defaultValue: string | undefined;
export type CombinedOptions<T> = TranslateOptions<T> & {
[key: string]: T | PropType<TranslateOptions<T>>;
};
export type TranslatedWithMetadataTags<T> = {
translated: TranslationTags<T>;
key: string;
params: TranslationParamsTags<T>;
defaultValue: string | undefined;
export type TFnType<T = DefaultParamType, R = string> = {
(key: string, defaultValue?: string, options?: CombinedOptions<T>): R;
(key: string, options?: CombinedOptions<T>): R;
(props: TranslateProps<T>): R;
};
export type TranslationTags<T> = string | T[];
export type WrapperWrapProps = Pick<
TranslatePropsInternal,
'key' | 'params' | 'defaultValue' | 'ns' | 'translation'
>;
export type WrapperWrapFunction = (props: WrapperWrapProps) => string;
export type WrapperUnwrapFunction = (text: string) => Unwrapped;
export type NodeWithMeta = Node & {
_tolgee: NodeMeta;
export type WrapperAttributeXPathGetter = (props: {
tag: string;
attribute: string;
}) => string;
export type WrapperInterface = {
unwrap: WrapperUnwrapFunction;
wrap: WrapperWrapFunction;
getTextXPath: () => string;
getAttributeXPath: WrapperAttributeXPathGetter;
};
export type NodeWithLock = Node & {
_tolgee: NodeLock;
export type FormatterInterfaceFormatParams = {
translation: string;
language: string;
params: Record<string, any> | undefined;
};
export type ElementWithMeta = Element &
ElementCSSInlineStyle & {
_tolgee: ElementMeta;
};
export type FormatterInterface = {
format: (props: FormatterInterfaceFormatParams) => string;
};
export type FinalFormatterInterface = {
format: (props: FormatterInterfaceFormatParams) => any;
};
export type ObserverProps = {
translate: (params: TranslatePropsInternal) => string;
onClick: TranslationOnClick;
};
export type HighlightInterface = (
key?: string,
ns?: FallbackNSTranslation
) => {
unhighlight(): void;
};
export type ObserverRunProps = {
mouseHighlight: boolean;
};
export type ObserverInterface = (props: ObserverProps) => {
unwrap: (text: string) => Unwrapped;
wrap: WrapperWrapFunction;
retranslate: () => void;
stop: () => void;
run: (props: ObserverRunProps) => void;
highlight: HighlightInterface;
outputNotFormattable: boolean;
};
export type LanguageDetectorProps = {
availableLanguages: string[];
};
export type LanguageDetectorInterface = {
getLanguage: (
props: LanguageDetectorProps
) => string | undefined | Promise<string | undefined>;
};
export type LanguageStorageInterface = {
getLanguage: () => string | undefined | Promise<string | undefined>;
setLanguage: (language: string) => void | Promise<void>;
};
export type BackendDevProps = {
apiUrl?: string;
apiKey?: string;
projectId?: number;
};
export type BackendGetRecordProps = {
language: string;
namespace?: string;
};
export type BackendGetRecord = (
data: BackendGetRecordProps
) => Promise<TreeTranslationsData | undefined> | undefined;
export interface BackendInterface {
getRecord: BackendGetRecord;
}
export type BackendGetDevRecord = (
data: BackendGetRecordProps & BackendDevProps
) => Promise<TreeTranslationsData | undefined> | undefined;
export type BackendDevInterface = {
getRecord: BackendGetDevRecord;
};
export type TolgeeEvent =
| 'pendingLanguage'
| 'language'
| 'key'
| 'loading'
| 'fetching'
| 'initialLoad'
| 'running'
| 'cache'
| 'keyUpdate';
export type TolgeeOn = {
(event: 'pendingLanguage', handler: ListenerHandler<string>): Listener;
(event: 'language', handler: ListenerHandler<string>): Listener;
(event: 'key', handler: ListenerHandler<string>): Listener;
(event: 'loading', handler: ListenerHandler<boolean>): Listener;
(event: 'fetching', handler: ListenerHandler<boolean>): Listener;
(event: 'initialLoad', handler: ListenerHandler<void>): Listener;
(event: 'running', handler: ListenerHandler<boolean>): Listener;
(event: 'keyUpdate', handler: ListenerHandler<void>): Listener;
(event: TolgeeEvent, handler: ListenerHandler<any>): Listener;
};
export type TolgeeInstance = Readonly<{
on: TolgeeOn;
onKeyUpdate: (handler: ListenerHandler<void>) => ListenerSelective;
use: (plugin: TolgeePlugin | undefined) => TolgeeInstance;
getLanguage: () => string | undefined;
getPendingLanguage: () => string | undefined;
changeLanguage: (language: string) => Promise<void>;
changeTranslation: ChangeTranslationInterface;
addActiveNs: (ns: FallbackNSTranslation, forget?: boolean) => Promise<void>;
removeActiveNs: (ns: FallbackNSTranslation) => void;
loadRecords: (descriptors: CacheDescriptor[]) => Promise<TranslationsFlat[]>;
loadRecord: (descriptors: CacheDescriptor) => Promise<TranslationsFlat>;
addStaticData: (data: Options['staticData']) => void;
getRecord: (
descriptor: CacheDescriptorInternal
) => TranslationsFlat | undefined;
getAllRecords: () => CachePublicRecord[];
isInitialLoading: () => boolean;
isLoading: (ns?: FallbackNSTranslation) => boolean;
isLoaded: (ns?: FallbackNSTranslation) => boolean;
isFetching: (ns?: FallbackNSTranslation) => boolean;
isRunning: () => boolean;
highlight: HighlightInterface;
getInitialOptions: () => Options;
isDev: () => boolean;
init: (options: Partial<Options>) => TolgeeInstance;
run: () => Promise<void>;
stop: () => void;
t: (props: TranslatePropsInternal) => string;
wrap: (params: TranslatePropsInternal) => string | undefined;
unwrap: (text: string) => Unwrapped;
}>;
export type PluginServicePublic = Readonly<{
setFinalFormatter: (formatter: FinalFormatterInterface | undefined) => void;
addFormatter: (formatter: FormatterInterface | undefined) => void;
setObserver: (observer: ObserverInterface | undefined) => void;
getObserver: () => ReturnType<ObserverInterface> | undefined;
setUi: (ui: UiLibInterface | undefined) => void;
getUi: () => UiConstructor | undefined;
addBackend: (backend: BackendInterface | undefined) => void;
setDevBackend: (backend: BackendInterface | undefined) => void;
setLanguageDetector: (
languageDetector: LanguageDetectorInterface | undefined
) => void;
setLanguageStorage: (
languageStorage: LanguageStorageInterface | undefined
) => void;
}>;
export type NodeMeta = {
oldTextContent: string;
keys: KeyAndParams[];
keyAttributeOnly?: boolean;
};
export type ElementMeta = {
wrappedWithElementOnlyKey?: string;
wrappedWithElementOnlyDefaultHtml?: string;
nodes: Set<NodeWithMeta>;
nodes: Map<Node, NodeMeta>;
highlightEl?: HTMLDivElement;

@@ -107,41 +292,90 @@ highlight?: () => void;

*/
preventClean?: boolean;
};
export type NodeMeta = {
oldTextContent: string;
keys: KeyAndParamsTags<any>[];
} & NodeLock;
export type ChangeTranslationInterface = (
descriptor: CacheDescriptor,
key: string,
value: string
) => { revert: () => void };
export type NodeLock = {
locked?: boolean;
export type UiProps = {
apiUrl: string;
apiKey: string;
highlight: HighlightInterface;
changeTranslation: ChangeTranslationInterface;
};
export type Scope =
| 'translations.edit'
| 'translations.view'
| 'keys.edit'
| 'screenshots.upload'
| 'screenshots.view'
| 'screenshots.delete';
export interface UiInterface {
handleElementClick(
event: MouseEvent,
keysAndDefaults: UiKeyOption[]
): Promise<void>;
}
export type Mode = 'development' | 'production';
export type UiConstructor = new (props: UiProps) => UiInterface;
export type Unwrapped = { text: string; keys: KeyAndParamsTags<any>[] };
export type UiLibInterface = {
UI: UiConstructor;
};
export interface Formatter {
format: FormatFunction;
}
export type UiType = UiConstructor | UiLibInterface;
interface FormatterStatic {
type: 'formatter';
new (): Formatter;
}
export type UiKeyOption = {
key: string;
defaultValue?: string;
ns: string[];
translation: string | undefined;
};
export type TolgeeModule = FormatterStatic;
export type KeyWithDefault = {
key: string;
defaultValue?: string;
ns: FallbackNSTranslation;
};
export type FormatFunction = (props: {
translation: string;
params: Record<string, any>;
export type TranslationOnClick = (
event: MouseEvent,
data: {
keysAndDefaults: KeyWithDefault[];
el: Element;
meta: ElementMeta;
}
) => void;
export type Listener = {
unsubscribe: () => void;
};
export type KeyDescriptorInternal = {
key?: string;
ns?: string[] | undefined;
};
export type KeyDescriptor = {
key: string;
ns?: string | string[];
};
export type ListenerSelective = {
unsubscribe: () => void;
subscribeNs: (ns: FallbackNSTranslation) => ListenerSelective;
unsubscribeNs: (ns: FallbackNSTranslation) => ListenerSelective;
subscribeKey: (descriptor: KeyDescriptor) => ListenerSelective;
unsubscribeKey: (descriptor: KeyDescriptor) => ListenerSelective;
};
export type ListenerHandlerEvent<T> = { value: T };
export type ListenerHandler<T> = (e: ListenerHandlerEvent<T>) => void;
export type TolgeePlugin = (
tolgee: TolgeeInstance,
tools: PluginServicePublic
) => TolgeeInstance;
export type CachePublicRecord = {
data: TranslationsFlat;
language: string;
}) => string | any[];
namespace: string;
};

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc