@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.
@@ -4,22 +4,22 @@ declare const kMountEnvironment: unique symbol;
4
4
  declare const kFeetchHandler: unique symbol;
5
5
  declare const kSubscriptionHandler: unique symbol;
6
6
  /**
7
- * Fábrica de `Environment` Relay com bateria inclusa: autenticação JWT,
8
- * retries com backoff, suporte a subscriptions via WebSocket, cache de
9
- * respostas e estratégia plugável de storage (localStorage ou cookie).
7
+ * Batteries-included Relay `Environment` factory: JWT authentication,
8
+ * retries with backoff, subscription support via WebSocket, response
9
+ * caching and a pluggable storage strategy (localStorage or cookie).
10
10
  *
11
- * Esta classe encapsula a configuração que normalmente precisaria ser
12
- * escrita à mão para cada projeto que usa Relay: criar `Network`,
13
- * `RecordSource`, `Store`, configurar `fetch` com retries/timeout,
14
- * adicionar headers de autenticação, lidar com redirecionamento em caso
15
- * de sessão expirada e opcionalmente registrar um handler de
16
- * subscriptions GraphQL.
11
+ * This class encapsulates the configuration that would normally have to be
12
+ * written by hand for every project using Relay: creating `Network`,
13
+ * `RecordSource`, `Store`, configuring `fetch` with retries/timeout,
14
+ * adding authentication headers, handling redirection when the
15
+ * session expires and optionally registering a GraphQL
16
+ * subscriptions handler.
17
17
  *
18
- * A instância exposta possui a propriedade pública `Environment`, que é
19
- * o objeto que deve ser passado para `react-relay` (via `RelayEnvironmentProvider`
20
- * ou `QueryRenderer`).
18
+ * The exposed instance has the public `Environment` property, which is
19
+ * the object that must be passed to `react-relay` (via `RelayEnvironmentProvider`
20
+ * or `QueryRenderer`).
21
21
  *
22
- * @example Setup mínimo
22
+ * @example Minimal setup
23
23
  * ```ts
24
24
  * import { CreateRelayEnvironment } from '@apollion-dsi/relay';
25
25
  *
@@ -28,7 +28,7 @@ declare const kSubscriptionHandler: unique symbol;
28
28
  * });
29
29
  * ```
30
30
  *
31
- * @example Com auth JWT (Bearer) e retries
31
+ * @example With JWT (Bearer) auth and retries
32
32
  * ```ts
33
33
  * const { Environment } = new CreateRelayEnvironment({
34
34
  * url: 'https://api.example.com/graphql/',
@@ -39,12 +39,12 @@ declare const kSubscriptionHandler: unique symbol;
39
39
  * });
40
40
  * ```
41
41
  *
42
- * @example Com sessão por cookie httpOnly (modelo seguro p/ SPA)
42
+ * @example With httpOnly cookie session (secure model for SPAs)
43
43
  * ```ts
44
- * // O token de sessão fica num cookie httpOnly + SameSite (invisível ao
45
- * // JS, imune a XSS). Nada é lido do storage e nenhum Bearer é injetado;
46
- * // `credentials:'include'` faz o browser anexar o cookie sozinho. Em
47
- * // erro de auth (401) o refresh é disparado contra `authUrl`.
44
+ * // The session token lives in an httpOnly + SameSite cookie (invisible to
45
+ * // JS, immune to XSS). Nothing is read from storage and no Bearer is injected;
46
+ * // `credentials:'include'` makes the browser attach the cookie on its own. On
47
+ * // an auth error (401) the refresh is dispatched against `authUrl`.
48
48
  * const { Environment } = new CreateRelayEnvironment({
49
49
  * url: 'https://api.example.com/graphql/',
50
50
  * authUrl: 'https://api.example.com/auth/refresh/',
@@ -54,7 +54,7 @@ declare const kSubscriptionHandler: unique symbol;
54
54
  * });
55
55
  * ```
56
56
  *
57
- * @example Com subscriptions
57
+ * @example With subscriptions
58
58
  * ```ts
59
59
  * const { Environment } = new CreateRelayEnvironment({
60
60
  * url: 'https://api.example.com/graphql/',
@@ -63,86 +63,86 @@ declare const kSubscriptionHandler: unique symbol;
63
63
  * });
64
64
  * ```
65
65
  *
66
- * @see {@link RelayArgsInterface} para a lista completa de opções de configuração.
66
+ * @see {@link RelayArgsInterface} for the complete list of configuration options.
67
67
  */
