@pixelume/sdk 0.2.0 → 0.4.0

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.
Files changed (43) hide show
  1. package/CHANGELOG.md +62 -1
  2. package/README.md +113 -22
  3. package/dist/contracts/index.d.ts +42 -2
  4. package/dist/contracts/index.js +107 -8
  5. package/dist/contracts/index.js.map +1 -1
  6. package/dist/core/PixelumeClient.d.ts +12 -2
  7. package/dist/core/PixelumeClient.js +16 -2
  8. package/dist/core/PixelumeClient.js.map +1 -1
  9. package/dist/core/config.d.ts +2 -1
  10. package/dist/core/config.js +8 -1
  11. package/dist/core/config.js.map +1 -1
  12. package/dist/core/errors.d.ts +44 -2
  13. package/dist/core/errors.js +30 -0
  14. package/dist/core/errors.js.map +1 -1
  15. package/dist/core/types.d.ts +12 -0
  16. package/dist/core/types.js.map +1 -1
  17. package/dist/http/HttpClient.js +1 -0
  18. package/dist/http/HttpClient.js.map +1 -1
  19. package/dist/index.d.ts +5 -3
  20. package/dist/index.js +1 -1
  21. package/dist/index.js.map +1 -1
  22. package/dist/modules/auth/AuthModule.d.ts +28 -3
  23. package/dist/modules/auth/AuthModule.js +82 -40
  24. package/dist/modules/auth/AuthModule.js.map +1 -1
  25. package/dist/modules/auth/SessionManager.d.ts +91 -0
  26. package/dist/modules/auth/SessionManager.js +475 -0
  27. package/dist/modules/auth/SessionManager.js.map +1 -0
  28. package/dist/modules/saves/SavesModule.d.ts +100 -0
  29. package/dist/modules/saves/SavesModule.js +238 -0
  30. package/dist/modules/saves/SavesModule.js.map +1 -0
  31. package/dist/ui/index.d.ts +2 -0
  32. package/dist/ui/index.js +2 -0
  33. package/dist/ui/index.js.map +1 -0
  34. package/dist/ui/styles.d.ts +1 -0
  35. package/dist/ui/styles.js +402 -0
  36. package/dist/ui/styles.js.map +1 -0
  37. package/dist/ui/widget.d.ts +29 -0
  38. package/dist/ui/widget.js +435 -0
  39. package/dist/ui/widget.js.map +1 -0
  40. package/dist/version.d.ts +1 -1
  41. package/dist/version.js +1 -1
  42. package/dist/version.js.map +1 -1
  43. package/package.json +7 -2
package/CHANGELOG.md CHANGED
@@ -7,6 +7,65 @@ conter mudanças incompatíveis, sempre listadas em **Changed/Removed**.
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [0.4.0] - 2026-10-14
11
+
12
+ ### Added
13
+
14
+ - Renovação automática de sessão com os refresh tokens rotativos da Pixelume API: renovação proativa
15
+ (`expires_in − 60 s`, com jitter), verificação ao retomar a aba (`visibilitychange`, `pageshow`,
16
+ `online`), single-flight por instância, uma renovação + um único retry após `401`, retry único após
17
+ falha de rede/5xx, backoff para `429`/offline sem logout e encerramento explícito em `invalid_grant`
18
+ (`session_expired`) ou `invalid_client` (`game_unavailable`). Tokens permanecem só em memória.
19
+ - `pixelume.auth.session`, `auth.subscribeSession()` e `auth.refresh()` para interfaces próprias
20
+ (escopos, expiração, renovação em andamento e falha transitória, sem expor tokens).
21
+ - `pixelume.saves` (Cloud Saves): `list()`, `load()`, `save()` e `delete()` sobre
22
+ `/v1/games/:gameId/saves`, com validação local de slot/versão/revisão/JSON, `PixelumeSaveConflictError`
23
+ (`409`, com `current` e `expectedRevision`), exclusão idempotente (`'deleted' | 'not_found'`) e
24
+ atividade observável (`saves.activity`, `saves.subscribe()`) sem dados do save.
25
+ - Opção `scope` (`'profile' | 'profile saves'`) no cliente e em `auth.login()`; a restauração após
26
+ reload reutiliza o escopo concedido.
27
+ - `PixelumeClient.destroy()` para liberar timers e listeners.
28
+ - `PixelumeHttpError.details` com os detalhes não sensíveis do envelope de erro da API
29
+ (`oauthError`, `quota`, metadados de conflito).
30
+ - Widget: aviso de conexão durante falhas transitórias de renovação, mensagem para jogo indisponível e
31
+ status da nuvem somente após `saves.save()`/`saves.delete()` explícitos.
32
+ - Exemplo Vite com status da sessão, painel de Cloud Saves e modo `?headless`.
33
+
34
+ ### Changed
35
+
36
+ - `auth.logout()` revoga o refresh token (`token_type_hint=refresh_token`, com `client_id`), encerrando
37
+ toda a autorização do jogo; sem refresh token, revoga o access token como antes.
38
+ - `auth.getPlayer()` renova a sessão em vez de declará-la expirada quando o access token vence ou a API
39
+ responde `401`; quando a sessão realmente termina, o estado `anonymous/expired` agora traz
40
+ `PixelumeAuthError` explícito em `error` (antes `null`).
41
+ - O parser do token aceita `scope` `profile saves` e os campos opcionais `refresh_token` e
42
+ `refresh_token_expires_in`.
43
+ - Uniões públicas ampliadas (aditivo, mas afeta `switch` exaustivo): `PixelumeAuthErrorReason` ganhou
44
+ `not_authenticated`, `session_expired`, `game_unavailable` e `renewal_rejected`;
45
+ `PixelumeApiErrorCode` ganhou os códigos de Cloud Saves e `OAUTH_UNSUPPORTED_GRANT_TYPE`.
46
+ - A interface `PixelumeAuthApi` ganhou `session`, `subscribeSession()` e `refresh()`; implementações
47
+ próprias dessa interface (mocks) precisam acrescentá-los.
48
+ - O marcador não sensível em `sessionStorage` passou a guardar o escopo concedido (`profile` ou
49
+ `profile saves`); o valor antigo `1` continua aceito.
50
+
51
+ ## [0.3.0] - 2026-10-13
52
+
53
+ ### Added
54
+
55
+ - Entry point opt-in `@pixelume/sdk/ui` com `mountPixelumeWidget()`, Shadow DOM aberto e controlador
56
+ `hide()`, `show()` e `destroy()`.
57
+ - Widget oficial responsivo com estados de visitante, carregamento, autenticado e erro; login/logout
58
+ reutilizam exclusivamente `client.auth`.
59
+ - Posição, distância das bordas, container e `z-index` configuráveis, incluindo safe areas mobile.
60
+ - Navegação por teclado, Escape com devolução de foco, foco visível, região de status e isolamento de
61
+ eventos pointer/touch/teclado do jogo.
62
+ - Testes DOM do widget e validação dos dois entrypoints no consumidor empacotado.
63
+
64
+ ### Changed
65
+
66
+ - O exemplo Vite agora monta também o widget oficial, mantendo os controles headless para demonstrar os
67
+ dois modos de consumo.
68
+
10
69
  ## [0.2.0] - 2026-10-13
