@apollion-dsi/relay 0.27.2 → 0.27.3

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.
@@ -1,205 +1,205 @@
1
1
  /**
2
- * @fileoverview Tipos públicos consumidos pelo `setupRelayEnvironment`
3
- * (`RelayArgsInterface`) e pelos seus internals (`Sink`).
2
+ * @fileoverview Public types consumed by `setupRelayEnvironment`
3
+ * (`RelayArgsInterface`) and by its internals (`Sink`).
4
4
  *
5
- * `RelayArgsInterface` é o contrato de configuração de
6
- * `CreateRelayEnvironment` — qualquer mudança aqui é parte da API
7
- * pública do package.
5
+ * `RelayArgsInterface` is the configuration contract of
6
+ * `CreateRelayEnvironment` — any change here is part of the package's
7
+ * public API.
8
8
  */
9
9
  /**
10
- * Sink do `Observable` Relay. Implementado pelo runtime do Relay e
11
- * passado para o callback de `Observable.create`. Os internals de
12
- * fetch/subscription usam essa interface para propagar dados, erros
13
- * e completação para a stream.
10
+ * Relay `Observable` sink. Implemented by the Relay runtime and
11
+ * passed to the `Observable.create` callback. The fetch/subscription
12
+ * internals use this interface to propagate data, errors
13
+ * and completion to the stream.
14
14
  */
15
15
  export interface Sink {
16
- /** Empurra o próximo valor para a stream. */
16
+ /** Pushes the next value into the stream. */
17
17
  next(value: any): void;
18
- /** Reporta um erro e fecha a stream. */
18
+ /** Reports an error and closes the stream. */
19
19
  error(error: Error, isUncaughtThrownError?: boolean): void;
20
- /** Sinaliza completação normal da stream. */
20
+ /** Signals normal stream completion. */
21
21
  complete(): void;
22
- /** `true` quando a stream foi fechada (sink complete/error). */
22
+ /** `true` when the stream has already been closed (sink complete/error). */
23
23
  readonly closed: boolean;
24
24
  }
25
25
  /**
26
- * Configuração aceita pelo construtor de `CreateRelayEnvironment`.
26
+ * Configuration accepted by the `CreateRelayEnvironment` constructor.
27
27
  *
28
- * Apenas `url` é obrigatório. Todos os demais campos têm defaults
29
- * sensatos definidos no construtor.
28
+ * Only `url` is required. All the other fields have sensible defaults
29
+ * defined in the constructor.
30
30
  *
31
- * @see {@link "../setupRelayEnvironment/setupRelayEnvironment"} para os defaults.
31
+ * @see {@link "../setupRelayEnvironment/setupRelayEnvironment"} for the defaults.
32
32
  */