68
68
  export default class RelayEnvironment implements RelayArgsInterface {
69
- /** Endpoint HTTP do servidor GraphQL. Obrigatório. */
69
+ /** HTTP endpoint of the GraphQL server. Required. */
70
70
  url: string;
71
- /** Endpoint do servidor de autenticação. Obrigatório quando `useAuthorization` é `true`. */
71
+ /** Authentication server endpoint. Required when `useAuthorization` is `true`. */
72
72
  authUrl?: string;
73
- /** Endpoint WebSocket para subscriptions. Obrigatório quando `useSubscription` é `true`. */
73
+ /** WebSocket endpoint for subscriptions. Required when `useSubscription` is `true`. */
74
74
  socket?: string;
75
- /** Lista de delays (ms) entre tentativas, quando `useRetries` é `true`. */
75
+ /** List of delays (ms) between attempts, when `useRetries` is `true`. */
76
76
  retries?: number[];
77
- /** Timeout (ms) por requisição. */
77
+ /** Per-request timeout (ms). */
78
78
  timeout?: number;
79
- /** Habilita subscriptions GraphQL via WebSocket. */
79
+ /** Enables GraphQL subscriptions over WebSocket. */
80
80
  useSubscription?: boolean;
81
- /** Habilita injeção do header `Authorization: Bearer <token>` em cada request. */
81
+ /** Enables injecting the `Authorization: Bearer <token>` header on every request. */
82
82
  useAuthorization?: boolean;
83
- /** Modelo de auth: `'bearer'` (token JS + header) ou `'cookie'` (httpOnly). */
83
+ /** Auth model: `'bearer'` (JS token + header) or `'cookie'` (httpOnly). */
84
84
  authMode: 'bearer' | 'cookie';
85
- /** Valor de `credentials` repassado aos fetches GraphQL/refresh. */
85
+ /** `credentials` value forwarded to the GraphQL/refresh fetches. */
86
86
  credentials?: RequestCredentials;
87
- /** URL de verificação/refresh de sessão; `false` desliga o probe. */
87
+ /** Session verification/refresh URL; `false` disables the probe. */
88
88
  sessionCheckUrl?: string | false;
89
- /** Habilita cache de respostas (via `QueryResponseCache` do Relay). */
89
+ /** Enables response caching (via Relay's `QueryResponseCache`). */
90
90
  useCache?: boolean;
91
- /** TTL (ms) das entradas do cache. */
91
+ /** TTL (ms) of the cache entries. */
92
92
  cacheTime?: number;
93
- /** Tamanho máximo do cache (número de queries). */
93
+ /** Maximum cache size (number of queries). */
94
94
  cacheSize?: number;
95
- /** Nome da chave em storage usada para guardar o token de sessão. */
95
+ /** Storage key name used to hold the session token. */
96
96
  sessionStorageProp?: string;
97
- /** Nome da chave em storage usada para guardar o refresh token. */
97
+ /** Storage key name used to hold the refresh token. */
98
98
  refreshStorageProp?: string;
99
- /** Rota usada para redirecionar o usuário em caso de sessão expirada. */
99
+ /** Route used to redirect the user when the session expires. */
100
100
  loginRoute?: string;
101
- /** Liga logs de debug (útil em desenvolvimento). */
101
+ /** Turns on debug logs (useful in development). */
102
102
  useDebug?: boolean;
103
- /** Habilita o mecanismo de retries em caso de erro/timeout. */
103
+ /** Enables the retry mechanism on error/timeout. */
104
104
  useRetries?: boolean;
105
- /** Redireciona automaticamente para `loginRoute` em caso de erro de auth. */
105
+ /** Automatically redirects to `loginRoute` on an auth error. */
106
106
  redirectOnError?: boolean;
107
- /** Lista de status HTTP que disparam retry (quando `useRetries` é `true`). */
107
+ /** List of HTTP statuses that trigger a retry (when `useRetries` is `true`). */
108
108
  retryWhen?: number[];
109
- /** Status HTTP considerados como erros de autenticação (default: 401, 403). */
109
+ /** HTTP statuses treated as authentication errors (default: 401, 403). */
110
110
  authenticationErrors?: number[];
111
- /** Estratégia de storage no browser. */
111
+ /** Browser storage strategy. */
112
112
  storageType: 'cookie' | 'localStorage';
113
- /** Identificador opcional do parceiro, enviado no header `X-Partner`. */
113
+ /** Optional partner identifier, sent in the `X-Partner` header. */
114
114
  partner?: string;
115
115
  /**
116
- * Função de fetch montada para uso pelo `Network` do Relay. Interno.
116
+ * Fetch function assembled for use by Relay's `Network`. Internal.
117
117
  */
118
118
  private [kFeetchHandler]?;
119
119
  /**
120
- * Função de subscription montada para uso pelo `Network` do Relay. Interno.
120
+ * Subscription function assembled for use by Relay's `Network`. Internal.
121
121
  */
122
122
  private [kSubscriptionHandler]?;
123
123
  /**
124
- * Handler de storage. Expõe métodos `getTokens`, `setTokens`, `clear`,
125
- * `hasChangedSession`. Use diretamente quando precisar manipular tokens
126
- * fora do fluxo padrão (ex: tela de login).
124
+ * Storage handler. Exposes the `getTokens`, `setTokens`, `clear`,
125
+ * `hasChangedSession` methods. Use it directly when you need to manipulate
126
+ * tokens outside the standard flow (e.g. a login screen).
127
127
  */
128
128
  StorageHandler: any;
129
129
  /**
130
- * Instância de `Environment` do `relay-runtime` pronta para uso com
130
+ * `relay-runtime` `Environment` instance ready for use with
131
131
  * `RelayEnvironmentProvider` (`react-relay`).
132
132
  */
133
133
  Environment: Environment;
134
134
  /**
135
- * @param config - Configuração da instância. Veja {@link RelayArgsInterface}.
136
- * Apenas `url` é obrigatório; demais opções têm defaults sensatos.
135
+ * @param config - Instance configuration. See {@link RelayArgsInterface}.
136
+ * Only `url` is required; the other options have sensible defaults.
137
137
  *
138
- * @throws {Error} Se `url` não for informado.
139
- * @throws {Error} Se `useAuthorization` for `true` e `authUrl` não for informado.
140
- * @throws {Error} Se `useSubscription` for `true` e `socket` não for informado.
138
+ * @throws {Error} If `url` is not provided.
139
+ * @throws {Error} If `useAuthorization` is `true` and `authUrl` is not provided.
140
+ * @throws {Error} If `useSubscription` is `true` and `socket` is not provided.
141
141
  */
142
142
  constructor(config: RelayArgsInterface);
143
143
  /**
144
- * Monta o `Environment` Relay a partir da fetch function e subscription
145
- * handler configurados. Chamado uma única vez pelo construtor.
144
+ * Assembles the Relay `Environment` from the configured fetch function and
145
+ * subscription handler. Called exactly once by the constructor.
146
146
  */
147
147
  private [kMountEnvironment];
148
148
  }