11
70
 
12
71
  ### Added
@@ -47,7 +106,9 @@ conter mudanças incompatíveis, sempre listadas em **Changed/Removed**.
47
106
  `invalid_response`) e `isPixelumeError()`.
48
107
  - Build ESM + `.d.ts`, CI e workflow de publicação via npm Trusted Publishing.
49
108
 
50
- [Unreleased]: https://github.com/ericksonnascimento/pixelume-sdk/compare/v0.2.0...HEAD
109
+ [Unreleased]: https://github.com/ericksonnascimento/pixelume-sdk/compare/v0.4.0...HEAD
110
+ [0.4.0]: https://github.com/ericksonnascimento/pixelume-sdk/compare/v0.3.0...v0.4.0
111
+ [0.3.0]: https://github.com/ericksonnascimento/pixelume-sdk/compare/v0.2.0...v0.3.0
51
112
  [0.2.0]: https://github.com/ericksonnascimento/pixelume-sdk/compare/v0.1.1...v0.2.0
52
113
  [0.1.1]: https://github.com/ericksonnascimento/pixelume-sdk/compare/v0.1.0...v0.1.1
53
114
  [0.1.0]: https://github.com/ericksonnascimento/pixelume-sdk/releases/tag/v0.1.0
package/README.md CHANGED
@@ -1,8 +1,10 @@
1
1
  # @pixelume/sdk
2
2
 
3
- SDK TypeScript headless para jogos web da Pixelume. A versão 0.2 adiciona autenticação centralizada
4
- com OAuth 2.0 Authorization Code + PKCE S256, além do cliente HTTP e health check da Fase 1. Não há
5
- dependências de runtime, componentes visuais, senha no jogo nem `client_secret`.
3
+ SDK TypeScript para jogos web da Pixelume. O core headless continua sendo o padrão e há um widget
4
+ oficial opt-in em `@pixelume/sdk/ui`. Os dois modos usam a mesma autenticação centralizada com OAuth 2.0
5
+ Authorization Code + PKCE S256. A versão 0.4 adiciona **renovação automática de sessão** (refresh tokens
6
+ rotativos, só em memória) e **Cloud Saves** (`pixelume.saves`). Não há dependências de runtime, senha
7
+ no jogo nem `client_secret`.
6
8
 
7
9
  ## Instalação
8
10
 
@@ -18,14 +20,16 @@ CommonJS, use `await import('@pixelume/sdk')`.
18
20
  Antes de integrar um jogo, registre na Pixelume API:
19
21
 
20
22
  - um `client_id` público, normalmente igual ao `gameId`;
21
- - o escopo `profile`;
22
- - cada callback completo por igualdade exata de scheme, host, porta, path e query.
23
+ - os escopos: `profile` (obrigatório) e `saves` (somente se o jogo usar Cloud Saves);
24
+ - cada callback completo por igualdade exata de scheme, host, porta, path e query, e as origens do jogo.
23
25
 
24
26
  Não são aceitos curingas, prefixos ou callbacks enviados dinamicamente. O cliente local já cadastrado é
25
27
  `pixelume-local-dev`, exclusivamente com `http://localhost:4173/oauth/callback` e
26
- `http://127.0.0.1:4173/oauth/callback`. Jogos publicados exigem migration/configuração revisada na API.
28
+ `http://127.0.0.1:4173/oauth/callback`, apenas com `profile`. Jogos são cadastrados pelo Game Registry
29
+ da API (`npm run admin:games` no repositório `pixelume-api`; veja `docs/GAME_REGISTRY.md` de lá). Em
30
+ 14/10/2026 nenhum cliente público tinha `saves` habilitado em produção.
27
31
 
28
- ## Uso
32
+ ## Uso headless
29
33
 
30
34
  ```ts
31
35
  import { Pixelume, isPixelumeError } from '@pixelume/sdk';
@@ -53,17 +57,89 @@ loginButton.addEventListener('click', () => {
53
57
 
54
58
  logoutButton.addEventListener('click', async () => {
55
59
  try {
56
- await pixelume.auth.logout(); // revoga somente o token deste jogo
60
+ await pixelume.auth.logout(); // revoga somente a autorização deste jogo
57
61
  } catch (error) {
58
62
  if (!isPixelumeError(error)) throw error;
59
63
  showRecoverableError(error.kind);
60
64
  }
61
65
  });
62
66
 
63
- // Ao desmontar a tela:
67
+ // Ao desmontar a tela/jogo:
64
68
  unsubscribe();
69
+ pixelume.destroy(); // cancela timers de renovação e listeners (não revoga)
65
70
  ```
66
71
 
72
+ ### Sessões longas
73
+
74
+ Nada a fazer: o SDK renova o access token (10 min) antes de expirar, ao retomar a aba e após um `401`,
75
+ com uma única renovação por vez e um único retry da requisição. Falhas de rede mantêm o jogador
76
+ conectado (`pixelume.auth.session.error`); sessão revogada/expirada vira `anonymous/expired` com erro
77
+ explícito. Detalhes: [renovação de sessão](docs/SESSION_RENEWAL.md).
78
+
79
+ ```ts
80
+ pixelume.auth.subscribeSession((session) => {
81
+ connectionBanner.hidden = session.error === null; // recuperável, sem logout
82
+ });
83
+ ```
84
+
85
+ ## Cloud Saves
86
+
87
+ ```ts
88
+ const pixelume = new Pixelume({ gameId: 'rail-puzzle', scope: 'profile saves' });
89
+ await pixelume.initialize();
90
+
91
+ const current = await pixelume.saves.load<{ level: number }>('main'); // ou null
92
+ await pixelume.saves.save('main', {
93
+ schemaVersion: 1,
94
+ expectedRevision: current?.revision ?? 0, // 0 cria; n atualiza só a revisão n
95
+ data: { level: 12 },
96
+ });
97
+ const { saves, limits, usage } = await pixelume.saves.list();
98
+ await pixelume.saves.delete('old-slot', { expectedRevision: 3 }); // 'deleted' | 'not_found'
99
+ ```
100
+
101
+ Conflitos (`409`) rejeitam com `PixelumeSaveConflictError` (revisão remota em `error.current`); o SDK
102
+ nunca sobrescreve, mescla ou reenvia sozinho, e não há fila offline. Saves são dados pessoais não
103
+ verificados: não servem como prova de conquista, ranking ou prêmio. Guia completo:
104
+ [Cloud Saves](docs/CLOUD_SAVES.md).
105
+
106
+ Importar ou instanciar o core não cria elementos, não injeta estilos e não ativa UI. O health check
107
+ também é totalmente independente: chamar `/health` nunca monta o widget.
108
+
109
+ ## Widget opcional
110
+
111
+ ```ts
112
+ import { Pixelume } from '@pixelume/sdk';
113
+ import { mountPixelumeWidget } from '@pixelume/sdk/ui';
114
+
115
+ const pixelume = new Pixelume({
116
+ gameId: 'rail-puzzle',
117
+ redirectUri: 'https://rail-puzzle.pixelume.com.br/oauth/callback',
118
+ });
119
+
120
+ await pixelume.initialize();
121
+
122
+ const widget = mountPixelumeWidget(pixelume, {
123
+ position: 'bottom-right',
124
+ offset: 16,
125
+ theme: 'pixel',
126
+ });
127
+
128
+ // Ao esconder controles, pausar ou trocar de tela:
129
+ widget.hide();
130
+ widget.show();
131
+
132
+ // Ao encerrar a tela/jogo:
133
+ widget.destroy();
134
+ ```
135
+
136
+ O painel usa Shadow DOM aberto, não aplica CSS global e chama somente `pixelume.auth.login()` e
137
+ `pixelume.auth.logout()`. Entrar sempre redireciona ao portal Pixelume Auth; o widget não exibe campos de
138
+ e-mail ou senha. Para overlays próprios ou canvas fullscreen, passe `container`, ajuste `position`,
139
+ `offset` e `zIndex`. Veja o [guia completo do widget](docs/phase-03-widget.md). O widget também mostra
140
+ avisos de conexão durante a renovação e, apenas depois de `saves.save()`/`saves.delete()` explícitos, o
141
+ status da nuvem.
142
+
67
143
  `pixelume.auth.state.status` é `uninitialized`, `redirecting`, `exchanging`, `anonymous` ou