33
33
  export interface RelayArgsInterface {
34
34
  /**
35
- * Endpoint HTTP do servidor GraphQL. Obrigatório.
35
+ * HTTP endpoint of the GraphQL server. Required.
36
36
  */
37
37
  url: string;
38
38
  /**
39
- * Endpoint do servidor de autenticação. Usado pelo fluxo de
40
- * verificação de sessão (`${authUrl}user/me`). Obrigatório quando
41
- * `useAuthorization` é `true`.
39
+ * Authentication server endpoint. Used by the session verification
40
+ * flow (`${authUrl}user/me`). Required when
41
+ * `useAuthorization` is `true`.
42
42
  */
43
43
  authUrl?: string;
44
44
  /**
45
- * Endpoint WebSocket para subscriptions GraphQL. Obrigatório quando
46
- * `useSubscription` é `true`.
45
+ * WebSocket endpoint for GraphQL subscriptions. Required when
46
+ * `useSubscription` is `true`.
47
47
  */
48
48
  socket?: string;
49
49
  /**
50
- * Lista de delays (ms) entre tentativas de retry, com backoff.
50
+ * List of delays (ms) between retry attempts, with backoff.
51
51
  *
52
52
  * @defaultValue `[1s, 2s, 3s, 5s, 8s, 13s, 21s, 34s]` (fibonacci-like)
53
53
  */
54
54
  retries?: number[];
55
55
  /**
56
- * Timeout por requisição em ms.
56
+ * Per-request timeout in ms.
57
57
  *
58
- * @defaultValue 15 minutos
58
+ * @defaultValue 15 minutes
59
59
  */
60
60
  timeout?: number;
61
61
  /**
62
- * Habilita o handler de subscriptions GraphQL via WebSocket.
62
+ * Enables the GraphQL subscriptions handler over WebSocket.
63
63
  *
64
64
  * @defaultValue false
65
65
  */
66
66
  useSubscription?: boolean;
67
67
  /**
68
- * Habilita autenticação via JWT injeta `Authorization: Bearer <token>`
69
- * em cada request usando o `sessionToken` armazenado.
68
+ * Enables JWT authenticationinjects `Authorization: Bearer <token>`
69
+ * on every request using the stored `sessionToken`.
70
70
  *
71
71
  * @defaultValue false
72
72
  */
73
73
  useAuthorization?: boolean;
74
74
  /**
75
- * Modelo de autenticação usado pelo Environment.
75
+ * Authentication model used by the Environment.
76
76
  *
77
- * - `'bearer'` (default, retrocompat): o `sessionToken` do storage
78
- * JS-legível e injeta `Authorization: Bearer <token>` em cada request.
79
- * A verificação de sessão usa o probe `${authUrl}user/me`.
80
- * - `'cookie'`: modelo de **sessão por cookie httpOnly**. O Environment
81
- * **não** o token em JS nem injeta `Authorization` — o cookie de
82
- * sessão (httpOnly + SameSite) viaja sozinho desde que o fetch use
83
- * `credentials` (default `'include'` neste modo). A renovação de
84
- * sessão é disparada por erro de auth (ex: 401) chamando `authUrl`
85
- * com `credentials:'include'`, sem probe a `user/me`.
77
+ * - `'bearer'` (default, backwards-compatible): reads the `sessionToken`
78
+ * from JS-readable storage and injects `Authorization: Bearer <token>`
79
+ * on every request. Session verification uses the `${authUrl}user/me` probe.
80
+ * - `'cookie'`: **httpOnly cookie session** model. The Environment does
81
+ * **not** read the token in JS nor inject `Authorization` — the session
82
+ * cookie (httpOnly + SameSite) travels on its own as long as the fetch uses
83
+ * `credentials` (default `'include'` in this mode). Session renewal
84
+ * is triggered by an auth error (e.g. 401) calling `authUrl`
85
+ * with `credentials:'include'`, without probing `user/me`.
86
86
  *
87
87
  * @defaultValue `'bearer'`
88
88
  */
89
89
  authMode?: 'bearer' | 'cookie';
90
90
  /**
91
- * Valor de `credentials` repassado aos fetches GraphQL e de
92
- * verificação/refresh de sessão. Use `'include'` para que o browser
93
- * anexe automaticamente cookies httpOnly de sessão (inclusive
91
+ * `credentials` value forwarded to the GraphQL and session
92
+ * verification/refresh fetches. Use `'include'` so the browser
93
+ * automatically attaches httpOnly session cookies (including
94
94
  * cross-origin).
95
95
  *
96
- * Quando não definido: `'include'` no modo `authMode:'cookie'`, e
97
- * omitido (default do browser) no modo `'bearer'` — preservando a
98
- * retrocompat dos consumidores Bearer existentes.
96
+ * When not set: `'include'` in `authMode:'cookie'` mode, and
97
+ * omitted (browser default) in `'bearer'` mode preserving
98
+ * backwards compatibility for existing Bearer consumers.
99
99
  *
100
- * @defaultValue `authMode:'cookie'` → `'include'`; senão omitido.
100
+ * @defaultValue `authMode:'cookie'` → `'include'`; otherwise omitted.
101
101
  */
102
102
  credentials?: RequestCredentials;
103
103
  /**
104
- * URL usada para verificar/renovar a sessão quando um erro de auth é
105
- * detectado. Torna o probe configurável/opcional:
104
+ * URL used to verify/renew the session when an auth error is
105
+ * detected. Makes the probe configurable/optional:
106
106
  *
107
- * - `string` — sobrescreve a URL padrão do probe.
108
- * - `false` — **desliga** o probe; um erro de auth é tratado como
109
- * logout direto (limpa storage + redireciona para `loginRoute`),
110
- * sem nenhuma requisição extra.
111
- * - não definidousa o default do modo: `${authUrl}user/me` (GET,
112
- * modo `bearer`) ou `authUrl` (POST + `credentials:'include'`, modo
113
- * `cookie`).
107
+ * - `string` — overrides the default probe URL.
108
+ * - `false` — **disables** the probe; an auth error is treated as
109
+ * a direct logout (clears storage + redirects to `loginRoute`),
110
+ * without any extra request.
111
+ * - not setuses the mode's default: `${authUrl}user/me` (GET,
112
+ * `bearer` mode) or `authUrl` (POST + `credentials:'include'`,
113
+ * `cookie` mode).
114
114
  *
115
- * @defaultValue depende de `authMode` (veja acima).
115
+ * @defaultValue depends on `authMode` (see above).
116
116
  */
117
117
  sessionCheckUrl?: string | false;
118
118
  /**
119
- * Habilita cache de respostas via `QueryResponseCache` do Relay.
120
- * Por recomendação do time do Relay, vem desligado por padrão.
119
+ * Enables response caching via Relay's `QueryResponseCache`.
120
+ * Per the Relay team's recommendation, it is off by default.
121
121
  *
122
122
  * @defaultValue false
123
123
  */
124
124
  useCache?: boolean;
125
125
  /**
126
- * TTL (ms) das entradas do cache de queries.
126
+ * TTL (ms) of the query cache entries.
127
127
  *
128
- * @defaultValue 8 minutos
128
+ * @defaultValue 8 minutes
129
129
  */
130
130
  cacheTime?: number;
131
131
  /**
132
- * Tamanho máximo do cache (número de queries distintas mantidas).
132
+ * Maximum cache size (number of distinct queries kept).
133
133
  *
134
134
  * @defaultValue 250
135
135
  */
136
136
  cacheSize?: number;
137
137
  /**
138
- * Nome da chave usada em storage para o token de sessão (JWT).
138
+ * Storage key name for the session token (JWT).
139
139
  *
140
140
  * @defaultValue `'USER_SESSION_TOKEN'`
141
141
  */
142
142
  sessionStorageProp?: string;
143
143
  /**
144
- * Nome da chave usada em storage para o refresh token.
144
+ * Storage key name for the refresh token.
145
145
  *
146
146
  * @defaultValue `'USER_REFRESH_TOKEN'`
147
147
  */
148
148
  refreshStorageProp?: string;
149
149
  /**
150
- * Rota interna para a qual o usuário será redirecionado quando a
151
- * sessão expirar (ou em erros de auth, se `redirectOnError` estiver
152
- * ligado).
150
+ * Internal route the user is redirected to when the
151
+ * session expires (or on auth errors, if `redirectOnError` is
152
+ * enabled).
153
153
  *
154
154
  * @defaultValue `'/'`
155
155
  */
156
156
  loginRoute?: string;
157
157
  /**
158
- * Liga logs verbosos (útil em desenvolvimento). Não habilite em
159
- * produção.
158
+ * Turns on verbose logs (useful in development). Do not enable in
159
+ * production.
160
160
  *
161
161
  * @defaultValue false
162
162
  */
163
163
  useDebug?: boolean;
164
164
  /**
165
- * Habilita retries em caso de erro/timeout, usando os delays de
165
+ * Enables retries on error/timeout, using the delays from
166
166
  * `retries`.
167
167
  *
168
168
  * @defaultValue false
169
169
  */
170
170
  useRetries?: boolean;
171
171
  /**
172
- * Redireciona o usuário para `loginRoute` quando um erro com status
173
- * em `authenticationErrors` é detectado e a sessão é considerada
174
- * inválida.
172
+ * Redirects the user to `loginRoute` when an error with a status
173
+ * in `authenticationErrors` is detected and the session is considered
174
+ * invalid.
175
175
  *
176
176
  * @defaultValue false
177
177
  */
178
178
  redirectOnError?: boolean;
179
179
  /**
180
- * Lista de status HTTP que disparam retry (quando `useRetries` é
181
- * `true`). Defaults cobrem erros típicos de Cloudflare.
180
+ * List of HTTP statuses that trigger a retry (when `useRetries` is
181
+ * `true`). Defaults cover typical Cloudflare errors.
182
182
  *
183
183
  * @defaultValue `[503, 504, 521, 522, 524]`
184
184
  * @see https://support.cloudflare.com/hc/pt-br/articles/115003011431-Solu%C3%A7%C3%A3o-de-problemas-de-erros-5XX-da-Cloudflare
185
185
  */
186
186
  retryWhen?: number[];
187
187
  /**
188
- * Status considerados como erro de autenticação para o fluxo de
189
- * `redirectOnError`.
188
+ * Statuses treated as authentication errors for the
189
+ * `redirectOnError` flow.
190
190
  *
191
191
  * @defaultValue `[401, 403]`
192
192
  */
193
193
  authenticationErrors?: number[];
194
194
  /**
195
- * Estratégia de storage no browser para tokens.
195
+ * Browser storage strategy for tokens.
196
196
  *
197
197
  * @defaultValue `'localStorage'`
198
198
  */
199
199
  storageType?: 'cookie' | 'localStorage';
200
200
  /**
201
- * Identificador de parceiro enviado em todas as requests via
202
- * header `X-Partner`. Útil para tenants/whitelabels.
201
+ * Partner identifier sent on every request via the
202
+ * `X-Partner` header. Useful for tenants/whitelabels.
203
203
  *
204
204
  * @defaultValue undefined
205
205
  */
@@ -1,27 +1,27 @@
1
1
  /**
2
- * @fileoverview Detecção de ambiente de execução (browser/DOM,
3
- * Worker, viewport) usada por `setupRelayEnvironment` para alternar
4
- * comportamento entre browser e SSR.
2
+ * @fileoverview Execution environment detection (browser/DOM,
3
+ * Worker, viewport) used by `setupRelayEnvironment` to switch
4
+ * behavior between browser and SSR.
5
5
  *
6
- * Não exposto pelo barrel raiz implementação interna de
6
+ * Not exposed by the root barrel — internal implementation of
7
7
  * `CreateRelayEnvironment`.
8
8
  */
9
9
  /**
10
- * Conjunto de flags booleanas indicando capacidades do ambiente atual.
11
- * Inspirado no antigo `fbjs/ExecutionEnvironment`. Usado para evitar
12
- * dependências circulares e permitir que o código reaja a SSR sem
13
- * importar React diretamente.
10
+ * Set of boolean flags indicating the current environment's capabilities.
11
+ * Inspired by the old `fbjs/ExecutionEnvironment`. Used to avoid
12
+ * circular dependencies and let code react to SSR without
13
+ * importing React directly.
14
14
  */
15
15
  declare const _default: {
16
- /** `true` em browsers. */
16
+ /** `true` in browsers. */
17
17
  canUseDOM: boolean;
18
- /** `true` se `Worker` está disponível globalmente. */
18
+ /** `true` if `Worker` is globally available. */
19
19
  canUseWorkers: boolean;
20
- /** `true` em browsers que suportam `addEventListener` ou IE `attachEvent`. */
20
+ /** `true` in browsers supporting `addEventListener` or IE `attachEvent`. */
21
21
  canUseEventListeners: boolean;
22
- /** `true` em browsers com `window.screen` (viewport mensurável). */
22
+ /** `true` in browsers with `window.screen` (measurable viewport). */
23
23
  canUseViewport: boolean;
24
- /** `true` quando rodando em um Worker (sem DOM). */
24
+ /** `true` when running in a Worker (no DOM). */
25
25
  isInWorker: boolean;
26
26
  };
27
27
  export default _default;
@@ -1,29 +1,29 @@
1
1
  /**
2
- * @fileoverview Fábrica da `fetchFn` do Relay usada por
3
- * `setupRelayEnvironment`. Encapsula cache de respostas, retries via
4
- * `fetchWithRetries`, tratamento de erros (incluindo redirect em caso
5
- * de sessão expirada) e adaptação para o modelo `Observable` que o
6
- * `Network.create` do Relay espera.
2
+ * @fileoverview Factory for the Relay `fetchFn` used by
3
+ * `setupRelayEnvironment`. Encapsulates response caching, retries via
4
+ * `fetchWithRetries`, error handling (including redirect when the
5
+ * session expires) and the adaptation to the `Observable` model that
6
+ * Relay's `Network.create` expects.
7
7
  *
8
- * Não exposto pelo barrel raiz implementação interna de
8
+ * Not exposed by the root barrel — internal implementation of
9
9
  * `CreateRelayEnvironment`.
10
10
  */
11
11
  import { CacheConfig, Observable, RequestParameters, UploadableMap, Variables } from 'relay-runtime';
12
12
  /**
13
- * Cria a fetch function que será passada para `Network.create` do Relay.
13
+ * Creates the fetch function that will be passed to Relay's `Network.create`.
14
14
  *
15
- * Comportamento:
16
- * - Para queries com `useCache` ligado, tenta servir do cache
17
- * (`QueryResponseCache`) antes de fazer a requisição.
18
- * - Para mutations com `useCache` ligado, limpa o cache (invalidação
19
- * total — Relay vai re-buscar queries afetadas).
20
- * - Em caso de erro de autenticação detectado, verifica/renova a sessão
21
- * (modo bearer: probe `${authUrl}user/me`; modo cookie httpOnly:
22
- * refresh em `authUrl` com `credentials:'include'`) e, se inválida,
23
- * limpa storage e redireciona para `loginRoute`.
24
- * - Erros são propagados via `sink.error()`.
15
+ * Behavior:
16
+ * - For queries with `useCache` on, tries to serve from the cache
17
+ * (`QueryResponseCache`) before making the request.
18
+ * - For mutations with `useCache` on, clears the cache (full
19
+ * invalidation — Relay will re-fetch affected queries).
20
+ * - When an authentication error is detected, verifies/renews the session
21
+ * (bearer mode: `${authUrl}user/me` probe; httpOnly cookie mode:
22
+ * refresh at `authUrl` with `credentials:'include'`) and, if invalid,
23
+ * clears storage and redirects to `loginRoute`.
24
+ * - Errors are propagated via `sink.error()`.
25
25
  *
26
- * @param config - Instância de `CreateRelayEnvironment` configurada.
27
- * @returns Função compatível com `Network.create(fetchFn, ...)`.
26
+ * @param config - Configured `CreateRelayEnvironment` instance.
27
+ * @returns Function compatible with `Network.create(fetchFn, ...)`.
28
28
  */
29
29
  export declare const createFetchFunction: (config: any) => (request: RequestParameters, variables: Variables, cacheConfig: CacheConfig, uploadables: UploadableMap) => Observable<unknown>;
@@ -1,19 +1,19 @@
1
1
  /**
2
- * @fileoverview Implementação de `fetch` com retries e timeout, usada
3
- * internamente por `fetchQuery` no `setupRelayEnvironment`.
2
+ * @fileoverview `fetch` implementation with retries and timeout, used
3
+ * internally by `fetchQuery` in `setupRelayEnvironment`.
4
4
  *
5
- * Adiciona em cima do `fetch` nativo:
6
- * - timeout por requisição (`AbortController`);
7
- * - retry com delays configuráveis (`retries` no config) quando o
8
- * status HTTP está em `retryWhen` ou houve timeout;
9
- * - debug logs opcionais via `useDebug`.
5
+ * Adds on top of the native `fetch`:
6
+ * - per-request timeout (`AbortController`);
7
+ * - retry with configurable delays (`retries` in the config) when the
8
+ * HTTP status is in `retryWhen` or a timeout occurred;
9
+ * - optional debug logs via `useDebug`.
10
10
  *
11
- * Não exposto pelo barrel raiz implementação interna de
11
+ * Not exposed by the root barrel — internal implementation of
12
12
  * `CreateRelayEnvironment`.
13
13
  */
14
14
  /**
15
- * Subconjunto de `RequestInit` aceito por `fetchWithRetries`. Mantemos
16
- * apenas os campos efetivamente repassados ao `fetch` nativo.
15
+ * Subset of `RequestInit` accepted by `fetchWithRetries`. We keep
16
+ * only the fields actually forwarded to the native `fetch`.
17
17
  */
18
18
  export type InitWithRetries = {
19
19
  body?: BodyInit | null;
@@ -24,18 +24,18 @@ export type InitWithRetries = {
24
24
  mode?: RequestMode;
25
25
  };
26
26
  /**
27
- * Cria uma função `fetch` configurada com timeout e retries.
27
+ * Creates a `fetch` function configured with timeout and retries.
28
28
  *
29
- * Comportamento:
30
- * - Cada tentativa tem timeout de `config.timeout` ms (via `AbortController`).
31
- * - Se houver timeout ou o status estiver em `config.retryWhen`, agenda
32
- * a próxima tentativa com o delay correspondente em `config.retries`.
33
- * - Retries ocorrem quando DOM disponível e `config.useRetries`
34
- * é `true` — no SSR a primeira tentativa é a única.
35
- * - Erros não relacionados a `AbortError` são rejeitados imediatamente.
29
+ * Behavior:
30
+ * - Each attempt has a timeout of `config.timeout` ms (via `AbortController`).
31
+ * - On timeout, or when the status is in `config.retryWhen`, it schedules
32
+ * the next attempt with the corresponding delay in `config.retries`.
33
+ * - Retries only happen when a DOM is available and `config.useRetries`
34
+ * is `true` — in SSR the first attempt is the only one.
35
+ * - Errors unrelated to `AbortError` are rejected immediately.
36
36
  *
37
- * @param config - Configuração do environment (timeout, retries,
37
+ * @param config - Environment configuration (timeout, retries,
38
38
  * retryWhen, useRetries, useDebug, url).
39
- * @returns Função que recebe `RequestInit` e retorna `Promise<Response>`.
39
+ * @returns Function that takes a `RequestInit` and returns a `Promise<Response>`.
40
40
  */
41
41
  export declare function fetchWithRetries(config: any): (init?: InitWithRetries | null) => Promise<any>;