@@ -1,98 +1,98 @@
1
1
  /**
2
- * @fileoverview Helpers internos usados por `setupRelayEnvironment` para
3
- * montar a Network do Relay: detecção do tipo de operação, construção do
4
- * body/headers da requisição, parse de respostas (incluindo
5
- * `multipart/mixed` para `@defer`/`@stream`), redirecionamento em erro
6
- * de auth e constantes de tempo.
2
+ * @fileoverview Internal helpers used by `setupRelayEnvironment` to
3
+ * assemble the Relay Network: operation-kind detection, request
4
+ * body/header construction, response parsing (including
5
+ * `multipart/mixed` for `@defer`/`@stream`), redirection on auth
6
+ * error and time constants.
7
7
  *
8
- * Não exposto pelo barrel raiz faz parte da implementação interna de
8
+ * Not exposed by the root barrel — part of the internal implementation of
9
9
  * `CreateRelayEnvironment`.
10
10
  */
11
11
  import { CacheConfig, RequestParameters, UploadableMap, Variables } from 'relay-runtime';
12
12
  import { RelayArgsInterface, Sink } from '../relayArgsInterface';
13
- /** Verdadeiro se a operação Relay é uma mutation. */
13
+ /** True if the Relay operation is a mutation. */
14
14
  export declare const isMutation: (request: RequestParameters) => boolean;