68
144
  `authenticated`. O estado anônimo informa `reason` (`visitor`, `cancelled`, `expired`, `logged_out` ou
69
145
  `error`) e, em falha, um `PixelumeError`. Cancelar no portal resulta em visitante, não em exceção.
@@ -71,14 +147,17 @@ unsubscribe();
71
147
  ### Visitante, recarga e expiração
72
148
 
73
149
  - Sem login ou callback, `initialize()` termina como visitante e não faz requisição.
74
- - O access token opaco dura 10 minutos e fica **somente em memória**.
150
+ - O access token opaco dura 10 minutos e é renovado automaticamente pelo refresh token rotativo; os dois
151
+ ficam **somente em memória**.
75
152
  - Após autenticar, o SDK guarda em `sessionStorage` apenas o marcador não secreto de que aquela aba
76
- tinha uma sessão. Em uma recarga, inicia uma nova autorização; enquanto a sessão central da API
77
- continuar válida, o portal retorna sem pedir senha. `restoreSession: false` desliga esse comportamento.
153
+ tinha uma sessão (e o escopo concedido). Em uma recarga, inicia uma nova autorização com o mesmo
154
+ escopo; enquanto a sessão central da API continuar válida, o portal retorna sem pedir senha.
155
+ `restoreSession: false` desliga esse comportamento.
78
156
  - PKCE `state`/`code_verifier` ficam na sessão por no máximo 10 minutos e são removidos antes da troca.
79
157
  - Código expirado/repetido, `state` divergente, callback adulterado e 401 deixam o jogo utilizável como
80
158
  visitante. O jogo pode oferecer o login novamente.
81
- - `logout()` limpa o estado local imediatamente e chama `/v1/oauth/revoke`. A sessão central do portal
159
+ - `logout()` limpa o estado local imediatamente, cancela a renovação e revoga o refresh token em
160
+ `/v1/oauth/revoke` (o que encerra todos os tokens daquela autorização). A sessão central do portal
82
161
  continua existente por desenho; entrar novamente pode ser imediato.
83
162
 
84
163
  ## Configuração
@@ -90,6 +169,7 @@ unsubscribe();
90
169
  | `gameId` | — | slug público do jogo; também é o `clientId` padrão |
91
170
  | `clientId` | `gameId` | identificador OAuth público cadastrado; nunca é credencial |
92
171
  | `redirectUri` | `<origin>/oauth/callback` no browser | deve coincidir exatamente com o cadastro e não pode conter fragmento nem parâmetros OAuth |
172
+ | `scope` | `profile` | `profile saves` para Cloud Saves (o cadastro do jogo precisa permitir `saves`) |
93
173
  | `restoreSession` | `true` | reautoriza após reload da mesma aba sem persistir token |
94
174
  | `timeoutMs` | `10000` | cobre resposta e leitura do corpo |
95
175
  | `credentials` | `omit` | política dos módulos genéricos; Auth força `omit` para token/userinfo/revoke |
@@ -114,16 +194,20 @@ uma ferramenta de teste, não UI oficial.
114
194
 
115
195
  ## Segurança e confiança
116
196
 
117
- - O fluxo não é OIDC: não há ID Token, discovery, refresh token nem `client_secret`.
197
+ - O fluxo não é OIDC: não há ID Token, discovery nem `client_secret`. O refresh token é rotativo, de uso
198
+ único, ligado ao jogo e à sessão central, e fica só em memória.
118
199
  - A sessão central é cookie `HttpOnly`, `Secure`, `SameSite=Lax` e host-only da API. O jogo nunca a lê.
119
200
  - Requests OAuth do jogo usam Bearer curto e `credentials: 'omit'`; `credentials: 'include'` pertence
120
201
  apenas ao portal ao consultar/concluir a sessão central.
121
202
  - `crypto.getRandomValues` e Web Crypto SHA-256 geram `state`, verifier e challenge; não há
122
203
  `Math.random`.
123
- - Access token, código e verifier não são registrados. Tokens não vão para `localStorage`, cookies ou URL.
204
+ - Access/refresh token, código e verifier não são registrados. Tokens não vão para `localStorage`,
205
+ `sessionStorage`, cookies, URL, estado observável ou mensagens de erro.
124
206
  - CORS/Origin não são considerados autenticação. PKCE, URI exata, state e vínculos persistidos pela API
125
207
  são os controles de segurança.
126
208
  - XSS ainda pode ler um token que esteja em memória; jogos devem manter CSP e dependências sob controle.
209
+ - Cloud Saves sempre passam pela autorização do backend (token do próprio jogo + escopo `saves`); o SDK
210
+ nunca envia `playerId`, e a UI nunca prova legitimidade de progresso.
127
211
 
128
212
  ## Erros
129
213
 
@@ -132,8 +216,11 @@ Todo erro lançado diretamente pelo SDK é `PixelumeError`. Os `kind` estáveis
132
216
  o modo visitante; consulte `pixelume.auth.state.error`. Métodos chamados explicitamente (`login`,
133
217
  `getPlayer`, `logout`) rejeitam normalmente.
134
218
 
