@smartcorehub/localization-sdk 1.0.3474
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +83 -0
- package/README.md +202 -0
- package/dist/index.d.mts +150 -0
- package/dist/index.d.ts +150 -0
- package/dist/index.js +1 -0
- package/dist/index.mjs +1 -0
- package/package.json +60 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
SMARTCOREHUB SOFTWARE LICENSE / LICENCA DE SOFTWARE SMARTCOREHUB
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 SmartCoreHub. All rights reserved.
|
|
4
|
+
Copyright (c) 2026 SmartCoreHub. Todos os direitos reservados.
|
|
5
|
+
|
|
6
|
+
================================================================
|
|
7
|
+
PORTUGUES (PT-BR)
|
|
8
|
+
================================================================
|
|
9
|
+
|
|
10
|
+
1. CONCESSAO PARA USO NAO COMERCIAL
|
|
11
|
+
Fica autorizado, gratuitamente, o uso nao comercial deste software, incluindo
|
|
12
|
+
estudo, avaliacao, testes, desenvolvimento interno e projetos pessoais, desde
|
|
13
|
+
que seja mantido este aviso de direitos autorais e esta licenca.
|
|
14
|
+
|
|
15
|
+
2. USO COMERCIAL
|
|
16
|
+
Qualquer uso comercial deste software exige autorizacao previa e expressa da
|
|
17
|
+
SmartCoreHub, mediante:
|
|
18
|
+
- aquisicao de licenca comercial valida; ou
|
|
19
|
+
- contratacao de servicos oficiais da SmartCoreHub que incluam o direito de uso.
|
|
20
|
+
|
|
21
|
+
Sem uma das autorizacoes acima, e proibido usar, distribuir, sublicenciar,
|
|
22
|
+
incorporar, revender, oferecer como servico, ou explorar economicamente este
|
|
23
|
+
software, no todo ou em parte.
|
|
24
|
+
|
|
25
|
+
3. DEFINICAO DE USO COMERCIAL
|
|
26
|
+
Para esta licenca, considera-se uso comercial qualquer uso direto ou indireto
|
|
27
|
+
com finalidade de lucro, vantagem economica, atividade empresarial, prestacao
|
|
28
|
+
de servicos a terceiros, ou uso em ambiente corporativo para atividade-fim.
|
|
29
|
+
|
|
30
|
+
4. RESTRICOES GERAIS
|
|
31
|
+
Nao e permitido remover avisos de autoria, copyright, marca ou licenca.
|
|
32
|
+
Qualquer violacao destes termos encerra automaticamente a permissao de uso.
|
|
33
|
+
|
|
34
|
+
5. ISENCA DE GARANTIAS E RESPONSABILIDADE
|
|
35
|
+
O software e fornecido "no estado em que se encontra", sem garantias de qualquer
|
|
36
|
+
natureza, expressas ou implicitas. Em nenhuma hipotese a SmartCoreHub sera
|
|
37
|
+
responsavel por danos diretos, indiretos, incidentais, especiais, exemplares
|
|
38
|
+
ou consequenciais, decorrentes do uso ou da impossibilidade de uso do software.
|
|
39
|
+
|
|
40
|
+
6. CONTATO PARA LICENCA COMERCIAL
|
|
41
|
+
Para aquisicao de licenca comercial ou contratacao de servicos, entre em contato
|
|
42
|
+
com a SmartCoreHub pelos canais oficiais.
|
|
43
|
+
|
|
44
|
+
================================================================
|
|
45
|
+
ENGLISH
|
|
46
|
+
================================================================
|
|
47
|
+
|
|
48
|
+
1. NON-COMMERCIAL USE GRANT
|
|
49
|
+
You are granted permission, free of charge, to use this software for
|
|
50
|
+
non-commercial purposes, including study, evaluation, testing, internal
|
|
51
|
+
development, and personal projects, provided that this copyright notice
|
|
52
|
+
and this license are preserved.
|
|
53
|
+
|
|
54
|
+
2. COMMERCIAL USE
|
|
55
|
+
Any commercial use of this software requires prior written authorization
|
|
56
|
+
from SmartCoreHub through:
|
|
57
|
+
- purchase of a valid commercial license; or
|
|
58
|
+
- subscription to official SmartCoreHub services that include usage rights.
|
|
59
|
+
|
|
60
|
+
Without one of the authorizations above, it is prohibited to use,
|
|
61
|
+
distribute, sublicense, embed, resell, offer as a service, or otherwise
|
|
62
|
+
commercially exploit this software, in whole or in part.
|
|
63
|
+
|
|
64
|
+
3. DEFINITION OF COMMERCIAL USE
|
|
65
|
+
For the purposes of this license, commercial use means any direct or
|
|
66
|
+
indirect use for profit, economic advantage, business activity, service
|
|
67
|
+
delivery to third parties, or use in a corporate environment for core
|
|
68
|
+
business operations.
|
|
69
|
+
|
|
70
|
+
4. GENERAL RESTRICTIONS
|
|
71
|
+
You may not remove authorship, copyright, trademark, or license notices.
|
|
72
|
+
Any breach of these terms automatically terminates your right to use this
|
|
73
|
+
software.
|
|
74
|
+
|
|
75
|
+
5. DISCLAIMER OF WARRANTIES AND LIABILITY
|
|
76
|
+
THIS SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
|
|
77
|
+
OR IMPLIED. IN NO EVENT SHALL SMARTCOREHUB BE LIABLE FOR ANY DIRECT,
|
|
78
|
+
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES ARISING
|
|
79
|
+
OUT OF OR IN CONNECTION WITH THE USE OF OR INABILITY TO USE THE SOFTWARE.
|
|
80
|
+
|
|
81
|
+
6. CONTACT FOR COMMERCIAL LICENSE
|
|
82
|
+
To purchase a commercial license or contract official services, contact
|
|
83
|
+
SmartCoreHub through its official channels.
|
package/README.md
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
# @smartcorehub/localization-sdk
|
|
2
|
+
|
|
3
|
+
SDK TypeScript para consumir a API de localizacao da SmartCoreHub em projetos Angular, React, Next.js, Node.js e TypeScript puro.
|
|
4
|
+
|
|
5
|
+
## O que este pacote entrega
|
|
6
|
+
|
|
7
|
+
- Cliente tipado para localizacao
|
|
8
|
+
- Autenticacao por header X-Auth-Token
|
|
9
|
+
- Tratamento de erros padronizado
|
|
10
|
+
- Cache configuravel para listagem
|
|
11
|
+
- Integracao Angular via provider e service
|
|
12
|
+
|
|
13
|
+
## Requisitos
|
|
14
|
+
|
|
15
|
+
- Node.js 18+
|
|
16
|
+
- npm 9+
|
|
17
|
+
|
|
18
|
+
## Como instalar o pacote no projeto consumidor
|
|
19
|
+
|
|
20
|
+
Quando o pacote estiver publicado no npm:
|
|
21
|
+
|
|
22
|
+
~~~bash
|
|
23
|
+
npm install @smartcorehub/localization-sdk
|
|
24
|
+
~~~
|
|
25
|
+
|
|
26
|
+
## Primeiro uso rapido (TypeScript, React, Next.js, Node)
|
|
27
|
+
|
|
28
|
+
~~~ts
|
|
29
|
+
import { createLocalizationClient } from '@smartcorehub/localization-sdk';
|
|
30
|
+
|
|
31
|
+
const localizationClient = createLocalizationClient({
|
|
32
|
+
baseUrl: 'https://api.smartcorehub.io/',
|
|
33
|
+
token: 'SEU_TOKEN',
|
|
34
|
+
timeoutMs: 10000,
|
|
35
|
+
cache: {
|
|
36
|
+
enabled: true,
|
|
37
|
+
ttlMs: 60000
|
|
38
|
+
}
|
|
39
|
+
});
|
|
40
|
+
|
|
41
|
+
const current = await localizationClient.getCurrentLanguage('home.title');
|
|
42
|
+
const byLanguage = await localizationClient.getByLanguage('home.title', 'pt-BR');
|
|
43
|
+
const list = await localizationClient.listResources();
|
|
44
|
+
~~~
|
|
45
|
+
|
|
46
|
+
## Integracao com Angular
|
|
47
|
+
|
|
48
|
+
Use o provider para registrar o SDK na injecao de dependencia.
|
|
49
|
+
|
|
50
|
+
~~~ts
|
|
51
|
+
import { ApplicationConfig } from '@angular/core';
|
|
52
|
+
import { provideLocalization } from '@smartcorehub/localization-sdk';
|
|
53
|
+
|
|
54
|
+
export const appConfig: ApplicationConfig = {
|
|
55
|
+
providers: [
|
|
56
|
+
provideLocalization({
|
|
57
|
+
baseUrl: 'https://api.smartcorehub.io/',
|
|
58
|
+
token: 'SEU_TOKEN',
|
|
59
|
+
cache: { enabled: true, ttlMs: 60000 }
|
|
60
|
+
})
|
|
61
|
+
]
|
|
62
|
+
};
|
|
63
|
+
~~~
|
|
64
|
+
|
|
65
|
+
Consumindo no service/componente Angular:
|
|
66
|
+
|
|
67
|
+
~~~ts
|
|
68
|
+
import { Component, inject } from '@angular/core';
|
|
69
|
+
import { LocalizationService } from '@smartcorehub/localization-sdk';
|
|
70
|
+
|
|
71
|
+
@Component({
|
|
72
|
+
selector: 'app-home-title',
|
|
73
|
+
template: '{{ title }}'
|
|
74
|
+
})
|
|
75
|
+
export class HomeTitleComponent {
|
|
76
|
+
private readonly localizationService = inject(LocalizationService);
|
|
77
|
+
title = '';
|
|
78
|
+
|
|
79
|
+
ngOnInit(): void {
|
|
80
|
+
this.localizationService.getCurrentLanguage('home.title').subscribe((result) => {
|
|
81
|
+
this.title = result.value;
|
|
82
|
+
});
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
~~~
|
|
86
|
+
|
|
87
|
+
## Integracao com React
|
|
88
|
+
|
|
89
|
+
~~~tsx
|
|
90
|
+
import { useEffect, useState } from 'react';
|
|
91
|
+
import { createLocalizationClient } from '@smartcorehub/localization-sdk';
|
|
92
|
+
|
|
93
|
+
const client = createLocalizationClient({
|
|
94
|
+
baseUrl: 'https://api.smartcorehub.io/',
|
|
95
|
+
token: 'SEU_TOKEN'
|
|
96
|
+
});
|
|
97
|
+
|
|
98
|
+
export function HomeTitle() {
|
|
99
|
+
const [title, setTitle] = useState('');
|
|
100
|
+
|
|
101
|
+
useEffect(() => {
|
|
102
|
+
client.getCurrentLanguage('home.title').then((response) => {
|
|
103
|
+
setTitle(response.value);
|
|
104
|
+
});
|
|
105
|
+
}, []);
|
|
106
|
+
|
|
107
|
+
return <h1>{title}</h1>;
|
|
108
|
+
}
|
|
109
|
+
~~~
|
|
110
|
+
|
|
111
|
+
## Integracao com Next.js
|
|
112
|
+
|
|
113
|
+
Uso recomendado em Server Components, Route Handlers ou Server Actions.
|
|
114
|
+
|
|
115
|
+
~~~ts
|
|
116
|
+
import { createLocalizationClient } from '@smartcorehub/localization-sdk';
|
|
117
|
+
|
|
118
|
+
export async function getHomeTitle() {
|
|
119
|
+
const client = createLocalizationClient({
|
|
120
|
+
baseUrl: process.env.LOCALIZATION_API_URL ?? '',
|
|
121
|
+
token: process.env.LOCALIZATION_API_TOKEN ?? ''
|
|
122
|
+
});
|
|
123
|
+
|
|
124
|
+
return client.getCurrentLanguage('home.title');
|
|
125
|
+
}
|
|
126
|
+
~~~
|
|
127
|
+
|
|
128
|
+
## Tratamento de erros
|
|
129
|
+
|
|
130
|
+
O SDK mapeia erros HTTP para classes especificas:
|
|
131
|
+
|
|
132
|
+
- LocalizationAuthError para 401 e 403
|
|
133
|
+
- ResourceNotFoundError para 404
|
|
134
|
+
- LocalizationServerError para 5xx
|
|
135
|
+
- LocalizationTimeoutError para timeout
|
|
136
|
+
- LocalizationNetworkError para erros de rede
|
|
137
|
+
|
|
138
|
+
~~~ts
|
|
139
|
+
import {
|
|
140
|
+
LocalizationAuthError,
|
|
141
|
+
ResourceNotFoundError
|
|
142
|
+
} from '@smartcorehub/localization-sdk';
|
|
143
|
+
|
|
144
|
+
try {
|
|
145
|
+
await localizationClient.getCurrentLanguage('home.title');
|
|
146
|
+
} catch (error) {
|
|
147
|
+
if (error instanceof LocalizationAuthError) {
|
|
148
|
+
console.error('Token invalido ou sem permissao');
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
if (error instanceof ResourceNotFoundError) {
|
|
152
|
+
console.error('Recurso nao encontrado');
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
~~~
|
|
156
|
+
|
|
157
|
+
## Cache configuravel
|
|
158
|
+
|
|
159
|
+
Por padrao, voce pode usar o MemoryCacheProvider.
|
|
160
|
+
|
|
161
|
+
~~~ts
|
|
162
|
+
import { createLocalizationClient, MemoryCacheProvider } from '@smartcorehub/localization-sdk';
|
|
163
|
+
|
|
164
|
+
const client = createLocalizationClient({
|
|
165
|
+
baseUrl: 'https://api.smartcorehub.io/',
|
|
166
|
+
token: 'SEU_TOKEN',
|
|
167
|
+
cache: {
|
|
168
|
+
enabled: true,
|
|
169
|
+
provider: new MemoryCacheProvider(),
|
|
170
|
+
ttlMs: 120000
|
|
171
|
+
}
|
|
172
|
+
});
|
|
173
|
+
~~~
|
|
174
|
+
|
|
175
|
+
## Comandos para desenvolvimento do pacote
|
|
176
|
+
|
|
177
|
+
No diretorio do pacote:
|
|
178
|
+
|
|
179
|
+
~~~bash
|
|
180
|
+
npm install
|
|
181
|
+
npm run build
|
|
182
|
+
npm test
|
|
183
|
+
~~~
|
|
184
|
+
|
|
185
|
+
Para detalhes de publicacao em pipeline classico, consulte NPM-PUBLISH-GUIDE.md.
|
|
186
|
+
|
|
187
|
+
Para automacao completa de CI/CD da publicacao, consulte NPM-AUTOMATION-GUIDE.md.
|
|
188
|
+
|
|
189
|
+
Para fluxo interno de contribuicao e troubleshooting de desenvolvimento, consulte o arquivo DEVELOPMENT-GUIDE.md.
|
|
190
|
+
|
|
191
|
+
## Licensing / Licenciamento
|
|
192
|
+
|
|
193
|
+
### English
|
|
194
|
+
This project is provided for non-commercial use.
|
|
195
|
+
Commercial use requires prior authorization from SmartCoreHub through a valid commercial license purchase or an active service contract.
|
|
196
|
+
See the LICENSE file in this project for full terms.
|
|
197
|
+
|
|
198
|
+
### Portugues (PT-BR)
|
|
199
|
+
Este projeto e fornecido para uso nao comercial.
|
|
200
|
+
O uso comercial exige autorizacao previa da SmartCoreHub, por meio de aquisicao de licenca comercial valida ou contrato de servico ativo.
|
|
201
|
+
Consulte o arquivo LICENSE deste projeto para os termos completos.
|
|
202
|
+
|
package/dist/index.d.mts
ADDED
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
import { EnvironmentProviders, InjectionToken } from '@angular/core';
|
|
2
|
+
import { Observable } from 'rxjs';
|
|
3
|
+
|
|
4
|
+
interface AuthProvider {
|
|
5
|
+
getToken(): Promise<string | null>;
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
interface CacheProvider {
|
|
9
|
+
get<T>(key: string): Promise<T | null>;
|
|
10
|
+
set<T>(key: string, value: T, ttlMs?: number): Promise<void>;
|
|
11
|
+
delete(key: string): Promise<void>;
|
|
12
|
+
clear(): Promise<void>;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
type HttpMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
|
|
16
|
+
interface HttpRequest {
|
|
17
|
+
readonly method: HttpMethod;
|
|
18
|
+
readonly path: string;
|
|
19
|
+
readonly query?: Readonly<Record<string, string | number | boolean | undefined>>;
|
|
20
|
+
readonly headers?: Readonly<Record<string, string>>;
|
|
21
|
+
readonly body?: unknown;
|
|
22
|
+
readonly timeoutMs?: number;
|
|
23
|
+
}
|
|
24
|
+
interface HttpResponse<T> {
|
|
25
|
+
readonly status: number;
|
|
26
|
+
readonly headers: Headers;
|
|
27
|
+
readonly data: T;
|
|
28
|
+
}
|
|
29
|
+
interface SDKMiddleware {
|
|
30
|
+
onRequest?(request: Request): Promise<Request>;
|
|
31
|
+
onResponse?(response: Response): Promise<Response>;
|
|
32
|
+
onError?(error: Error): Promise<void>;
|
|
33
|
+
}
|
|
34
|
+
interface HttpTransport {
|
|
35
|
+
request<T>(request: HttpRequest): Promise<HttpResponse<T>>;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
interface SDKLogger {
|
|
39
|
+
debug(message: string): void;
|
|
40
|
+
info(message: string): void;
|
|
41
|
+
warn(message: string): void;
|
|
42
|
+
error(message: string): void;
|
|
43
|
+
}
|
|
44
|
+
interface LocalizationClientOptions {
|
|
45
|
+
readonly baseUrl: string;
|
|
46
|
+
readonly token?: string;
|
|
47
|
+
readonly authProvider?: AuthProvider;
|
|
48
|
+
readonly timeoutMs?: number;
|
|
49
|
+
readonly headers?: Readonly<Record<string, string>>;
|
|
50
|
+
readonly middleware?: readonly SDKMiddleware[];
|
|
51
|
+
readonly fetchFn?: typeof fetch;
|
|
52
|
+
readonly cache?: {
|
|
53
|
+
readonly enabled?: boolean;
|
|
54
|
+
readonly provider?: CacheProvider;
|
|
55
|
+
readonly ttlMs?: number;
|
|
56
|
+
};
|
|
57
|
+
readonly logger?: SDKLogger;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
interface ResourceResponse {
|
|
61
|
+
readonly key: string;
|
|
62
|
+
readonly value: string;
|
|
63
|
+
readonly language: string;
|
|
64
|
+
readonly lastUpdated?: string;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
interface LocalizationClient {
|
|
68
|
+
getCurrentLanguage(resourceKey: string): Promise<ResourceResponse>;
|
|
69
|
+
getByLanguage(resourceKey: string, languageKey: string): Promise<ResourceResponse>;
|
|
70
|
+
listResources(): Promise<readonly ResourceResponse[]>;
|
|
71
|
+
invalidateCache(key?: string): Promise<void>;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
declare function createLocalizationClient(options: LocalizationClientOptions): LocalizationClient;
|
|
75
|
+
|
|
76
|
+
declare class XAuthTokenProvider implements AuthProvider {
|
|
77
|
+
private readonly token;
|
|
78
|
+
constructor(token: string);
|
|
79
|
+
getToken(): Promise<string | null>;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
declare class MemoryCacheProvider implements CacheProvider {
|
|
83
|
+
private readonly store;
|
|
84
|
+
get<T>(key: string): Promise<T | null>;
|
|
85
|
+
set<T>(key: string, value: T, ttlMs?: number): Promise<void>;
|
|
86
|
+
delete(key: string): Promise<void>;
|
|
87
|
+
clear(): Promise<void>;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
interface FetchHttpTransportOptions {
|
|
91
|
+
readonly baseUrl: string;
|
|
92
|
+
readonly fetchFn?: typeof fetch;
|
|
93
|
+
readonly defaultHeaders?: Readonly<Record<string, string>>;
|
|
94
|
+
readonly middleware?: readonly SDKMiddleware[];
|
|
95
|
+
readonly timeoutMs: number;
|
|
96
|
+
}
|
|
97
|
+
declare class FetchHttpTransport implements HttpTransport {
|
|
98
|
+
private readonly options;
|
|
99
|
+
private readonly fetchFn;
|
|
100
|
+
constructor(options: FetchHttpTransportOptions);
|
|
101
|
+
request<T>(request: HttpRequest): Promise<HttpResponse<T>>;
|
|
102
|
+
private resolveUrl;
|
|
103
|
+
private runRequestMiddleware;
|
|
104
|
+
private runResponseMiddleware;
|
|
105
|
+
private runErrorMiddleware;
|
|
106
|
+
private parseResponse;
|
|
107
|
+
private toError;
|
|
108
|
+
private isAbortError;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
interface SDKErrorMetadata {
|
|
112
|
+
readonly requestId?: string;
|
|
113
|
+
readonly statusCode?: number;
|
|
114
|
+
readonly traceId?: string;
|
|
115
|
+
readonly timestamp?: string;
|
|
116
|
+
}
|
|
117
|
+
declare class LocalizationError extends Error {
|
|
118
|
+
readonly metadata?: SDKErrorMetadata | undefined;
|
|
119
|
+
constructor(message: string, metadata?: SDKErrorMetadata | undefined);
|
|
120
|
+
}
|
|
121
|
+
declare class LocalizationAuthError extends LocalizationError {
|
|
122
|
+
constructor(message?: string, metadata?: SDKErrorMetadata);
|
|
123
|
+
}
|
|
124
|
+
declare class ResourceNotFoundError extends LocalizationError {
|
|
125
|
+
constructor(message?: string, metadata?: SDKErrorMetadata);
|
|
126
|
+
}
|
|
127
|
+
declare class LocalizationServerError extends LocalizationError {
|
|
128
|
+
constructor(message?: string, metadata?: SDKErrorMetadata);
|
|
129
|
+
}
|
|
130
|
+
declare class LocalizationNetworkError extends LocalizationError {
|
|
131
|
+
constructor(message?: string, metadata?: SDKErrorMetadata);
|
|
132
|
+
}
|
|
133
|
+
declare class LocalizationTimeoutError extends LocalizationError {
|
|
134
|
+
constructor(message?: string, metadata?: SDKErrorMetadata);
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
declare function provideLocalization(options: LocalizationClientOptions): EnvironmentProviders;
|
|
138
|
+
|
|
139
|
+
declare class LocalizationService {
|
|
140
|
+
private readonly client;
|
|
141
|
+
getCurrentLanguage(resourceKey: string): Observable<ResourceResponse>;
|
|
142
|
+
getByLanguage(resourceKey: string, languageKey: string): Observable<ResourceResponse>;
|
|
143
|
+
listResources(): Observable<readonly ResourceResponse[]>;
|
|
144
|
+
invalidateCache(key?: string): Observable<void>;
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
declare const LOCALIZATION_SDK_OPTIONS: InjectionToken<LocalizationClientOptions>;
|
|
148
|
+
declare const LOCALIZATION_CLIENT: InjectionToken<LocalizationClient>;
|
|
149
|
+
|
|
150
|
+
export { type AuthProvider, type CacheProvider, FetchHttpTransport, type HttpRequest, type HttpResponse, type HttpTransport, LOCALIZATION_CLIENT, LOCALIZATION_SDK_OPTIONS, LocalizationAuthError, type LocalizationClient, type LocalizationClientOptions, LocalizationError, LocalizationNetworkError, LocalizationServerError, LocalizationService, LocalizationTimeoutError, MemoryCacheProvider, ResourceNotFoundError, type ResourceResponse, type SDKLogger, type SDKMiddleware, XAuthTokenProvider, createLocalizationClient, provideLocalization };
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
import { EnvironmentProviders, InjectionToken } from '@angular/core';
|
|
2
|
+
import { Observable } from 'rxjs';
|
|
3
|
+
|
|
4
|
+
interface AuthProvider {
|
|
5
|
+
getToken(): Promise<string | null>;
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
interface CacheProvider {
|
|
9
|
+
get<T>(key: string): Promise<T | null>;
|
|
10
|
+
set<T>(key: string, value: T, ttlMs?: number): Promise<void>;
|
|
11
|
+
delete(key: string): Promise<void>;
|
|
12
|
+
clear(): Promise<void>;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
type HttpMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
|
|
16
|
+
interface HttpRequest {
|
|
17
|
+
readonly method: HttpMethod;
|
|
18
|
+
readonly path: string;
|
|
19
|
+
readonly query?: Readonly<Record<string, string | number | boolean | undefined>>;
|
|
20
|
+
readonly headers?: Readonly<Record<string, string>>;
|
|
21
|
+
readonly body?: unknown;
|
|
22
|
+
readonly timeoutMs?: number;
|
|
23
|
+
}
|
|
24
|
+
interface HttpResponse<T> {
|
|
25
|
+
readonly status: number;
|
|
26
|
+
readonly headers: Headers;
|
|
27
|
+
readonly data: T;
|
|
28
|
+
}
|
|
29
|
+
interface SDKMiddleware {
|
|
30
|
+
onRequest?(request: Request): Promise<Request>;
|
|
31
|
+
onResponse?(response: Response): Promise<Response>;
|
|
32
|
+
onError?(error: Error): Promise<void>;
|
|
33
|
+
}
|
|
34
|
+
interface HttpTransport {
|
|
35
|
+
request<T>(request: HttpRequest): Promise<HttpResponse<T>>;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
interface SDKLogger {
|
|
39
|
+
debug(message: string): void;
|
|
40
|
+
info(message: string): void;
|
|
41
|
+
warn(message: string): void;
|
|
42
|
+
error(message: string): void;
|
|
43
|
+
}
|
|
44
|
+
interface LocalizationClientOptions {
|
|
45
|
+
readonly baseUrl: string;
|
|
46
|
+
readonly token?: string;
|
|
47
|
+
readonly authProvider?: AuthProvider;
|
|
48
|
+
readonly timeoutMs?: number;
|
|
49
|
+
readonly headers?: Readonly<Record<string, string>>;
|
|
50
|
+
readonly middleware?: readonly SDKMiddleware[];
|
|
51
|
+
readonly fetchFn?: typeof fetch;
|
|
52
|
+
readonly cache?: {
|
|
53
|
+
readonly enabled?: boolean;
|
|
54
|
+
readonly provider?: CacheProvider;
|
|
55
|
+
readonly ttlMs?: number;
|
|
56
|
+
};
|
|
57
|
+
readonly logger?: SDKLogger;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
interface ResourceResponse {
|
|
61
|
+
readonly key: string;
|
|
62
|
+
readonly value: string;
|
|
63
|
+
readonly language: string;
|
|
64
|
+
readonly lastUpdated?: string;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
interface LocalizationClient {
|
|
68
|
+
getCurrentLanguage(resourceKey: string): Promise<ResourceResponse>;
|
|
69
|
+
getByLanguage(resourceKey: string, languageKey: string): Promise<ResourceResponse>;
|
|
70
|
+
listResources(): Promise<readonly ResourceResponse[]>;
|
|
71
|
+
invalidateCache(key?: string): Promise<void>;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
declare function createLocalizationClient(options: LocalizationClientOptions): LocalizationClient;
|
|
75
|
+
|
|
76
|
+
declare class XAuthTokenProvider implements AuthProvider {
|
|
77
|
+
private readonly token;
|
|
78
|
+
constructor(token: string);
|
|
79
|
+
getToken(): Promise<string | null>;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
declare class MemoryCacheProvider implements CacheProvider {
|
|
83
|
+
private readonly store;
|
|
84
|
+
get<T>(key: string): Promise<T | null>;
|
|
85
|
+
set<T>(key: string, value: T, ttlMs?: number): Promise<void>;
|
|
86
|
+
delete(key: string): Promise<void>;
|
|
87
|
+
clear(): Promise<void>;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
interface FetchHttpTransportOptions {
|
|
91
|
+
readonly baseUrl: string;
|
|
92
|
+
readonly fetchFn?: typeof fetch;
|
|
93
|
+
readonly defaultHeaders?: Readonly<Record<string, string>>;
|
|
94
|
+
readonly middleware?: readonly SDKMiddleware[];
|
|
95
|
+
readonly timeoutMs: number;
|
|
96
|
+
}
|
|
97
|
+
declare class FetchHttpTransport implements HttpTransport {
|
|
98
|
+
private readonly options;
|
|
99
|
+
private readonly fetchFn;
|
|
100
|
+
constructor(options: FetchHttpTransportOptions);
|
|
101
|
+
request<T>(request: HttpRequest): Promise<HttpResponse<T>>;
|
|
102
|
+
private resolveUrl;
|
|
103
|
+
private runRequestMiddleware;
|
|
104
|
+
private runResponseMiddleware;
|
|
105
|
+
private runErrorMiddleware;
|
|
106
|
+
private parseResponse;
|
|
107
|
+
private toError;
|
|
108
|
+
private isAbortError;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
interface SDKErrorMetadata {
|
|
112
|
+
readonly requestId?: string;
|
|
113
|
+
readonly statusCode?: number;
|
|
114
|
+
readonly traceId?: string;
|
|
115
|
+
readonly timestamp?: string;
|
|
116
|
+
}
|
|
117
|
+
declare class LocalizationError extends Error {
|
|
118
|
+
readonly metadata?: SDKErrorMetadata | undefined;
|
|
119
|
+
constructor(message: string, metadata?: SDKErrorMetadata | undefined);
|
|
120
|
+
}
|
|
121
|
+
declare class LocalizationAuthError extends LocalizationError {
|
|
122
|
+
constructor(message?: string, metadata?: SDKErrorMetadata);
|
|
123
|
+
}
|
|
124
|
+
declare class ResourceNotFoundError extends LocalizationError {
|
|
125
|
+
constructor(message?: string, metadata?: SDKErrorMetadata);
|
|
126
|
+
}
|
|
127
|
+
declare class LocalizationServerError extends LocalizationError {
|
|
128
|
+
constructor(message?: string, metadata?: SDKErrorMetadata);
|
|
129
|
+
}
|
|
130
|
+
declare class LocalizationNetworkError extends LocalizationError {
|
|
131
|
+
constructor(message?: string, metadata?: SDKErrorMetadata);
|
|
132
|
+
}
|
|
133
|
+
declare class LocalizationTimeoutError extends LocalizationError {
|
|
134
|
+
constructor(message?: string, metadata?: SDKErrorMetadata);
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
declare function provideLocalization(options: LocalizationClientOptions): EnvironmentProviders;
|
|
138
|
+
|
|
139
|
+
declare class LocalizationService {
|
|
140
|
+
private readonly client;
|
|
141
|
+
getCurrentLanguage(resourceKey: string): Observable<ResourceResponse>;
|
|
142
|
+
getByLanguage(resourceKey: string, languageKey: string): Observable<ResourceResponse>;
|
|
143
|
+
listResources(): Observable<readonly ResourceResponse[]>;
|
|
144
|
+
invalidateCache(key?: string): Observable<void>;
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
declare const LOCALIZATION_SDK_OPTIONS: InjectionToken<LocalizationClientOptions>;
|
|
148
|
+
declare const LOCALIZATION_CLIENT: InjectionToken<LocalizationClient>;
|
|
149
|
+
|
|
150
|
+
export { type AuthProvider, type CacheProvider, FetchHttpTransport, type HttpRequest, type HttpResponse, type HttpTransport, LOCALIZATION_CLIENT, LOCALIZATION_SDK_OPTIONS, LocalizationAuthError, type LocalizationClient, type LocalizationClientOptions, LocalizationError, LocalizationNetworkError, LocalizationServerError, LocalizationService, LocalizationTimeoutError, MemoryCacheProvider, ResourceNotFoundError, type ResourceResponse, type SDKLogger, type SDKMiddleware, XAuthTokenProvider, createLocalizationClient, provideLocalization };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
'use strict';var core=require('@angular/core'),rxjs=require('rxjs');var re=Object.create;var q=Object.defineProperty;var oe=Object.getOwnPropertyDescriptor;var $=(r,e)=>(e=Symbol[r])?e:Symbol.for("Symbol."+r),v=r=>{throw TypeError(r)};var ne=(r,e,t)=>e in r?q(r,e,{enumerable:true,configurable:true,writable:true,value:t}):r[e]=t;var j=(r,e)=>q(r,"name",{value:e,configurable:true});var V=r=>[,,,re(null)],X=["class","method","getter","setter","accessor","field","value","get","set"],w=r=>r!==void 0&&typeof r!="function"?v("Function expected"):r,ie=(r,e,t,o,n)=>({kind:X[r],name:e,metadata:o,addInitializer:a=>t._?v("Already initialized"):n.push(w(a||null))}),ae=(r,e)=>ne(e,$("metadata"),r[3]),J=(r,e,t,o)=>{for(var n=0,a=r[e>>1],l=a&&a.length;n<l;n++)a[n].call(t);return o},Y=(r,e,t,o,n,a)=>{var s,p,f,i=e&7,m=false,H=0,te=r[H]||(r[H]=[]),u=i&&((n=n.prototype),i<5&&(i>3||!m)&&oe(n,t));j(n,t);for(var N=o.length-1;N>=0;N--)f=ie(i,t,p={},r[3],te),s=(0, o[N])(n,f),p._=1,w(s)&&(n=s);return ae(r,n),u&&q(n,t,u),m?i^4?a:u:n};var g=class{constructor(e){this.token=e;}async getToken(){return this.token?.trim()?this.token:null}};var L=class{constructor(){this.store=new Map;}async get(e){let t=this.store.get(e);return t?t.expiresAt!==void 0&&Date.now()>t.expiresAt?(this.store.delete(e),null):t.value:null}async set(e,t,o){let n=o&&o>0?Date.now()+o:void 0;this.store.set(e,{value:t,expiresAt:n});}async delete(e){this.store.delete(e);}async clear(){this.store.clear();}};var c=class extends Error{constructor(t,o){super(t);this.metadata=o;this.name="LocalizationError";}},C=class extends c{constructor(e="Authentication failed",t){super(e,t),this.name="LocalizationAuthError";}},T=class extends c{constructor(e="Resource not found",t){super(e,t),this.name="ResourceNotFoundError";}},R=class extends c{constructor(e="Localization server error",t){super(e,t),this.name="LocalizationServerError";}},E=class extends c{constructor(e="Network error while contacting localization API",t){super(e,t),this.name="LocalizationNetworkError";}},x=class extends c{constructor(e="Localization request timeout",t){super(e,t),this.name="LocalizationTimeoutError";}};var P=class extends Error{constructor(t,o,n){super(`Request failed with status ${t}`);this.statusCode=t;this.responseBody=o;this.responseHeaders=n;this.name="HttpStatusError";}},z=class extends Error{constructor(t){super(`Request timed out after ${t}ms`);this.timeoutMs=t;this.name="HttpTimeoutError";}},O=class extends Error{constructor(t){super("Network error while sending request");this.causeError=t;this.name="HttpNetworkError";}},A=class{constructor(e){this.options=e;this.fetchFn=e.fetchFn??fetch;}async request(e){let t=e.timeoutMs??this.options.timeoutMs,o=new AbortController,n=setTimeout(()=>o.abort(),t),a=new Request(this.resolveUrl(e),{method:e.method,headers:{"Content-Type":"application/json",...this.options.defaultHeaders,...e.headers},body:e.body===void 0?void 0:JSON.stringify(e.body),signal:o.signal});try{let l=await this.runRequestMiddleware(a),s;try{s=await this.fetchFn(l);}catch(h){throw this.isAbortError(h)?new z(t):new O(h)}let p=await this.runResponseMiddleware(s);if(!p.ok){let h=await p.text();throw new P(p.status,h,p.headers)}let f=await this.parseResponse(p);return {status:p.status,headers:p.headers,data:f}}catch(l){throw await this.runErrorMiddleware(this.toError(l)),l}finally{clearTimeout(n);}}resolveUrl(e){let t=new URL(e.path,this.options.baseUrl);return e.query&&Object.entries(e.query).forEach(([o,n])=>{n!==void 0&&t.searchParams.set(o,String(n));}),t.toString()}async runRequestMiddleware(e){let t=e;for(let o of this.options.middleware??[])o.onRequest&&(t=await o.onRequest(t));return t}async runResponseMiddleware(e){let t=e;for(let o of this.options.middleware??[])o.onResponse&&(t=await o.onResponse(t));return t}async runErrorMiddleware(e){for(let t of this.options.middleware??[])t.onError&&await t.onError(e);}async parseResponse(e){return e.status===204?null:(e.headers.get("content-type")??"").includes("application/json")?await e.json():await e.text()}toError(e){return e instanceof Error?e:new Error("Unknown request error")}isAbortError(e){return e instanceof DOMException&&e.name==="AbortError"}};var Q="localization:listResources",I=class{constructor(e){this.dependencies=e;}async getCurrentLanguage(e){this.validateRequired(e,"resourceKey");let t=await this.send({method:"GET",path:"api/localization/client/currentlanguage",query:{resourceKey:e}});return {key:e,value:t??"",language:"current"}}async getByLanguage(e,t){this.validateRequired(e,"resourceKey"),this.validateRequired(t,"languageKey");let o=await this.send({method:"GET",path:"api/localization/client/bylanguage",query:{resourceKey:e,languageKey:t}});return {key:e,value:o??"",language:t}}async listResources(){let e=await this.dependencies.cacheProvider?.get(Q);if(e)return e;let o=(await this.send({method:"GET",path:"api/localization/client/list"})??[]).map(n=>({key:n.resourceKey,value:n.value,language:n.languageKey}));return await this.dependencies.cacheProvider?.set(Q,o,this.dependencies.cacheTtlMs),o}async invalidateCache(e){if(this.dependencies.cacheProvider){if(e){await this.dependencies.cacheProvider.delete(e);return}await this.dependencies.cacheProvider.clear();}}async send(e){try{let t=await this.dependencies.authProvider?.getToken(),o=t?{...e.headers,"X-Auth-Token":t}:e.headers;return (await this.dependencies.httpTransport.request({...e,headers:o})).data}catch(t){throw this.mapError(t)}}mapError(e){return e instanceof c?e:e instanceof z?new x(e.message):e instanceof O?new E(e.message):e instanceof P?e.statusCode===401||e.statusCode===403?new C("Invalid token for localization endpoint",{statusCode:e.statusCode}):e.statusCode===404?new T("Localization resource was not found",{statusCode:e.statusCode}):e.statusCode>=500?new R("Localization API is unavailable",{statusCode:e.statusCode}):new c(e.message,{statusCode:e.statusCode}):new c("Unexpected localization SDK error")}validateRequired(e,t){if(!e?.trim())throw new c(`${t} is required`)}};function K(r){le(r);let t=r.cache?.enabled??false?r.cache?.provider??new L:void 0,o=new A({baseUrl:r.baseUrl,fetchFn:r.fetchFn,timeoutMs:r.timeoutMs??1e4,defaultHeaders:r.headers,middleware:r.middleware});return new I({httpTransport:o,authProvider:r.authProvider??(r.token?new g(r.token):void 0),cacheProvider:t,cacheTtlMs:r.cache?.ttlMs})}function le(r){if(!r?.baseUrl?.trim())throw new c("baseUrl is required to create localization client")}var _=new core.InjectionToken("LOCALIZATION_SDK_OPTIONS"),b=new core.InjectionToken("LOCALIZATION_CLIENT");function ue(r){return core.makeEnvironmentProviders([{provide:_,useValue:r},{provide:b,useFactory:()=>K(r)}])}var ee,F;ee=[core.Injectable({providedIn:"root"})];exports.LocalizationService=class y{constructor(){this.client=core.inject(b);}getCurrentLanguage(e){return rxjs.from(this.client.getCurrentLanguage(e))}getByLanguage(e,t){return rxjs.from(this.client.getByLanguage(e,t))}listResources(){return rxjs.from(this.client.listResources())}invalidateCache(e){return rxjs.from(this.client.invalidateCache(e))}};F=V(),exports.LocalizationService=Y(F,0,"LocalizationService",ee,exports.LocalizationService),J(F,1,exports.LocalizationService);exports.FetchHttpTransport=A;exports.LOCALIZATION_CLIENT=b;exports.LOCALIZATION_SDK_OPTIONS=_;exports.LocalizationAuthError=C;exports.LocalizationError=c;exports.LocalizationNetworkError=E;exports.LocalizationServerError=R;exports.LocalizationTimeoutError=x;exports.MemoryCacheProvider=L;exports.ResourceNotFoundError=T;exports.XAuthTokenProvider=g;exports.createLocalizationClient=K;exports.provideLocalization=ue;
|
package/dist/index.mjs
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import {InjectionToken,Injectable,makeEnvironmentProviders,inject}from'@angular/core';import {from}from'rxjs';var re=Object.create;var q=Object.defineProperty;var oe=Object.getOwnPropertyDescriptor;var $=(r,e)=>(e=Symbol[r])?e:Symbol.for("Symbol."+r),v=r=>{throw TypeError(r)};var ne=(r,e,t)=>e in r?q(r,e,{enumerable:true,configurable:true,writable:true,value:t}):r[e]=t;var j=(r,e)=>q(r,"name",{value:e,configurable:true});var V=r=>[,,,re(null)],X=["class","method","getter","setter","accessor","field","value","get","set"],w=r=>r!==void 0&&typeof r!="function"?v("Function expected"):r,ie=(r,e,t,o,n)=>({kind:X[r],name:e,metadata:o,addInitializer:a=>t._?v("Already initialized"):n.push(w(a||null))}),ae=(r,e)=>ne(e,$("metadata"),r[3]),J=(r,e,t,o)=>{for(var n=0,a=r[e>>1],l=a&&a.length;n<l;n++)a[n].call(t);return o},Y=(r,e,t,o,n,a)=>{var s,p,f,i=e&7,m=false,H=0,te=r[H]||(r[H]=[]),u=i&&((n=n.prototype),i<5&&(i>3||!m)&&oe(n,t));j(n,t);for(var N=o.length-1;N>=0;N--)f=ie(i,t,p={},r[3],te),s=(0, o[N])(n,f),p._=1,w(s)&&(n=s);return ae(r,n),u&&q(n,t,u),m?i^4?a:u:n};var g=class{constructor(e){this.token=e;}async getToken(){return this.token?.trim()?this.token:null}};var L=class{constructor(){this.store=new Map;}async get(e){let t=this.store.get(e);return t?t.expiresAt!==void 0&&Date.now()>t.expiresAt?(this.store.delete(e),null):t.value:null}async set(e,t,o){let n=o&&o>0?Date.now()+o:void 0;this.store.set(e,{value:t,expiresAt:n});}async delete(e){this.store.delete(e);}async clear(){this.store.clear();}};var c=class extends Error{constructor(t,o){super(t);this.metadata=o;this.name="LocalizationError";}},C=class extends c{constructor(e="Authentication failed",t){super(e,t),this.name="LocalizationAuthError";}},T=class extends c{constructor(e="Resource not found",t){super(e,t),this.name="ResourceNotFoundError";}},R=class extends c{constructor(e="Localization server error",t){super(e,t),this.name="LocalizationServerError";}},E=class extends c{constructor(e="Network error while contacting localization API",t){super(e,t),this.name="LocalizationNetworkError";}},x=class extends c{constructor(e="Localization request timeout",t){super(e,t),this.name="LocalizationTimeoutError";}};var P=class extends Error{constructor(t,o,n){super(`Request failed with status ${t}`);this.statusCode=t;this.responseBody=o;this.responseHeaders=n;this.name="HttpStatusError";}},z=class extends Error{constructor(t){super(`Request timed out after ${t}ms`);this.timeoutMs=t;this.name="HttpTimeoutError";}},O=class extends Error{constructor(t){super("Network error while sending request");this.causeError=t;this.name="HttpNetworkError";}},A=class{constructor(e){this.options=e;this.fetchFn=e.fetchFn??fetch;}async request(e){let t=e.timeoutMs??this.options.timeoutMs,o=new AbortController,n=setTimeout(()=>o.abort(),t),a=new Request(this.resolveUrl(e),{method:e.method,headers:{"Content-Type":"application/json",...this.options.defaultHeaders,...e.headers},body:e.body===void 0?void 0:JSON.stringify(e.body),signal:o.signal});try{let l=await this.runRequestMiddleware(a),s;try{s=await this.fetchFn(l);}catch(h){throw this.isAbortError(h)?new z(t):new O(h)}let p=await this.runResponseMiddleware(s);if(!p.ok){let h=await p.text();throw new P(p.status,h,p.headers)}let f=await this.parseResponse(p);return {status:p.status,headers:p.headers,data:f}}catch(l){throw await this.runErrorMiddleware(this.toError(l)),l}finally{clearTimeout(n);}}resolveUrl(e){let t=new URL(e.path,this.options.baseUrl);return e.query&&Object.entries(e.query).forEach(([o,n])=>{n!==void 0&&t.searchParams.set(o,String(n));}),t.toString()}async runRequestMiddleware(e){let t=e;for(let o of this.options.middleware??[])o.onRequest&&(t=await o.onRequest(t));return t}async runResponseMiddleware(e){let t=e;for(let o of this.options.middleware??[])o.onResponse&&(t=await o.onResponse(t));return t}async runErrorMiddleware(e){for(let t of this.options.middleware??[])t.onError&&await t.onError(e);}async parseResponse(e){return e.status===204?null:(e.headers.get("content-type")??"").includes("application/json")?await e.json():await e.text()}toError(e){return e instanceof Error?e:new Error("Unknown request error")}isAbortError(e){return e instanceof DOMException&&e.name==="AbortError"}};var Q="localization:listResources",I=class{constructor(e){this.dependencies=e;}async getCurrentLanguage(e){this.validateRequired(e,"resourceKey");let t=await this.send({method:"GET",path:"api/localization/client/currentlanguage",query:{resourceKey:e}});return {key:e,value:t??"",language:"current"}}async getByLanguage(e,t){this.validateRequired(e,"resourceKey"),this.validateRequired(t,"languageKey");let o=await this.send({method:"GET",path:"api/localization/client/bylanguage",query:{resourceKey:e,languageKey:t}});return {key:e,value:o??"",language:t}}async listResources(){let e=await this.dependencies.cacheProvider?.get(Q);if(e)return e;let o=(await this.send({method:"GET",path:"api/localization/client/list"})??[]).map(n=>({key:n.resourceKey,value:n.value,language:n.languageKey}));return await this.dependencies.cacheProvider?.set(Q,o,this.dependencies.cacheTtlMs),o}async invalidateCache(e){if(this.dependencies.cacheProvider){if(e){await this.dependencies.cacheProvider.delete(e);return}await this.dependencies.cacheProvider.clear();}}async send(e){try{let t=await this.dependencies.authProvider?.getToken(),o=t?{...e.headers,"X-Auth-Token":t}:e.headers;return (await this.dependencies.httpTransport.request({...e,headers:o})).data}catch(t){throw this.mapError(t)}}mapError(e){return e instanceof c?e:e instanceof z?new x(e.message):e instanceof O?new E(e.message):e instanceof P?e.statusCode===401||e.statusCode===403?new C("Invalid token for localization endpoint",{statusCode:e.statusCode}):e.statusCode===404?new T("Localization resource was not found",{statusCode:e.statusCode}):e.statusCode>=500?new R("Localization API is unavailable",{statusCode:e.statusCode}):new c(e.message,{statusCode:e.statusCode}):new c("Unexpected localization SDK error")}validateRequired(e,t){if(!e?.trim())throw new c(`${t} is required`)}};function K(r){le(r);let t=r.cache?.enabled??false?r.cache?.provider??new L:void 0,o=new A({baseUrl:r.baseUrl,fetchFn:r.fetchFn,timeoutMs:r.timeoutMs??1e4,defaultHeaders:r.headers,middleware:r.middleware});return new I({httpTransport:o,authProvider:r.authProvider??(r.token?new g(r.token):void 0),cacheProvider:t,cacheTtlMs:r.cache?.ttlMs})}function le(r){if(!r?.baseUrl?.trim())throw new c("baseUrl is required to create localization client")}var _=new InjectionToken("LOCALIZATION_SDK_OPTIONS"),b=new InjectionToken("LOCALIZATION_CLIENT");function ue(r){return makeEnvironmentProviders([{provide:_,useValue:r},{provide:b,useFactory:()=>K(r)}])}var ee,F;ee=[Injectable({providedIn:"root"})];var y=class{constructor(){this.client=inject(b);}getCurrentLanguage(e){return from(this.client.getCurrentLanguage(e))}getByLanguage(e,t){return from(this.client.getByLanguage(e,t))}listResources(){return from(this.client.listResources())}invalidateCache(e){return from(this.client.invalidateCache(e))}};F=V(),y=Y(F,0,"LocalizationService",ee,y),J(F,1,y);export{A as FetchHttpTransport,b as LOCALIZATION_CLIENT,_ as LOCALIZATION_SDK_OPTIONS,C as LocalizationAuthError,c as LocalizationError,E as LocalizationNetworkError,R as LocalizationServerError,y as LocalizationService,x as LocalizationTimeoutError,L as MemoryCacheProvider,T as ResourceNotFoundError,g as XAuthTokenProvider,K as createLocalizationClient,ue as provideLocalization};
|
package/package.json
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
{
|
|
2
|
+
"description": "TypeScript SDK for SmartCoreHub localization API",
|
|
3
|
+
"license": "SEE LICENSE IN LICENSE",
|
|
4
|
+
"scripts": {
|
|
5
|
+
"lint": "eslint src/**/*.ts",
|
|
6
|
+
"version:auto": "node ./scripts/auto-version.cjs",
|
|
7
|
+
"prebuild": "npm run version:auto",
|
|
8
|
+
"build": "tsup",
|
|
9
|
+
"prebuild:prod": "npm run version:auto",
|
|
10
|
+
"build:prod": "tsup --config tsup.config.prod.ts",
|
|
11
|
+
"test": "jest --config jest.config.js"
|
|
12
|
+
},
|
|
13
|
+
"main": "./dist/index.js",
|
|
14
|
+
"name": "@smartcorehub/localization-sdk",
|
|
15
|
+
"sideEffects": false,
|
|
16
|
+
"files": [
|
|
17
|
+
"dist"
|
|
18
|
+
],
|
|
19
|
+
"publishConfig": {
|
|
20
|
+
"access": "public"
|
|
21
|
+
},
|
|
22
|
+
"version": "1.0.3474",
|
|
23
|
+
"devDependencies": {
|
|
24
|
+
"@angular/core": "^20.3.15",
|
|
25
|
+
"@angular/common": "^20.3.15",
|
|
26
|
+
"@angular/compiler": "^20.3.15",
|
|
27
|
+
"@angular/compiler-cli": "^20.3.15",
|
|
28
|
+
"@angular/platform-browser": "^20.3.15",
|
|
29
|
+
"@angular/platform-browser-dynamic": "^20.3.15",
|
|
30
|
+
"jest-preset-angular": "^16.0.0",
|
|
31
|
+
"jest-environment-jsdom": "^30.2.0",
|
|
32
|
+
"jest-html-reporter": "^4.4.0",
|
|
33
|
+
"jest-html-reporters": "^3.1.7",
|
|
34
|
+
"jest": "^30.2.0",
|
|
35
|
+
"jest-junit": "^16.0.0",
|
|
36
|
+
"jest-sonar": "^0.2.16",
|
|
37
|
+
"jest-stare": "^2.5.3",
|
|
38
|
+
"@types/jest": "^30.0.0",
|
|
39
|
+
"ts-jest": "^29.0.0",
|
|
40
|
+
"rxjs": "^7.8.0",
|
|
41
|
+
"tsup": "^8.0.0",
|
|
42
|
+
"typescript": "^5.0.0",
|
|
43
|
+
"whatwg-fetch": "^3.6.20",
|
|
44
|
+
"zone.js": "~0.15.0"
|
|
45
|
+
},
|
|
46
|
+
"peerDependencies": {
|
|
47
|
+
"@angular/core": ">=16",
|
|
48
|
+
"rxjs": ">=7"
|
|
49
|
+
},
|
|
50
|
+
"peerDependenciesMeta": {
|
|
51
|
+
"@angular/core": {
|
|
52
|
+
"optional": true
|
|
53
|
+
},
|
|
54
|
+
"rxjs": {
|
|
55
|
+
"optional": true
|
|
56
|
+
}
|
|
57
|
+
},
|
|
58
|
+
"module": "./dist/index.mjs",
|
|
59
|
+
"types": "./dist/index.d.ts"
|
|
60
|
+
}
|