15
- /** Verdadeiro se a operação Relay é uma query. */
15
+ /** True if the Relay operation is a query. */
16
16
  export declare const isQuery: (request: RequestParameters) => boolean;
17
- /** Verdadeiro quando o consumidor pediu `force: true` no `CacheConfig` (bypass do cache). */
17
+ /** True when the consumer requested `force: true` in the `CacheConfig` (cache bypass). */
18
18
  export declare const forceFetch: (cacheConfig: CacheConfig) => boolean;
19
19
  /**
20
- * Retorna o delimitador (`?` ou `&`) apropriado para anexar query params
21
- * à URL atual do browser. Retorna string vazia em ambientes sem DOM (SSR).
20
+ * Returns the appropriate delimiter (`?` or `&`) for appending query params
21
+ * to the browser's current URL. Returns an empty string in DOM-less environments (SSR).
22
22
  */
23
23
  export declare const getParamsDelimiter: () => string;
24
24
  /**
25
- * Retorna o `pathname` atual do browser, ou string vazia em ambientes
26
- * sem DOM (SSR).
25
+ * Returns the browser's current `pathname`, or an empty string in
26
+ * DOM-less environments (SSR).
27
27
  */
28
28
  export declare const getBrowserLocation: () => string;
29
29
  /**
30
- * Redireciona o usuário para `redirectTo`, preservando a URL atual em
31
- * `?redirect=` (para o fluxo de login redirecionar de volta).
30
+ * Redirects the user to `redirectTo`, preserving the current URL in
31
+ * `?redirect=` (so the login flow can redirect back).
32
32
  *
33
- * Não adiciona o parâmetro `redirect` quando a URL atual é igual ao
34
- * destino ou quando o destino é a própria `loginRoute`.
33
+ * Does not add the `redirect` parameter when the current URL already equals
34
+ * the destination or when the destination is `loginRoute` itself.
35
35
  *
36
- * @param url - URL atual (origem do redirect).
37
- * @param redirectTo - Destino do redirect.
38
- * @param config - Configuração do environment (usada para checar `loginRoute`).
36
+ * @param url - Current URL (redirect origin).
37
+ * @param redirectTo - Redirect destination.
38
+ * @param config - Environment configuration (used to check `loginRoute`).
39
39
  */
40
40
  export declare const redirectUser: (url: string, redirectTo: string, config?: RelayArgsInterface) => void;
41
41
  /**
42
- * Constrói o body da requisição GraphQL — multipart se uploadables,
43
- * JSON caso contrário.
42
+ * Builds the GraphQL request body — multipart if there are uploadables,
43
+ * JSON otherwise.
44
44
  *
45
- * @param request - Parâmetros da requisição Relay.
46
- * @param variables - Variáveis da operação.
47
- * @param uploadables - Arquivos para upload (opcional).
45
+ * @param request - Relay request parameters.
46
+ * @param variables - Operation variables.
47
+ * @param uploadables - Files to upload (optional).
48
48
  */
49
49
  export declare function getRequestBody(request: RequestParameters, variables: Variables, uploadables?: UploadableMap): string | FormData;