135
- O SDK não faz retry automático. Para 400/401/403/429/5xx, use `PixelumeHttpError.status`, `code` e
136
- `requestId`; para cancelamento do chamador, use `AbortSignal`.
219
+ O único retry automático é o da renovação de sessão: após `401` em uma rota autenticada, o SDK renova uma
220
+ vez e repete aquela requisição uma vez. Nada mais é repetido. Para 400/403/409/413/429/5xx, use
221
+ `PixelumeHttpError.status`, `code`, `details` e `requestId`; conflitos de save são
222
+ `PixelumeSaveConflictError`; sessões encerradas são `PixelumeAuthError` (`session_expired`,
223
+ `game_unavailable`, `renewal_rejected`, `not_authenticated`). Para cancelamento, use `AbortSignal`.
137
224
 
138
225
  ## Health check
139
226
 
@@ -146,10 +233,12 @@ local, mas não diretamente de outro domínio no browser.
146
233
 
147
234
  ## Compatibilidade
148
235
 
149
- | SDK | Pixelume API | Pixelume Auth | Recursos |
150
- | ------- | ---------------------------------------------------- | ------------------------------ | -------------------------------- |
151
- | `0.2.x` | OpenAPI `0.4.0`, release SSO `3846479` ou compatível | Fase 2 `dd5a8e5` ou compatível | SSO PKCE, perfil, logout, health |
152
- | `0.1.x` | API anterior/atual para `/health` | não consumido | fundação e health apenas |
236
+ | SDK | Pixelume API | Pixelume Auth | Recursos |
237
+ | ------- | ---------------------------------------------------- | ------------------------------ | ----------------------------------------------- |
238
+ | `0.4.x` | OpenAPI `0.6.0`, release `10752b8` ou compatível | Fase 2 `3a1ded4` ou compatível | Renovação de sessão, Cloud Saves, widget, SSO |
239
+ | `0.3.x` | OpenAPI `0.4.0`, release SSO `3846479` ou compatível | Fase 2 `3a1ded4` ou compatível | Widget opt-in, SSO PKCE, perfil, logout, health |
240
+ | `0.2.x` | OpenAPI `0.4.0`, release SSO `3846479` ou compatível | Fase 2 `3a1ded4` ou compatível | SSO PKCE, perfil, logout, health |
241
+ | `0.1.x` | API anterior/atual para `/health` | não consumido | fundação e health apenas |
153
242
 
154
243
  Como o pacote ainda está em `0.x`, mudanças incompatíveis usam incremento _minor_ e são listadas no
155
244
  [CHANGELOG](CHANGELOG.md).
@@ -164,7 +253,9 @@ npm run verify
164
253
  npm run example:smoke # leitura opcional da API real