50
50
  /**
51
- * Resolve o valor efetivo de `credentials` para os fetches (GraphQL e
52
- * verificação/refresh de sessão).
51
+ * Resolves the effective `credentials` value for the fetches (GraphQL and
52
+ * session verification/refresh).
53
53
  *
54
- * - Se `config.credentials` foi definido explicitamente, ele vence.
55
- * - Caso contrário, no modo `authMode:'cookie'` o default é `'include'`
56
- * (para o browser anexar cookies httpOnly de sessão).
57
- * - No modo `'bearer'` (default) retorna `undefined` — o fetch usa o
58
- * default do browser, preservando a retrocompat.
54
+ * - If `config.credentials` was set explicitly, it wins.
55
+ * - Otherwise, in `authMode:'cookie'` mode the default is `'include'`
56
+ * (so the browser attaches httpOnly session cookies).
57
+ * - In `'bearer'` mode (default) it returns `undefined` — the fetch uses the
58
+ * browser default, preserving backwards compatibility.
59
59
  *
60
- * @param config - Configuração do environment.
61
- * @returns O `RequestCredentials` a usar, ou `undefined` para omitir.
60
+ * @param config - Environment configuration.
61
+ * @returns The `RequestCredentials` to use, or `undefined` to omit.
62
62
  */
63
63
  export declare const resolveCredentials: (config: any) => RequestCredentials | undefined;
64
64
  /**
65
- * Monta os headers HTTP da requisição. Para uploads, usa `Accept: *\/*`
66
- * e deixa o browser definir o `Content-Type` com boundary. Para JSON,
67
- * usa `application/json` em ambos.
65
+ * Assembles the request's HTTP headers. For uploads, uses `Accept: *\/*`
66
+ * and lets the browser set the `Content-Type` with the boundary. For JSON,
67
+ * uses `application/json` for both.
68
68
  *
69
- * Modo `bearer` (default): quando `useAuthorization` está ligado e existe
70
- * um `sessionToken` em storage, anexa `Authorization: Bearer <token>` —
71
- * exceto quando o usuário está na própria rota de login (para evitar
69
+ * `bearer` mode (default): when `useAuthorization` is on and a
70
+ * `sessionToken` exists in storage, attaches `Authorization: Bearer <token>` —
71
+ * except when the user is on the login route itself (to avoid
72
72
  * loops).
73
73
  *
74
- * Modo `cookie` (httpOnly): **nunca** o token em JS nem injeta
75
- * `Authorization` — o cookie de sessão viaja sozinho via `credentials`.
76
- * Isso evita o header `Authorization: Bearer ` vazio que o modo bearer
77
- * produziria quando o token é httpOnly e portanto invisível ao JS.
74
+ * `cookie` mode (httpOnly): **never** reads the token in JS nor injects
75
+ * `Authorization` — the session cookie travels on its own via `credentials`.
76
+ * This avoids the empty `Authorization: Bearer ` header that bearer mode
77
+ * would produce when the token is httpOnly and therefore invisible to JS.
78
78
  *
79
- * Se um `partner` está configurado, adiciona o header `X-Partner`.
79
+ * If a `partner` is configured, adds the `X-Partner` header.
80
80
  */
81
81
  export declare const getHeaders: (args: any, uploadables?: UploadableMap) => HeadersInit;
82
82
  /**
83
- * o `Response` do fetch e empurra os dados para o `Sink` do Relay.
83
+ * Reads the fetch `Response` and pushes the data into the Relay `Sink`.
84
84
  *
85
- * Suporta três modos:
86
- * - `multipart/mixed` (usado por `@defer` e `@stream`): o stream
87
- * chunk a chunk e usa `PatchResolver` para repassar cada patch.
88
- * - `application/json`: parseia o JSON inteiro e chama `callback`.
89
- * - Outros: como texto e empurra como array de strings.
85
+ * Supports three modes:
86
+ * - `multipart/mixed` (used by `@defer` and `@stream`): reads the stream
87
+ * chunk by chunk and uses `PatchResolver` to forward each patch.
88
+ * - `application/json`: parses the whole JSON and calls `callback`.
89
+ * - Others: reads as text and pushes it as an array of strings.
90
90
  *
91
- * Copiado da biblioteca `fetch-multipart-graphql` com adaptações para o
92
- * `Sink` Relay.
91
+ * Copied from the `fetch-multipart-graphql` library with adaptations for the
92
+ * Relay `Sink`.
93
93
  */
94
94
  export declare const handleData: (response: Response, sink: Sink, callback: (data: any) => void) => void;
95
- /** Constante de tempo: 1 segundo em milissegundos. */
95
+ /** Time constant: 1 second in milliseconds. */
96
96
  export declare const ONE_SECOND = 1000;
97
- /** Constante de tempo: 1 minuto em milissegundos. */
97
+ /** Time constant: 1 minute in milliseconds. */
98
98
  export declare const ONE_MINUTE: number;
@@ -1,5 +1,5 @@
1
1
  import { RelayArgsInterface } from '../relayArgsInterface';
2
- /** Par de tokens armazenado. */
2
+ /** Stored token pair. */
3
3
  type TokenTypes = {
4
4
  sessionToken?: string;
5
5
  refreshToken?: string;
@@ -8,9 +8,9 @@ declare const kStorageHandler: unique symbol;
8
8
  declare const kPropSession: unique symbol;
9
9
  declare const kPropRefresh: unique symbol;
10
10
  /**
11
- * Handler de storage usado por `CreateRelayEnvironment`. Encapsula a
12
- * estratégia escolhida (`storageType`) e padroniza a manipulação de
13
- * `sessionToken` e `refreshToken` por trás de uma API estável.
11
+ * Storage handler used by `CreateRelayEnvironment`. Encapsulates the
12
+ * chosen strategy (`storageType`) and standardizes the handling of
13
+ * `sessionToken` and `refreshToken` behind a stable API.
14
14
  *
15
15
  * @example
16
16
  * ```ts
@@ -25,34 +25,34 @@ export default class StorageClass {
25
25
  private [kPropSession];
26
26
  private [kPropRefresh];
27
27
  /**
28
- * @param strategy - Instância de `CreateRelayEnvironment` (que
29
- * implementa `RelayArgsInterface`). Os campos lidos são
28
+ * @param strategy - `CreateRelayEnvironment` instance (which
29
+ * implements `RelayArgsInterface`). The fields read are
30
30
  * `storageType`, `sessionStorageProp`, `refreshStorageProp`.
31
31
  */
32
32
  constructor(strategy: RelayArgsInterface);
33
33
  /**
34
- * os tokens atualmente armazenados.
34
+ * Reads the currently stored tokens.
35
35
  *
36
- * @returns Objeto com `sessionToken` e `refreshToken` (podem ser
37
- * `undefined` quando ausentes).
36
+ * @returns Object with `sessionToken` and `refreshToken` (may be
37
+ * `undefined` when absent).
38
38
  */
39
39
  getTokens(): TokenTypes;
40
40
  /**
41
- * Grava ambos os tokens em storage. Use após receber resposta de
42
- * login/refresh.
41
+ * Writes both tokens to storage. Use after receiving a
42
+ * login/refresh response.
43
43
  */
44
44
  setTokens(tokens: TokenTypes): void;
45
45
  /**
46
- * Remove ambos os tokens do storage. Usado em logout ou ao detectar
47
- * sessão expirada.
46
+ * Removes both tokens from storage. Used on logout or when an
47
+ * expired session is detected.
48
48
  */
49
49
  clear(): void;
50
50
  /**
51
- * Compara um novo `sessionToken` com o atualmente armazenado.
51
+ * Compares a new `sessionToken` against the currently stored one.
52
52
  *
53
- * @param tokens - Objeto contendo o novo `sessionToken` (vindo, por
54
- * exemplo, de um header de resposta).
55
- * @returns `true` se o token mudou.
53
+ * @param tokens - Object containing the new `sessionToken` (coming, for
54
+ * example, from a response header).
55
+ * @returns `true` if the token changed.
56
56
  */
57
57
  hasChangedSession({ sessionToken: newSessionToken }: TokenTypes): boolean;
58
58
  }