165
254
  ```
166
255
 
167
- Mais detalhes: [integração SSO](docs/SSO_INTEGRATION.md),
256
+ Mais detalhes: [renovação de sessão](docs/SESSION_RENEWAL.md), [Cloud Saves](docs/CLOUD_SAVES.md),
257
+ [auditoria da Fase 4](docs/PHASE_04_CONTRACT_AUDIT.md), [widget oficial](docs/phase-03-widget.md),
258
+ [integração SSO](docs/SSO_INTEGRATION.md),
168
259
  [auditoria do contrato](docs/SSO_CONTRACT_AUDIT.md), [arquitetura](docs/architecture.md) e
169
260
  [publicação](docs/publishing.md).
170
261
 
@@ -25,11 +25,17 @@ export interface PlayerEnvelopeWire {
25
25
  player: PlayerWire;
26
26
  }
27
27
  export declare const parsePlayerEnvelope: BodyParser<PlayerEnvelopeWire>;
28
+ /** Scopes the API can grant. `profile` is always present; `saves` is opt-in per game. */
29
+ export type OAuthScopeWire = 'profile' | 'saves';
28
30
  export interface OAuthTokenResponseWire {
29
31
  access_token: string;
30
32
  token_type: 'Bearer';
31
33
  expires_in: number;
32
- scope: 'profile';
34
+ /** Granted scopes, parsed from the space-separated `scope` field. */
35
+ scopes: readonly OAuthScopeWire[];
36
+ /** Rotating refresh token; absent for legacy codes or when the central session already ended. */
37
+ refresh_token?: string;
38
+ refresh_token_expires_in?: number;
33
39
  }
34
40
  export declare const parseOAuthTokenResponse: BodyParser<OAuthTokenResponseWire>;
35
41
  export declare const parseEmptyResponse: BodyParser<void>;
@@ -40,13 +46,47 @@ export interface HealthResponseWire {
40
46
  release?: string;
41
47
  }
42
48
  export declare const parseHealthResponse: BodyParser<HealthResponseWire>;
43
- /** Error envelope returned by every API error: `{ error: { code, message, requestId } }`. */
49
+ /** Error envelope returned by every API error: `{ error: { code, message, requestId, details? } }`. */
44
50
  export interface ErrorEnvelopeWire {
45
51
  error: {
46
52
  code: string;
47
53
  message: string;
48
54
  requestId: string;
55
+ details: Readonly<Record<string, unknown>> | null;
49
56
  };
50
57
  }
51
58
  /** Returns the envelope when `body` matches it, `null` otherwise (e.g. an HTML 502 from a proxy). */
52
59
  export declare function parseErrorEnvelope(body: unknown): ErrorEnvelopeWire | null;
60
+ export interface SaveMetadataWire {
61
+ gameId: string;
62
+ slotId: string;
63
+ schemaVersion: number;
64
+ revision: number;
65
+ sizeBytes: number;
66
+ createdAt: string;
67
+ updatedAt: string;
68
+ }
69
+ export interface CloudSaveWire extends SaveMetadataWire {
70
+ data: Record<string, unknown>;
71
+ }
72
+ export interface SaveListWire {
73
+ gameId: string;
74
+ saves: SaveMetadataWire[];
75
+ limits: {
76
+ maxSlotsPerGame: number;
77
+ maxDataBytes: number;
78
+ maxBytesPerPlayer: number;
79
+ };
80
+ usage: {
81
+ slots: number;
82
+ playerBytes: number;
83
+ };
84
+ }
85
+ /** Validates one `SaveMetadata` object; `null` when it does not match. */
86
+ export declare function parseSaveMetadata(value: unknown): SaveMetadataWire | null;
87
+ /** `PUT` → `{ save: SaveMetadata }`. */
88
+ export declare const parseSaveMetadataEnvelope: BodyParser<SaveMetadataWire>;
89
+ /** `GET /saves/:slotId` → `{ save: SaveMetadata & { data } }`. */
90
+ export declare const parseCloudSaveEnvelope: BodyParser<CloudSaveWire>;
91
+ /** `GET /saves` → `{ gameId, saves, limits, usage }`. */
92
+ export declare const parseSaveList: BodyParser<SaveListWire>;
@@ -27,11 +27,12 @@ export const parsePlayerEnvelope = (body) => {
27
27
  }
28
28
  return ok({ player: { id, displayName, avatarUrl } });
29
29
  };
30
+ const TOKEN_PATTERN = /^[A-Za-z0-9_-]{43,128}$/u;
31
+ const KNOWN_SCOPES = ['profile', 'saves'];
30
32
  export const parseOAuthTokenResponse = (body) => {
31
33
  if (!isRecord(body))
32
34
  return fail('expected a JSON object');
33
- if (typeof body.access_token !== 'string' ||
34
- !/^[A-Za-z0-9_-]{43,128}$/u.test(body.access_token)) {
35
+ if (typeof body.access_token !== 'string' || !TOKEN_PATTERN.test(body.access_token)) {
35
36
  return fail('expected "access_token" to be a base64url token');
36
37
  }
37
38
  if (body.token_type !== 'Bearer')
@@ -39,13 +40,34 @@ export const parseOAuthTokenResponse = (body) => {
39
40
  if (!Number.isInteger(body.expires_in) || body.expires_in <= 0) {
40
41
  return fail('expected "expires_in" to be a positive integer');
41
42
  }
42
- if (body.scope !== 'profile')
43
- return fail('expected "scope" to be "profile"');
44
- return ok({
43
+ const scopes = typeof body.scope === 'string' ? body.scope.split(' ') : [];
44
+ if (!scopes.includes('profile') ||
45
+ new Set(scopes).size !== scopes.length ||
46
+ !scopes.every((scope) => KNOWN_SCOPES.includes(scope))) {
47
+ return fail('expected "scope" to be "profile" or "profile saves"');
48
+ }
49
+ const result = {
45
50
  access_token: body.access_token,
46
51
  token_type: 'Bearer',
47
52
  expires_in: body.expires_in,
48
- scope: 'profile',
53
+ scopes: scopes,
54
+ };
55
+ if (body.refresh_token === undefined)
56
+ return ok(result);
57
+ if (typeof body.refresh_token !== 'string' || !TOKEN_PATTERN.test(body.refresh_token)) {
58
+ return fail('expected "refresh_token" to be a base64url token when present');
59
+ }
60
+ const refreshExpiresIn = body.refresh_token_expires_in;
61
+ if (refreshExpiresIn !== undefined &&
62
+ (!Number.isInteger(refreshExpiresIn) || refreshExpiresIn < 0)) {
63
+ return fail('expected "refresh_token_expires_in" to be a non-negative integer when present');
64
+ }
65
+ return ok({
66
+ ...result,
67
+ refresh_token: body.refresh_token,
68
+ ...(refreshExpiresIn === undefined
69
+ ? {}
70
+ : { refresh_token_expires_in: refreshExpiresIn }),
49
71
  });
50
72
  };
51
73
  export const parseEmptyResponse = (body) => body === undefined ? ok(undefined) : fail('expected an empty response body');
@@ -69,10 +91,87 @@ export const parseHealthResponse = (body) => {
69
91
  export function parseErrorEnvelope(body) {
70
92
  if (!isRecord(body) || !isRecord(body.error))
71
93
  return null;
72
- const { code, message, requestId } = body.error;
94
+ const { code, message, requestId, details } = body.error;
73
95
  if (typeof code !== 'string' || typeof message !== 'string' || typeof requestId !== 'string') {
74
96
  return null;
75
97
  }
76
- return { error: { code, message, requestId } };
98
+ return { error: { code, message, requestId, details: isRecord(details) ? details : null } };
99
+ }
100
+ function isNonNegativeInteger(value) {
101
+ return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0;
102
+ }
103
+ function isTimestamp(value) {
104
+ return typeof value === 'string' && !Number.isNaN(Date.parse(value));
105
+ }
106
+ /** Validates one `SaveMetadata` object; `null` when it does not match. */
107
+ export function parseSaveMetadata(value) {
108
+ if (!isRecord(value))
109
+ return null;
110
+ const { gameId, slotId, schemaVersion, revision, sizeBytes, createdAt, updatedAt } = value;
111
+ if (typeof gameId !== 'string' ||
112
+ typeof slotId !== 'string' ||
113
+ !isNonNegativeInteger(schemaVersion) ||
114
+ schemaVersion < 1 ||
115
+ !isNonNegativeInteger(revision) ||
116
+ revision < 1 ||
117
+ !isNonNegativeInteger(sizeBytes) ||
118
+ !isTimestamp(createdAt) ||
119
+ !isTimestamp(updatedAt)) {
120
+ return null;
121
+ }
122
+ return { gameId, slotId, schemaVersion, revision, sizeBytes, createdAt, updatedAt };
77
123
  }
124
+ /** `PUT` → `{ save: SaveMetadata }`. */
125
+ export const parseSaveMetadataEnvelope = (body) => {
126
+ const save = isRecord(body) ? parseSaveMetadata(body.save) : null;
127
+ return save ? ok(save) : fail('expected a JSON object containing "save" metadata');
128
+ };
129
+ /** `GET /saves/:slotId` → `{ save: SaveMetadata & { data } }`. */
130
+ export const parseCloudSaveEnvelope = (body) => {
131
+ if (!isRecord(body) || !isRecord(body.save)) {
132
+ return fail('expected a JSON object containing "save"');
133
+ }
134
+ const metadata = parseSaveMetadata(body.save);
135
+ if (!metadata)
136
+ return fail('expected "save" to contain valid save metadata');
137
+ const data = body.save.data;
138
+ if (!isRecord(data))
139
+ return fail('expected "save.data" to be a JSON object');
140
+ return ok({ ...metadata, data });
141
+ };
142
+ /** `GET /saves` → `{ gameId, saves, limits, usage }`. */
143
+ export const parseSaveList = (body) => {
144
+ if (!isRecord(body) || typeof body.gameId !== 'string' || !Array.isArray(body.saves)) {
145
+ return fail('expected a JSON object containing "gameId" and "saves"');
146
+ }
147
+ const saves = [];
148
+ for (const entry of body.saves) {
149
+ const save = parseSaveMetadata(entry);
150
+ if (!save)
151
+ return fail('expected every entry of "saves" to be save metadata');
152
+ saves.push(save);
153
+ }
154
+ const { limits, usage } = body;
155
+ if (!isRecord(limits) ||
156
+ !isNonNegativeInteger(limits.maxSlotsPerGame) ||
157
+ !isNonNegativeInteger(limits.maxDataBytes) ||
158
+ !isNonNegativeInteger(limits.maxBytesPerPlayer)) {
159
+ return fail('expected "limits" to contain non-negative integers');
160
+ }
161
+ if (!isRecord(usage) ||
162
+ !isNonNegativeInteger(usage.slots) ||
163
+ !isNonNegativeInteger(usage.playerBytes)) {
164
+ return fail('expected "usage" to contain non-negative integers');
165
+ }
166
+ return ok({
167
+ gameId: body.gameId,
168
+ saves,
169
+ limits: {
170
+ maxSlotsPerGame: limits.maxSlotsPerGame,
171
+ maxDataBytes: limits.maxDataBytes,
172
+ maxBytesPerPlayer: limits.maxBytesPerPlayer,
173
+ },
174
+ usage: { slots: usage.slots, playerBytes: usage.playerBytes },
175
+ });
176
+ };
78
177
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/contracts/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAOH,MAAM,EAAE,GAAG,CAAI,KAAQ,EAAkB,EAAE,CAAC,CAAC,EAAE,EAAE,EAAE,IAAI,EAAE,KAAK,EAAE,CAAC,CAAC;AAClE,MAAM,IAAI,GAAG,CAAC,MAAc,EAAs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CAAC;QACnE,OAAO,IAAI,CAAC,gDAAgD,CAAC,CAAC;IAChE,CAAC;IACD,OAAO,EAAE,CAAC;QACR,MAAM,EAAE,IAAI;QACZ,YAAY,EAAE,IAAI,CAAC,YAAY;QAC/B,GAAG,CAAC,IAAI,CAAC,OAAO,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,OAAO,EAAE,IAAI,CAAC,OAAO,EAAE,CAAC;KACjE,CAAC,CAAC;AACL,CAAC,CAAC;AAOF,qGAAqG;AACrG,MAAM,UAAU,kBAAkB,CAAC,IAAa;IAC9C,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,KAAK,CAAC;QAAE,OAAO,IAAI,CAAC;IAC1D,MAAM,EAAE,IAAI,EAAE,OAAO,EAAE,SAAS,EAAE,GAAG,IAAI,CAAC,KAAK,CAAC;IAChD,IAAI,OAAO,IAAI,KAAK,QAAQ,IAAI,OAAO,OAAO,KAAK,QAAQ,IAAI,OAAO,SAAS,KAAK,QAAQ,EAAE,CAAC;QAC7F,OAAO,IAAI,CAAC;IACd,CAAC;IACD,OAAO,EAAE,KAAK,EAAE,EAAE,IAAI,EAAE,OAAO,EAAE,SAAS,EAAE,EAAE,CAAC;AACjD,CAAC","sourcesContent":["/**\n * Wire contracts of the Pixelume API used by the SDK, with hand-written runtime guards.\n *\n * Source of truth: `pixelume-api` (`docs/openapi.yaml` and `src/interfaces/http/app.ts`).\n * See `docs/api-contract-audit.md`. These types describe JSON on the wire and are internal;\n * public modules map them to SDK types so the API can evolve without breaking consumers.\n *\n * Validation is intentionally tolerant to *additive* changes (unknown fields are ignored,\n * unknown enum values are accepted as strings) and strict about the fields the SDK relies on.\n */\n\nexport type ParseResult<T> =\n { readonly ok: true; readonly value: T } | { readonly ok: false; readonly reason: string };\n\nexport type BodyParser<T> = (body: unknown) => ParseResult<T>;\n\nconst ok = <T>(value: T): ParseResult<T> => ({ ok: true, value });\nconst fail = (reason: string): ParseResult<never> => ({ ok: false, reason });\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nexport interface PlayerWire {\n id: string;\n displayName: string;\n avatarUrl: string | null;\n}\n\nexport interface PlayerEnvelopeWire {\n player: PlayerWire;\n}\n\nexport const parsePlayerEnvelope: BodyParser<PlayerEnvelopeWire> = (body) => {\n if (!isRecord(body) || !isRecord(body.player)) {\n return fail('expected a JSON object containing \"player\"');\n }\n const { id, displayName, avatarUrl } = body.player;\n if (typeof id !== 'string' || id.length === 0) return fail('expected \"player.id\" to be a string');\n if (typeof displayName !== 'string') return fail('expected \"player.displayName\" to be a string');\n if (avatarUrl !== null && typeof avatarUrl !== 'string') {\n return fail('expected \"player.avatarUrl\" to be a string or null');\n }\n return ok({ player: { id, displayName, avatarUrl } });\n};\n\nexport interface OAuthTokenResponseWire {\n access_token: string;\n token_type: 'Bearer';\n expires_in: number;\n scope: 'profile';\n}\n\nexport const parseOAuthTokenResponse: BodyParser<OAuthTokenResponseWire> = (body) => {\n if (!isRecord(body)) return fail('expected a JSON object');\n if (\n typeof body.access_token !== 'string' ||\n !/^[A-Za-z0-9_-]{43,128}$/u.test(body.access_token)\n ) {\n return fail('expected \"access_token\" to be a base64url token');\n }\n if (body.token_type !== 'Bearer') return fail('expected \"token_type\" to be \"Bearer\"');\n if (!Number.isInteger(body.expires_in) || (body.expires_in as number) <= 0) {\n return fail('expected \"expires_in\" to be a positive integer');\n }\n if (body.scope !== 'profile') return fail('expected \"scope\" to be \"profile\"');\n return ok({\n access_token: body.access_token,\n token_type: 'Bearer',\n expires_in: body.expires_in as number,\n scope: 'profile',\n });\n};\n\nexport const parseEmptyResponse: BodyParser<void> = (body) =>\n body === undefined ? ok(undefined) : fail('expected an empty response body');\n\n/** `GET /health` → 200. OpenAPI: `{ status: 'ok', registration: enum, release?: /^[a-f0-9]{7,40}$/ }`. */\nexport interface HealthResponseWire {\n status: 'ok';\n registration: string;\n release?: string;\n}\n\nexport const parseHealthResponse: BodyParser<HealthResponseWire> = (body) => {\n if (!isRecord(body)) return fail('expected a JSON object');\n if (body.status !== 'ok') return fail('expected \"status\" to be \"ok\"');\n if (typeof body.registration !== 'string') return fail('expected \"registration\" to be a string');\n if (body.release !== undefined && typeof body.release !== 'string') {\n return fail('expected \"release\" to be a string when present');\n }\n return ok({\n status: 'ok',\n registration: body.registration,\n ...(body.release === undefined ? {} : { release: body.release }),\n });\n};\n\n/** Error envelope returned by every API error: `{ error: { code, message, requestId } }`. */\nexport interface ErrorEnvelopeWire {\n error: { code: string; message: string; requestId: string };\n}\n\n/** Returns the envelope when `body` matches it, `null` otherwise (e.g. an HTML 502 from a proxy). */\nexport function parseErrorEnvelope(body: unknown): ErrorEnvelopeWire | null {\n if (!isRecord(body) || !isRecord(body.error)) return null;\n const { code, message, requestId } = body.error;\n if (typeof code !== 'string' || typeof message !== 'string' || typeof requestId !== 'string') {\n return null;\n }\n return { error: { code, message, requestId } };\n}\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/contracts/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAOH,MAAM,EAAE,GAAG,CAAI,KAAQ,EAAkB,EAAE,CAAC,CAAC,EAAE,EAAE,EAAE,IAAI,EAAE,KAAK,EAAE,CAAC,CAAC;AAClE,MAAM,IAAI,GAAG,CAAC,MAAc,EAAsB,EAAE,CAAC,CAAC,EAAE,EAAE,EAAE,KAAK,EAAE,MAAM,EAAE,CAAC,CAAC;AAE7E,SAAS,QAAQ,CAAC,KAAc;IAC9B,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;AAC9E,CAAC;AAYD,MAAM,CAAC,MAAM,mBAAmB,GAAmC,CAAC,IAAI,EAAE,EAAE;IAC1E,IAAI,CAAC,QAAQ,CAAC,IAAI,C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,EAAE,IAAI,CAAC,MAAM;QACnB,KAAK;QACL,MAAM,EAAE;YACN,eAAe,EAAE,MAAM,CAAC,eAAe;YACvC,YAAY,EAAE,MAAM,CAAC,YAAY;YACjC,iBAAiB,EAAE,MAAM,CAAC,iBAAiB;SAC5C;QACD,KAAK,EAAE,EAAE,KAAK,EAAE,KAAK,CAAC,KAAK,EAAE,WAAW,EAAE,KAAK,CAAC,WAAW,EAAE;KAC9D,CAAC,CAAC;AACL,CAAC,CAAC","sourcesContent":["/**\n * Wire contracts of the Pixelume API used by the SDK, with hand-written runtime guards.\n *\n * Source of truth: `pixelume-api` (`docs/openapi.yaml` and `src/interfaces/http/app.ts`).\n * See `docs/api-contract-audit.md`. These types describe JSON on the wire and are internal;\n * public modules map them to SDK types so the API can evolve without breaking consumers.\n *\n * Validation is intentionally tolerant to *additive* changes (unknown fields are ignored,\n * unknown enum values are accepted as strings) and strict about the fields the SDK relies on.\n */\n\nexport type ParseResult<T> =\n { readonly ok: true; readonly value: T } | { readonly ok: false; readonly reason: string };\n\nexport type BodyParser<T> = (body: unknown) => ParseResult<T>;\n\nconst ok = <T>(value: T): ParseResult<T> => ({ ok: true, value });\nconst fail = (reason: string): ParseResult<never> => ({ ok: false, reason });\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nexport interface PlayerWire {\n id: string;\n displayName: string;\n avatarUrl: string | null;\n}\n\nexport interface PlayerEnvelopeWire {\n player: PlayerWire;\n}\n\nexport const parsePlayerEnvelope: BodyParser<PlayerEnvelopeWire> = (body) => {\n if (!isRecord(body) || !isRecord(body.player)) {\n return fail('expected a JSON object containing \"player\"');\n }\n const { id, displayName, avatarUrl } = body.player;\n if (typeof id !== 'string' || id.length === 0) return fail('expected \"player.id\" to be a string');\n if (typeof displayName !== 'string') return fail('expected \"player.displayName\" to be a string');\n if (avatarUrl !== null && typeof avatarUrl !== 'string') {\n return fail('expected \"player.avatarUrl\" to be a string or null');\n }\n return ok({ player: { id, displayName, avatarUrl } });\n};\n\n/** Scopes the API can grant. `profile` is always present; `saves` is opt-in per game. */\nexport type OAuthScopeWire = 'profile' | 'saves';\n\nexport interface OAuthTokenResponseWire {\n access_token: string;\n token_type: 'Bearer';\n expires_in: number;\n /** Granted scopes, parsed from the space-separated `scope` field. */\n scopes: readonly OAuthScopeWire[];\n /** Rotating refresh token; absent for legacy codes or when the central session already ended. */\n refresh_token?: string;\n refresh_token_expires_in?: number;\n}\n\nconst TOKEN_PATTERN = /^[A-Za-z0-9_-]{43,128}$/u;\nconst KNOWN_SCOPES: readonly string[] = ['profile', 'saves'];\n\nexport const parseOAuthTokenResponse: BodyParser<OAuthTokenResponseWire> = (body) => {\n if (!isRecord(body)) return fail('expected a JSON object');\n if (typeof body.access_token !== 'string' || !TOKEN_PATTERN.test(body.access_token)) {\n return fail('expected \"access_token\" to be a base64url token');\n }\n if (body.token_type !== 'Bearer') return fail('expected \"token_type\" to be \"Bearer\"');\n if (!Number.isInteger(body.expires_in) || (body.expires_in as number) <= 0) {\n return fail('expected \"expires_in\" to be a positive integer');\n }\n const scopes = typeof body.scope === 'string' ? body.scope.split(' ') : [];\n if (\n !scopes.includes('profile') ||\n new Set(scopes).size !== scopes.length ||\n !scopes.every((scope) => KNOWN_SCOPES.includes(scope))\n ) {\n return fail('expected \"scope\" to be \"profile\" or \"profile saves\"');\n }\n const result: OAuthTokenResponseWire = {\n access_token: body.access_token,\n token_type: 'Bearer',\n expires_in: body.expires_in as number,\n scopes: scopes as OAuthScopeWire[],\n };\n if (body.refresh_token === undefined) return ok(result);\n if (typeof body.refresh_token !== 'string' || !TOKEN_PATTERN.test(body.refresh_token)) {\n return fail('expected \"refresh_token\" to be a base64url token when present');\n }\n const refreshExpiresIn = body.refresh_token_expires_in;\n if (\n refreshExpiresIn !== undefined &&\n (!Number.isInteger(refreshExpiresIn) || (refreshExpiresIn as number) < 0)\n ) {\n return fail('expected \"refresh_token_expires_in\" to be a non-negative integer when present');\n }\n return ok({\n ...result,\n refresh_token: body.refresh_token,\n ...(refreshExpiresIn === undefined\n ? {}\n : { refresh_token_expires_in: refreshExpiresIn as number }),\n });\n};\n\nexport const parseEmptyResponse: BodyParser<void> = (body) =>\n body === undefined ? ok(undefined) : fail('expected an empty response body');\n\n/** `GET /health` → 200. OpenAPI: `{ status: 'ok', registration: enum, release?: /^[a-f0-9]{7,40}$/ }`. */\nexport interface HealthResponseWire {\n status: 'ok';\n registration: string;\n release?: string;\n}\n\nexport const parseHealthResponse: BodyParser<HealthResponseWire> = (body) => {\n if (!isRecord(body)) return fail('expected a JSON object');\n if (body.status !== 'ok') return fail('expected \"status\" to be \"ok\"');\n if (typeof body.registration !== 'string') return fail('expected \"registration\" to be a string');\n if (body.release !== undefined && typeof body.release !== 'string') {\n return fail('expected \"release\" to be a string when present');\n }\n return ok({\n status: 'ok',\n registration: body.registration,\n ...(body.release === undefined ? {} : { release: body.release }),\n });\n};\n\n/** Error envelope returned by every API error: `{ error: { code, message, requestId, details? } }`. */\nexport interface ErrorEnvelopeWire {\n error: {\n code: string;\n message: string;\n requestId: string;\n details: Readonly<Record<string, unknown>> | null;\n };\n}\n\n/** Returns the envelope when `body` matches it, `null` otherwise (e.g. an HTML 502 from a proxy). */\nexport function parseErrorEnvelope(body: unknown): ErrorEnvelopeWire | null {\n if (!isRecord(body) || !isRecord(body.error)) return null;\n const { code, message, requestId, details } = body.error;\n if (typeof code !== 'string' || typeof message !== 'string' || typeof requestId !== 'string') {\n return null;\n }\n return { error: { code, message, requestId, details: isRecord(details) ? details : null } };\n}\n\n// ---------------------------------------------------------------------------------------------\n// Cloud Saves (`/v1/games/:gameId/saves`). OpenAPI: SaveMetadata, CloudSave, SaveListResponse.\n// ---------------------------------------------------------------------------------------------\n\nexport interface SaveMetadataWire {\n gameId: string;\n slotId: string;\n schemaVersion: number;\n revision: number;\n sizeBytes: number;\n createdAt: string;\n updatedAt: string;\n}\n\nexport interface CloudSaveWire extends SaveMetadataWire {\n data: Record<string, unknown>;\n}\n\nexport interface SaveListWire {\n gameId: string;\n saves: SaveMetadataWire[];\n limits: { maxSlotsPerGame: number; maxDataBytes: number; maxBytesPerPlayer: number };\n usage: { slots: number; playerBytes: number };\n}\n\nfunction isNonNegativeInteger(value: unknown): value is number {\n return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0;\n}\n\nfunction isTimestamp(value: unknown): value is string {\n return typeof value === 'string' && !Number.isNaN(Date.parse(value));\n}\n\n/** Validates one `SaveMetadata` object; `null` when it does not match. */\nexport function parseSaveMetadata(value: unknown): SaveMetadataWire | null {\n if (!isRecord(value)) return null;\n const { gameId, slotId, schemaVersion, revision, sizeBytes, createdAt, updatedAt } = value;\n if (\n typeof gameId !== 'string' ||\n typeof slotId !== 'string' ||\n !isNonNegativeInteger(schemaVersion) ||\n schemaVersion < 1 ||\n !isNonNegativeInteger(revision) ||\n revision < 1 ||\n !isNonNegativeInteger(sizeBytes) ||\n !isTimestamp(createdAt) ||\n !isTimestamp(updatedAt)\n ) {\n return null;\n }\n return { gameId, slotId, schemaVersion, revision, sizeBytes, createdAt, updatedAt };\n}\n\n/** `PUT` → `{ save: SaveMetadata }`. */\nexport const parseSaveMetadataEnvelope: BodyParser<SaveMetadataWire> = (body) => {\n const save = isRecord(body) ? parseSaveMetadata(body.save) : null;\n return save ? ok(save) : fail('expected a JSON object containing \"save\" metadata');\n};\n\n/** `GET /saves/:slotId` → `{ save: SaveMetadata & { data } }`. */\nexport const parseCloudSaveEnvelope: BodyParser<CloudSaveWire> = (body) => {\n if (!isRecord(body) || !isRecord(body.save)) {\n return fail('expected a JSON object containing \"save\"');\n }\n const metadata = parseSaveMetadata(body.save);\n if (!metadata) return fail('expected \"save\" to contain valid save metadata');\n const data = body.save.data;\n if (!isRecord(data)) return fail('expected \"save.data\" to be a JSON object');\n return ok({ ...metadata, data });\n};\n\n/** `GET /saves` → `{ gameId, saves, limits, usage }`. */\nexport const parseSaveList: BodyParser<SaveListWire> = (body) => {\n if (!isRecord(body) || typeof body.gameId !== 'string' || !Array.isArray(body.saves)) {\n return fail('expected a JSON object containing \"gameId\" and \"saves\"');\n }\n const saves: SaveMetadataWire[] = [];\n for (const entry of body.saves) {\n const save = parseSaveMetadata(entry);\n if (!save) return fail('expected every entry of \"saves\" to be save metadata');\n saves.push(save);\n }\n const { limits, usage } = body;\n if (\n !isRecord(limits) ||\n !isNonNegativeInteger(limits.maxSlotsPerGame) ||\n !isNonNegativeInteger(limits.maxDataBytes) ||\n !isNonNegativeInteger(limits.maxBytesPerPlayer)\n ) {\n return fail('expected \"limits\" to contain non-negative integers');\n }\n if (\n !isRecord(usage) ||\n !isNonNegativeInteger(usage.slots) ||\n !isNonNegativeInteger(usage.playerBytes)\n ) {\n return fail('expected \"usage\" to contain non-negative integers');\n }\n return ok({\n gameId: body.gameId,\n saves,\n limits: {\n maxSlotsPerGame: limits.maxSlotsPerGame,\n maxDataBytes: limits.maxDataBytes,\n maxBytesPerPlayer: limits.maxBytesPerPlayer,\n },\n usage: { slots: usage.slots, playerBytes: usage.playerBytes },\n });\n};\n"]}
@@ -1,5 +1,6 @@
1
1
  import { type PixelumeAuthApi, type PixelumeAuthState } from '../modules/auth/AuthModule.js';
2
2
  import { type PixelumeHealthApi } from '../modules/health/HealthModule.js';
3
+ import { type PixelumeSavesApi } from '../modules/saves/SavesModule.js';
3
4
  import type { PixelumeClientConfig, PixelumeClientOptions } from './types.js';
4
5
  /**
5
6
  * Entry point of the SDK. Create one instance per API/game and share it.
@@ -9,8 +10,9 @@ import type { PixelumeClientConfig, PixelumeClientOptions } from './types.js';
9
10
  * const health = await pixelume.health.check();
10
11
  * ```