@@ -1,28 +1,28 @@
1
1
  /**
2
- * @fileoverview Fábrica do subscription handler GraphQL via WebSocket,
3
- * usada por `setupRelayEnvironment` quando `useSubscription` está
4
- * habilitado.
2
+ * @fileoverview Factory for the GraphQL subscription handler over WebSocket,
3
+ * used by `setupRelayEnvironment` when `useSubscription` is
4
+ * enabled.
5
5
  *
6
- * Baseado em `graphql-ws` (protocolo `graphql-transport-ws`).
6
+ * Based on `graphql-ws` (`graphql-transport-ws` protocol).
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
  /**
12
- * Monta a subscription function para o `Network.create` do Relay.
12
+ * Builds the subscription function for Relay's `Network.create`.
13
13
  *
14
- * Retorna uma função (a ser chamada uma vez, no setup do Environment)
15
- * que por sua vez retorna a subscribe function que o Relay vai invocar
16
- * para cada subscription operation. A adaptação de callbacks
17
- * `next/error/complete` do `graphql-ws` para o `Sink` do Observable
18
- * Relay é feita aqui.
14
+ * Returns a function (to be called once, during Environment setup)
15
+ * which in turn returns the subscribe function that Relay will invoke
16
+ * for each subscription operation. The adaptation of `graphql-ws`
17
+ * `next/error/complete` callbacks to the Relay Observable `Sink`
18
+ * happens here.
19
19
  *
20
- * @param settings - Objeto com a URL do endpoint WebSocket (`socket`).
21
- * Quando `useSubscription` é `true` mas `socket` não foi configurado,
22
- * o construtor de `CreateRelayEnvironment` lança erro antes desta
23
- * função ser chamada.
24
- * @returns Função que, quando invocada, retorna a subscribe function
25
- * compatível com `Network.create(fetchFn, subscribeFn)`.
20
+ * @param settings - Object with the WebSocket endpoint URL (`socket`).
21
+ * When `useSubscription` is `true` but `socket` was not configured,
22
+ * the `CreateRelayEnvironment` constructor throws before this
23
+ * function is called.
24
+ * @returns Function that, when invoked, returns the subscribe function
25
+ * compatible with `Network.create(fetchFn, subscribeFn)`.
26
26
  */