11
12
  *
12
- * Feature modules are exposed as read-only properties. Phase 1 ships only `health`; future modules
13
- * (authentication, saves…) will be added as new properties without changing existing ones.
13
+ * Feature modules are exposed as read-only properties: `health`, `auth` and `saves`. New modules are
14
+ * added as new properties without changing existing ones. Nothing touches the DOM; the visual
15
+ * widget lives in the opt-in `@pixelume/sdk/ui` entry point.
14
16
  *
15
17
  * @throws {PixelumeConfigError} when the options are invalid.
16
18
  */
@@ -19,12 +21,20 @@ export declare class PixelumeClient {
19
21
  readonly config: PixelumeClientConfig;
20
22
  readonly health: PixelumeHealthApi;
21
23
  readonly auth: PixelumeAuthApi;
24
+ /** Cloud Saves of the signed-in player for `gameId` (requires the `saves` scope). */
25
+ readonly saves: PixelumeSavesApi;
22
26
  constructor(options?: PixelumeClientOptions);
23
27
  /**
24
28
  * Initializes browser authentication once. Callback failures become an anonymous state so a
25
29
  * game can always continue as a visitor; inspect `pixelume.auth.state.error` for diagnostics.
26
30
  */
27
31
  initialize(): Promise<PixelumeAuthState>;
32
+ /**
33
+ * Stops renewal timers and resume listeners and drops credentials from memory, without
34
+ * contacting the API. Call it when the game is torn down (SPA route change, hot reload); call
35
+ * `auth.logout()` first to also revoke the authorization. The client is unusable afterwards.
36
+ */
37
+ destroy(): void;
28
38
  }
29
39
  /** Concise alias for new integrations; `PixelumeClient` remains supported. */
30
40
  export { PixelumeClient as Pixelume };