27
27
  export declare function setupSubscription(settings: {
28
28
  socket?: string;
@@ -1,9 +1,9 @@
1
1
  /**
2
- * Barrel público do módulo `useEnvironment`.
2
+ * Public barrel for the `useEnvironment` module.
3
3
  *
4
- * Reexporta o hook `useEnvironment` e o componente `EnvironmentProvider`,
5
- * para que consumidores possam importar via
6
- * `@apollion-dsi/relay/useEnvironment` (granular) ou via
7
- * `@apollion-dsi/relay` (barrel raiz).
4
+ * Re-exports the `useEnvironment` hook and the `EnvironmentProvider`
5
+ * component, so consumers can import via
6
+ * `@apollion-dsi/relay/useEnvironment` (granular) or via
7
+ * `@apollion-dsi/relay` (root barrel).
8
8
  */
9
9
  export * from './useEnvironment';
@@ -2,24 +2,24 @@ import React from 'react';
2
2
  import { Environment } from 'relay-runtime';
3
3
  import { MockEnvironment } from 'relay-test-utils';
4
4
  /**
5
- * Estado interno do Context: contém apenas o `Environment` Relay
6
- * (real ou mockado em testes).
5
+ * Internal Context state: contains only the Relay `Environment`
6
+ * (real, or mocked in tests).
7
7
  */
8
8
  type StateType = {
9
9
  environment: Environment | MockEnvironment;
10
10
  };
11
11
  /**
12
- * Props do `EnvironmentProvider`.
12
+ * Props for `EnvironmentProvider`.
13
13
  */
14
14
  type EnvironmentProviderInterface = {
15
15
  children: React.ReactNode;
16
16
  } & StateType;
17
17
  /**
18
- * Provider que injeta o `Environment` Relay na árvore React via Context.
18
+ * Provider that injects the Relay `Environment` into the React tree via Context.
19
19
  *
20
- * Em produção, passe a propriedade `Environment` exposta por
21
- * `CreateRelayEnvironment`. Em testes, passe um `MockEnvironment` de
22
- * `relay-test-utils` para facilitar a substituição do backend.
20
+ * In production, pass the `Environment` property exposed by
21
+ * `CreateRelayEnvironment`. In tests, pass a `MockEnvironment` from
22
+ * `relay-test-utils` to make swapping out the backend easier.
23
23
  *
24
24
  * @example
25
25
  * ```tsx
@@ -36,7 +36,7 @@ type EnvironmentProviderInterface = {
36
36
  * }
37
37
  * ```
38
38
  *
39
- * @example Em testes
39
+ * @example In tests
40
40
  * ```tsx
41
41
  * import { createMockEnvironment } from 'relay-test-utils';
42
42
  *
@@ -50,16 +50,16 @@ type EnvironmentProviderInterface = {
50
50
  */
51
51
  declare function EnvironmentProvider({ children, environment }: EnvironmentProviderInterface): React.JSX.Element;
52
52
  /**
53
- * Hook para acessar o `Environment` Relay corrente.
53
+ * Hook to access the current Relay `Environment`.
54
54
  *
55
- * Deve ser usado dentro de um `EnvironmentProvider`. Lança erro
56
- * descritivo caso seja chamado fora dele ou se nenhum environment
57
- * tenha sido fornecido falhas silenciosas aqui geralmente viram
58
- * "loading infinito" no Relay, então preferimos falhar cedo.
55
+ * Must be used inside an `EnvironmentProvider`. Throws a descriptive
56
+ * error if called outside of it or if no environment was
57
+ * provided silent failures here usually turn into
58
+ * "infinite loading" in Relay, so we prefer to fail early.
59
59
  *
60
- * @returns Objeto com a propriedade `environment`.
61
- * @throws {Error} Quando usado fora de `EnvironmentProvider` ou quando
62
- * o environment fornecido é `null`/`undefined`.
60
+ * @returns Object with the `environment` property.
61
+ * @throws {Error} When used outside `EnvironmentProvider` or when
62
+ * the provided environment is `null`/`undefined`.
63
63
  *
64
64
  * @example
65
65
  * ```tsx
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@apollion-dsi/relay",
3
- "version": "0.27.2",
3
+ "version": "0.27.3",
4
4
  "description": "Frontend services regarding Relay Environment",
5
5
  "main": "lib/index.js",
6
6
  "module": "lib/index.esm.js",
@@ -10,8 +10,6 @@
10
10
  ],
11
11
  "license": "MIT",
12
12
  "scripts": {
13
- "prepare": "yarn build",
14
- "pretest": "relay-compiler",
15
13
  "audit-dependencies": "yarn npm audit --severity moderate --no-deprecations",
16
14
  "coverage": "jest --coverage",
17
15
  "lint": "eslint src --quiet",
@@ -21,10 +19,11 @@
21
19
  "prettier": "prettier --check **/*.{ts,tsx} --ignore-path .gitignore --no-error-on-unmatched-pattern",
22
20
  "format": "yarn prettier --write",
23
21
  "validate": "./scripts/validate.sh",
24
- "validate:tests": "jest --coverage",
22
+ "validate:tests": "relay-compiler && jest --coverage",
25
23
  "build": "node -e \"require('fs').rmSync('./lib',{recursive:true,force:true})\" && node ./esbuild && tsc --emitDeclarationOnly",
26
24
  "test": "yarn validate",
27
- "code:check": "yarn lint && yarn coverage"
25
+ "code:check": "yarn lint && yarn coverage",
26
+ "prepack": "node ../../scripts/release-preflight.js && yarn build"
28
27
  },
29
28
  "peerDependencies": {
30
29
  "react": "^19.0.0"
@@ -40,7 +39,7 @@
40
39
  "relay-test-utils": "^21.0.0"
41
40
  },
42
41
  "devDependencies": {
43
- "@apollion-dsi/eslint-config": "0.9.0",
42
+ "@apollion-dsi/eslint-config": "0.9.1",
44
43
  "@babel/core": "7.29.0",
45
44
  "@babel/plugin-transform-class-properties": "7.27.1",
46
45
  "@babel/plugin-transform-runtime": "7.29.0",