@groundbrick/sveltekit-adapter 0.7.1 → 0.9.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 (66) hide show
  1. package/README.md +213 -507
  2. package/dist/analytics/components/FacebookPixel.svelte +8 -27
  3. package/dist/analytics/components/GoogleAnalytics.svelte +12 -16
  4. package/dist/analytics/config/analytics.config.js +1 -1
  5. package/dist/analytics/config/analytics.config.js.map +1 -1
  6. package/dist/analytics/interfaces/IAnalyticsService.d.ts +13 -0
  7. package/dist/analytics/interfaces/IAnalyticsService.d.ts.map +1 -1
  8. package/dist/analytics/services/AnalyticsService.d.ts +15 -0
  9. package/dist/analytics/services/AnalyticsService.d.ts.map +1 -1
  10. package/dist/analytics/services/AnalyticsService.js +54 -9
  11. package/dist/analytics/services/AnalyticsService.js.map +1 -1
  12. package/dist/analytics/utils/consent.js +3 -3
  13. package/dist/analytics/utils/consent.js.map +1 -1
  14. package/dist/auth/index.d.ts.map +1 -1
  15. package/dist/auth/index.js +1 -5
  16. package/dist/auth/index.js.map +1 -1
  17. package/dist/client/ApiClient.d.ts.map +1 -1
  18. package/dist/client/ApiClient.js +4 -10
  19. package/dist/client/ApiClient.js.map +1 -1
  20. package/dist/client/apiWrapper.d.ts +31 -39
  21. package/dist/client/apiWrapper.d.ts.map +1 -1
  22. package/dist/client/apiWrapper.js +26 -27
  23. package/dist/client/apiWrapper.js.map +1 -1
  24. package/dist/client/authErrorHandler.js +1 -1
  25. package/dist/client/authErrorHandler.js.map +1 -1
  26. package/dist/client/hooks.d.ts +2 -2
  27. package/dist/client/hooks.js +2 -2
  28. package/dist/client/index.js +1 -1
  29. package/dist/client/index.js.map +1 -1
  30. package/dist/client/jwtDecoder.d.ts +8 -8
  31. package/dist/client/jwtDecoder.d.ts.map +1 -1
  32. package/dist/client/jwtDecoder.js +12 -15
  33. package/dist/client/jwtDecoder.js.map +1 -1
  34. package/dist/client/stores.d.ts.map +1 -1
  35. package/dist/client/stores.js +7 -16
  36. package/dist/client/stores.js.map +1 -1
  37. package/dist/consent/components/CookieConsent.svelte +179 -284
  38. package/dist/consent/config/consent.config.d.ts.map +1 -1
  39. package/dist/consent/config/consent.config.js +23 -20
  40. package/dist/consent/config/consent.config.js.map +1 -1
  41. package/dist/consent/index.js +1 -1
  42. package/dist/consent/index.js.map +1 -1
  43. package/dist/consent/interfaces/IConsentService.d.ts +3 -0
  44. package/dist/consent/interfaces/IConsentService.d.ts.map +1 -1
  45. package/dist/consent/services/ConsentService.d.ts +1 -0
  46. package/dist/consent/services/ConsentService.d.ts.map +1 -1
  47. package/dist/consent/services/ConsentService.js +17 -10
  48. package/dist/consent/services/ConsentService.js.map +1 -1
  49. package/dist/consent/utils/analytics.js +2 -2
  50. package/dist/consent/utils/analytics.js.map +1 -1
  51. package/dist/cookies/index.d.ts +10 -23
  52. package/dist/cookies/index.d.ts.map +1 -1
  53. package/dist/cookies/index.js +9 -22
  54. package/dist/cookies/index.js.map +1 -1
  55. package/dist/hooks/index.d.ts.map +1 -1
  56. package/dist/hooks/index.js +84 -66
  57. package/dist/hooks/index.js.map +1 -1
  58. package/dist/sentry/index.d.ts.map +1 -1
  59. package/dist/sentry/index.js +1 -1
  60. package/dist/sentry/index.js.map +1 -1
  61. package/dist/tracking/services/TrackingService.d.ts.map +1 -1
  62. package/dist/tracking/services/TrackingService.js +6 -7
  63. package/dist/tracking/services/TrackingService.js.map +1 -1
  64. package/dist/types/index.d.ts +19 -10
  65. package/dist/types/index.d.ts.map +1 -1
  66. package/package.json +6 -4
package/README.md CHANGED
@@ -1,64 +1,44 @@
1
1
  # @groundbrick/sveltekit-adapter
2
2
 
3
- SvelteKit integration adapter para o microframework TypeScript - fornece integração client-side com APIs Express, gerenciamento de estado reativo, autenticação JWT, hooks e sistema de consentimento de cookies.
4
-
5
- ## Features Implementadas
6
-
7
- - **🔧 ApiClient** - Cliente HTTP com autenticação, retry, timeout e suporte a cookies
8
- - **🔐 Gerenciamento de Autenticação** - Autenticação segura usando HttpOnly cookies
9
- - **📊 Stores Reativas** - Stores Svelte para estado de auth e API com suporte a runes
10
- - **� Sistema de Notificações** - Sistema completo de notificações toast com auto-clear na navegação
11
- - **�🛡️ Error Handling** - Hooks abrangentes de tratamento de erros
12
- - **📝 Request Logging** - Log automático de request/response com timing
13
- - **🎣 SvelteKit Hooks** - Hooks pré-construídos para autenticação e logging
14
- - **🔄 Retry Logic** - Lógica de retry automática com exponential backoff
15
- - **⏱️ Timeout Handling** - Controle de timeout configurável para requests
16
- - **🍪 Cookie Consent** - Sistema GDPR-compliant de consentimento com Google Analytics
3
+ Adaptador SvelteKit: cliente HTTP, stores, notificações, hooks de servidor, cookies de autenticação, consentimento de cookies, analytics, tracking e Sentry.
17
4
 
18
5
  ## Instalação
19
6
 
20
7
  ```bash
21
- npm install @groundbrick/sveltekit-adapter
8
+ pnpm add @groundbrick/sveltekit-adapter
22
9
  ```
23
10
 
24
- ### Peer Dependencies
11
+ Peer dependencies: `@sveltejs/kit` ^2.16.0, `svelte` ^5.25.0 e, opcionalmente, `@sentry/sveltekit` ^10.0.0. Requer Node.js >= 18.
25
12
 
26
- ```bash
27
- npm install @sveltejs/kit svelte
28
- ```
13
+ ## Exports
14
+
15
+ | Subpath | Conteúdo |
16
+ | --- | --- |
17
+ | `@groundbrick/sveltekit-adapter` | Reexporta `client`, `hooks`, `consent`, `analytics` e `cookies` |
18
+ | `.../client` | `ApiClient`, `ApiWrapper`, stores, JWT e notificações |
19
+ | `.../hooks` | Hooks de servidor |
20
+ | `.../cookies` | Cookies de autenticação |
21
+ | `.../consent` | Consentimento de cookies |
22
+ | `.../analytics` | Google Analytics, Google Ads e Facebook Pixel |
23
+ | `.../tracking` | Envio de eventos para um endpoint próprio |
24
+ | `.../sentry` | Sentry opcional |
29
25
 
30
- ## Quick Start
26
+ `tracking` e `sentry` só estão disponíveis pelo respetivo subpath. O build copia os componentes `.svelte` para `dist/`; são compilados pela app que os consome.
31
27
 
32
- ### 1. Configuração de Hooks
28
+ ## Hooks
33
29
 
34
30
  ```typescript
35
31
  // src/hooks.server.ts
36
32
  import { sequence } from '@sveltejs/kit/hooks';
37
- import { createSvelteKitHooks } from '@groundbrick/sveltekit-adapter';
33
+ import { createSvelteKitHooks } from '@groundbrick/sveltekit-adapter/hooks';
38
34
 
39
35
  const { hooks, handleError } = createSvelteKitHooks({
40
- logger: {
41
- logRequests: true,
42
- logResponses: true,
43
- includeHeaders: false,
44
- excludePaths: ['/favicon.ico', '/robots.txt', '/health'],
45
- context: 'my-app'
46
- },
47
- auth: {
48
- tokenKey: 'auth_token',
49
- publicPaths: ['/login', '/register', '/', '/api/public/*'],
50
- redirectPath: '/login',
51
- onAuthRequired: () => {
52
- console.log('Authentication required');
53
- }
54
- },
36
+ proxy: {},
37
+ logger: { excludePaths: ['/favicon.ico', '/robots.txt', '/health'], context: 'my-app' },
38
+ auth: { publicPaths: ['/login', '/register', '/', '/api/public/*'] },
55
39
  errorHandler: {
56
- logErrors: true,
57
40
  context: 'my-app',
58
- onError: (error, context) => {
59
- // Custom error handling
60
- console.error('App error:', error, context);
61
- }
41
+ onError: (error, context) => console.error('App error:', error, context)
62
42
  }
63
43
  });
64
44
 
@@ -66,479 +46,252 @@ export const handle = sequence(...hooks);
66
46
  export { handleError };
67
47
  ```
68
48
 
69
- ### 2. Configuração do API Client
49
+ Os hooks são devolvidos pela ordem proxy, logger, auth. `proxy` e `auth` só são incluídos quando configurados; o logger é incluído por omissão. Cada um pode ser criado isoladamente com `createProxyHeadersHook`, `createLoggerHook`, `createAuthHook` e `createErrorHandler`.
70
50
 
71
- ```typescript
72
- // src/lib/api.ts
73
- import { createApiClient } from '@groundbrick/sveltekit-adapter';
51
+ ### Logger (`LoggerHookConfig`)
74
52
 
75
- export const apiClient = createApiClient({
76
- baseUrl: 'http://localhost:3000/api',
77
- timeout: 10000,
78
- retries: 3,
79
- defaultHeaders: {
80
- 'X-App-Version': '1.0.0',
81
- 'X-Client': 'sveltekit'
82
- }
83
- });
84
- ```
53
+ | Opção | Padrão | Descrição |
54
+ | --- | --- | --- |
55
+ | `logRequests` | `true` | Regista método, URL, user agent e IP |
56
+ | `logResponses` | `true` | Regista método, URL, status e duração em ms |
57
+ | `includeHeaders` | `false` | Inclui os cabeçalhos no registo do pedido |
58
+ | `excludePaths` | `['/favicon.ico', '/robots.txt']` | Caminhos exatos não registados |
59
+ | `context` | `'request-logger'` | Contexto do logger |
85
60
 
86
- ### 3. Cookie Consent Setup
61
+ Um redirect lançado durante o pedido é devolvido como resposta. Outras exceções são registadas e relançadas.
87
62
 
88
- ```typescript
89
- // src/routes/+layout.svelte
90
- <script lang="ts">
91
- import {
92
- CookieConsent,
93
- ConsentService,
94
- createConsentAwareAnalytics
95
- } from '@groundbrick/sveltekit-adapter/consent';
96
-
97
- // Initialize consent service
98
- const consentService = ConsentService.getInstance();
99
-
100
- // Setup analytics with consent awareness
101
- const analytics = createConsentAwareAnalytics(consentService, {
102
- gaId: 'G-XXXXXXXXXX',
103
- enableDebug: true
104
- });
105
- </script>
63
+ ### Autenticação (`AuthHookConfig`)
106
64
 
107
- <!-- Your app content -->
108
- <slot />
109
-
110
- <!-- Cookie consent banner -->
111
- <CookieConsent
112
- theme="light"
113
- position="bottom"
114
- onConsentChange={(state) => {
115
- console.log('Consent updated:', state);
116
- }}
117
- />
118
- ```
65
+ | Opção | Padrão | Descrição |
66
+ | --- | --- | --- |
67
+ | `tokenKey` | `'auth_token'` | Nome do cookie |
68
+ | `redirectPath` | `'/login'` | Destino sem token |
69
+ | `publicPaths` | `['/login', '/register', '/']` | Caminhos exatos ou com `*` no fim |
70
+ | `isPublicPath` | - | Função verificada além de `publicPaths` |
71
+ | `validateExpiration` | `true` | Exige um JWT legível e não expirado. `false` para tokens que não são JWT |
72
+ | `onAuthRequired` | - | Chamada sem token, ou com token expirado ou ilegível |
73
+ | `validateSession` | - | Função `(token, event)` que devolve `'valid'`, `'invalid'` ou `'unknown'` |
74
+ | `authenticatedRedirect` | `'/dashboard'` | Destino de uma sessão confirmada: string, ou função que recebe o payload (`{}` se não for um JWT) |
75
+ | `cookieDomain` | - | Domínio, ou função do hostname, para apagar o cookie |
76
+ | `cookieOptions` | `{}` | `httpOnly`, `secure` e `sameSite` para apagar o cookie |
119
77
 
120
- ### 4. Using Stores
78
+ - Sem token num caminho protegido: redirect 302 para `redirectPath`, com `?redirect=` quando o caminho atual não é `/` nem `redirectPath`.
79
+ - Com token: fica em `event.locals.authToken` nos caminhos protegidos. O JWT é descodificado sem verificar a assinatura.
80
+ - Token expirado ou ilegível num caminho protegido, com `validateExpiration`: o cookie é apagado, `onAuthRequired` é chamada e há redirect 302 para `redirectPath`, como sem token.
81
+ - Em `/login` e `/register`, com token:
121
82
 
122
- ```typescript
123
- // src/routes/+page.svelte
124
- <script lang="ts">
125
- import {
126
- authStore,
127
- apiStore,
128
- isAuthenticated,
129
- currentUser,
130
- initializeStores
131
- } from '@groundbrick/sveltekit-adapter';
132
-
133
- // Initialize stores on app start
134
- initializeStores();
135
-
136
- // Reactive to authentication state
137
- $: if ($isAuthenticated) {
138
- console.log('User is logged in:', $currentUser);
139
- }
140
- </script>
141
-
142
- {#if $isAuthenticated}
143
- <h1>Welcome, {$currentUser?.name}!</h1>
144
- {:else}
145
- <a href="/login">Please log in</a>
146
- {/if}
147
-
148
- {#if $apiStore.loading}
149
- <div class="spinner">Loading...</div>
150
- {/if}
151
-
152
- {#if $apiStore.error}
153
- <div class="error">{$apiStore.error}</div>
154
- {/if}
155
- ```
156
-
157
- ## Module Exports
158
-
159
- ### Main Package
160
-
161
- ```typescript
162
- // Everything from client and hooks
163
- import {
164
- createApiClient,
165
- authStore,
166
- createSvelteKitHooks
167
- } from '@groundbrick/sveltekit-adapter';
168
- ```
83
+ | Sessão | Resposta | Cookie |
84
+ | --- | --- | --- |
85
+ | `validateSession` devolve `'valid'` | Redirect 302 para `authenticatedRedirect` | Mantido |
86
+ | `validateSession` devolve `'invalid'`, ou o token expirou ou é ilegível (com `validateExpiration`) | Página servida | Apagado |
87
+ | `'unknown'`, `validateSession` falha ou não está definida | Página servida | Mantido |
169
88
 
170
- ### Client Module
89
+ O conteúdo do token não é verificado pelo hook, e os parâmetros do URL não alteram a decisão. Quem recebe da API a recusa de uma sessão, num `load` ou endpoint, apaga o cookie no servidor antes de redirecionar para o login.
171
90
 
172
- ```typescript
173
- // Just client functionality
174
- import {
175
- ApiClient,
176
- createApiClient,
177
- authStore,
178
- apiStore,
179
- isAuthenticated,
180
- currentUser,
181
- isLoading,
182
- currentError,
183
- initializeStores,
184
- clearErrors
185
- } from '@groundbrick/sveltekit-adapter/client';
91
+ ```ts
92
+ validateSession: async (token, event) => {
93
+ const response = await event.fetch(`${API_URL}/auth/me`, {
94
+ headers: { Authorization: `Bearer ${token}` }
95
+ });
96
+ if (response.ok) return 'valid';
97
+ return response.status === 401 ? 'invalid' : 'unknown';
98
+ }
186
99
  ```
187
100
 
188
- ### Hooks Module
101
+ A página de login da aplicação não redireciona com base num token por verificar.
102
+ `handleAuthError`, usado pelo `ApiWrapper`, navega para o login com `?returnUrl=`, quando aplicável, e não apaga cookies `httpOnly`.
189
103
 
190
- ```typescript
191
- // Just hooks functionality
192
- import {
193
- createSvelteKitHooks,
194
- createAuthHook,
195
- createLoggerHook,
196
- createErrorHandlerHook
197
- } from '@groundbrick/sveltekit-adapter/hooks';
198
- ```
104
+ ### Cabeçalhos de proxy (`ProxyHookConfig`)
199
105
 
200
- ### Consent Module
106
+ | Opção | Padrão | Descrição |
107
+ | --- | --- | --- |
108
+ | `trustForwardedHeaders` | `true` | Aplica os cabeçalhos encaminhados |
109
+ | `forwardedHostHeader` | `'x-forwarded-host'` | Cabeçalho que substitui `host` |
110
+ | `forwardedProtoHeader` | `'x-forwarded-proto'` | Cabeçalho do protocolo (usa o primeiro valor) |
111
+ | `overrideOrigin` | `true` | Substitui um `origin` existente quando há host e protocolo |
201
112
 
202
- ```typescript
203
- // Cookie consent system
204
- import {
205
- CookieConsent,
206
- ConsentService,
207
- createConsentAwareAnalytics,
208
- GDPR_CONFIG,
209
- CCPA_CONFIG
210
- } from '@groundbrick/sveltekit-adapter/consent';
211
- ```
113
+ ### Erros (`ErrorHandlerConfig`)
212
114
 
213
- ## API Client Features
115
+ Opções: `logErrors` (padrão `true`), `context` (padrão `'error-handler'`), `logger` e `onError(error, context)`. Um status abaixo de 500 é registado como aviso; os restantes como erro. A mensagem devolvida é `Page not found` (404), `Internal server error` (>= 500) ou a mensagem do SvelteKit.
214
116
 
215
- ### Basic Usage
117
+ ## ApiClient
216
118
 
217
119
  ```typescript
218
- import { createApiClient } from '@groundbrick/sveltekit-adapter';
120
+ import { createApiClient } from '@groundbrick/sveltekit-adapter/client';
219
121
 
220
- const client = createApiClient({
122
+ export const apiClient = createApiClient({
221
123
  baseUrl: 'https://api.example.com',
222
124
  timeout: 10000,
223
- retries: 3
224
- });
225
-
226
- // GET request
227
- const users = await client.get('/users');
228
-
229
- // POST request with data
230
- const newUser = await client.post('/users', {
231
- name: 'John Doe',
232
- email: 'john@example.com'
125
+ retries: 3,
126
+ defaultHeaders: { 'X-App-Version': '1.0.0' }
233
127
  });
234
128
 
235
- // Request with auth token
236
- const profile = await client.get('/profile', {
237
- headers: { Authorization: 'Bearer token' }
238
- });
129
+ const users = await apiClient.get('/users');
130
+ await apiClient.post('/users', { name: 'John Doe' });
131
+ await apiClient.requestWithRetry('/users', { method: 'GET' });
239
132
  ```
240
133
 
241
- ### Advanced Configuration
134
+ | Método | Assinatura |
135
+ | --- | --- |
136
+ | `get` | `get<T>(endpoint, options?): Promise<T>` |
137
+ | `post`, `put`, `patch` | `post<T>(endpoint, data?, options?): Promise<T>` |
138
+ | `delete` | `delete<T>(endpoint, options?): Promise<T>` |
139
+ | `requestWithRetry` | `requestWithRetry<T>(endpoint, options?, retries?): Promise<T>` |
242
140
 
243
- ```typescript
244
- const client = createApiClient({
245
- baseUrl: 'https://api.example.com',
246
- timeout: 15000,
247
- retries: 5,
248
- retryDelay: 1000,
249
- defaultHeaders: {
250
- 'Content-Type': 'application/json',
251
- 'X-API-Version': '2024-01-01'
252
- },
253
- interceptors: {
254
- request: (config) => {
255
- // Add timestamp to all requests
256
- config.headers['X-Timestamp'] = new Date().toISOString();
257
- return config;
258
- },
259
- response: (response) => {
260
- // Log all successful responses
261
- console.log('Response received:', response.status);
262
- return response;
263
- },
264
- error: (error) => {
265
- // Custom error handling
266
- if (error.status === 401) {
267
- // Redirect to login
268
- window.location.href = '/login';
269
- }
270
- throw error;
271
- }
272
- }
273
- });
274
- ```
275
-
276
- ### Authentication Flow
277
-
278
- The adapter provides secure authentication using HttpOnly cookies:
141
+ - Configuração: `baseUrl`, `timeout` (padrão 10000 ms), `retries` (padrão 3, usado por `requestWithRetry`) e `defaultHeaders`.
142
+ - Opções por pedido: as de `RequestInit`, `timeout` e `expectedStatuses` (status que não são registados como aviso).
143
+ - Envia cookies (`credentials: 'include'`). O corpo é enviado como JSON, ou sem alterações quando é `FormData`.
144
+ - Uma resposta HTTP de erro não lança: é devolvida com `error.message` e `error.status`.
145
+ - JSON inválido é convertido num erro; um corpo vazio resulta em `{ success, status }`.
146
+ - Uma falha de rede ou um timeout lança `Error`.
147
+ - `requestWithRetry` repete quando o pedido lança, com espera de 1 s, 2 s, 4 s, etc. Os outros métodos não repetem.
279
148
 
280
- #### How Authentication Works:
149
+ ## ApiWrapper
281
150
 
282
- 1. **Server-side**: Auth hook validates JWT tokens from HttpOnly cookies (no client-side token handling)
283
- 2. **Client-side**: API Client automatically includes cookies with all requests
284
- 3. **Automatic cleanup**: Invalid tokens are cleared through HttpOnly cookie management
285
- 4. **Smart redirects**: Users are redirected to login with current page as return URL
286
- 5. **No performance impact**: No unnecessary API calls on page loads
151
+ ```typescript
152
+ import { createApiWrapper } from '@groundbrick/sveltekit-adapter/client';
287
153
 
288
- #### Auth Hook Configuration:
154
+ const api = createApiWrapper(apiClient);
155
+ const result = await api.get<User[]>('/users', { expectedStatuses: [404] });
289
156
 
290
- ```typescript
291
- // src/hooks.server.ts
292
- const { hooks, handleError } = createSvelteKitHooks({
293
- auth: {
294
- tokenKey: 'auth_token',
295
- redirectPath: '/login',
296
- publicPaths: [
297
- '/login',
298
- '/register',
299
- '/',
300
- '/landing',
301
- '/api/*', // Allow API calls to pass through
302
- '/favicon.ico',
303
- '/robots.txt'
304
- ],
305
- validateExpiration: true // Enable JWT expiration checking (default: true)
306
- }
307
- });
157
+ if (result.success) {
158
+ console.log(result.data);
159
+ } else {
160
+ console.error(result.error?.code, result.error?.status, result.error?.details);
161
+ }
308
162
  ```
309
163
 
310
- ## Auth Cookies
311
-
312
- `@groundbrick/sveltekit-adapter/cookies` keeps the set/delete options in one place — they must match **exactly**, or the browser creates a second cookie instead of clearing the first.
164
+ Métodos: `get`, `post`, `put`, `patch`, `delete` e `call(apiCall, options?)`. A API tem de responder com `{ success, data?, error?, message? }`; `success: false` é acompanhado de `error`.
313
165
 
314
- ```ts
315
- import { createAuthCookieHelper, isSecureRequest } from '@groundbrick/sveltekit-adapter/cookies';
166
+ | Opção | Padrão | Descrição |
167
+ | --- | --- | --- |
168
+ | `showLoading` | `true` | Atualiza `apiStore.loading` |
169
+ | `showErrorNotification` | `true` | Mostra uma notificação de erro no browser |
170
+ | `customErrorMessage` | - | Mensagem da notificação de erro |
171
+ | `expectedStatuses` | - | Status não registados como aviso (aplica-se a `get`) |
172
+ | `skipAuthHandling` | `false` | Não faz logout nem redirect |
316
173
 
317
- // Build it per request so `secure` follows the real protocol.
318
- const cookie = (event: RequestEvent) =>
319
- createAuthCookieHelper({
320
- tokenKey: 'minha_sessao', // name the cookie (default: 'auth_token')
321
- isProduction: process.env.NODE_ENV === 'production',
322
- secure: isSecureRequest(event),
323
- sameSite: 'lax'
324
- // resolveDomain omitted: host-only cookie, right for a single-host app.
325
- // Cross-subdomain? pass `(h) => resolveCookieDomain(h, env.COOKIE_DOMAIN)`.
326
- });
327
-
328
- cookie(event).set(event.cookies, event.url.hostname, token, maxAgeSeconds);
329
- cookie(event).get(event.cookies);
330
- cookie(event).delete(event.cookies, event.url.hostname);
331
- ```
174
+ - 401: mostra um aviso de sessão expirada (no máximo um a cada 5 s), limpa a `authStore` e navega para `/login`, com `?returnUrl=` quando aplicável.
175
+ - 403: mostra a notificação e mantém a sessão, exceto com um código de sessão inválida, tratado com logout e redirect.
176
+ - Os erros são devolvidos como `{ success: false, error: { message, status, code, details } }`.
332
177
 
333
- `isSecureRequest` reads `x-forwarded-proto` before `event.url`. Behind a proxy, adapter-node builds `event.url` from `ORIGIN`: with `ORIGIN=https://…` and a browser on plain http the cookie goes out `Secure`, the browser drops it silently, and the login bounces back with no error — indistinguishable from a wrong password. The same applies to the delete: a `Secure` delete over http never clears anything.
178
+ `authErrorHandler` e `handleAuthError(error)` expõem o logout e redirect; `error.redirectTo` altera o destino.
334
179
 
335
- ## Cookie Consent System
180
+ ## Stores
336
181
 
337
- ### GDPR Compliance
182
+ | Export | Descrição |
183
+ | --- | --- |
184
+ | `authStore` | `isAuthenticated`, `user`, `loading`, `error`; métodos `login(user)`, `logout()`, `setLoading`, `setError`, `initialize` (sem efeito), `initializeFromJwt`, `initializeFromToken` |
185
+ | `apiStore` | `loading`, `error`, `lastRequest`; métodos `setLoading`, `setError`, `setLastRequest` |
186
+ | `currentUser`, `isLoading`, `currentError` | Stores derivadas |
187
+ | `initializeFromJwt(payload)` | Preenche a `authStore` com o payload |
188
+ | `initializeFromToken(token)` | Descodifica e preenche; devolve `false` se inválido ou expirado |
189
+ | `initializeAuth(apiClient)` | Obsoleta: usar `initializeFromJwt`. Chama `GET /auth/me` e guarda a resposta como utilizador |
190
+ | `initializeStores()` | Chama `authStore.initialize()` no browser |
191
+ | `clearErrors()` | Limpa os erros das duas stores |
338
192
 
339
- ```typescript
340
- import {
341
- ConsentService,
342
- GDPR_CONFIG,
343
- createConsentAwareAnalytics
344
- } from '@groundbrick/sveltekit-adapter/consent';
345
-
346
- // GDPR-compliant setup
347
- const consentService = ConsentService.getInstance(GDPR_CONFIG);
348
-
349
- // Analytics only loads with explicit consent
350
- const analytics = createConsentAwareAnalytics(consentService, {
351
- gaId: 'G-XXXXXXXXXX',
352
- anonymizeIp: true
353
- });
193
+ ```svelte
194
+ <script lang="ts">
195
+ import { authStore, apiStore, currentUser } from '@groundbrick/sveltekit-adapter/client';
196
+ </script>
354
197
 
355
- // Track events (respects consent automatically)
356
- analytics.trackEvent({
357
- action: 'button_click',
358
- category: 'UI',
359
- label: 'signup'
360
- });
198
+ {#if $authStore.isAuthenticated}
199
+ <h1>{$currentUser?.name}</h1>
200
+ {/if}
201
+ {#if $apiStore.loading}<p>Loading...</p>{/if}
361
202
  ```
362
203
 
363
- ### Custom Configuration
204
+ ## JWT
364
205
 
365
- ```typescript
366
- const customConfig = {
367
- banner: {
368
- title: '🍪 Cookies',
369
- message: 'We use cookies to improve your experience.',
370
- acceptAllText: 'Accept All',
371
- rejectAllText: 'Reject All'
372
- },
373
- categories: {
374
- functional: {
375
- required: true,
376
- name: 'Essential',
377
- description: 'Required for basic functionality'
378
- },
379
- analytics: {
380
- required: false,
381
- name: 'Analytics',
382
- description: 'Help us improve our website'
383
- }
384
- }
385
- };
386
-
387
- const consentService = ConsentService.getInstance(customConfig);
388
- ```
206
+ `decodeJwtToken` e `safeDecodeJwt` descodificam o token sem verificar a assinatura e devolvem `{ payload, isValid, isExpired, expiresAt }` ou `null`. `getUserDisplayName(payload)` devolve o nome, o e-mail ou `'User'`; `getAdditionalFields(payload)` devolve os campos não standard.
389
207
 
390
- ## Stores System
208
+ `hasPermission`, `hasAnyPermission` e `hasAllPermissions` usam `payload.role`: `super_admin` e `admin` têm todas as permissões, `staff` as da lista `permissions`, e os restantes nenhuma.
391
209
 
392
- ### Authentication Store
210
+ ## Notificações
393
211
 
394
212
  ```typescript
395
- import { authStore, isAuthenticated, currentUser } from '@groundbrick/sveltekit-adapter';
213
+ import { showSuccess, showError, clearAllNotifications } from '@groundbrick/sveltekit-adapter/client';
396
214
 
397
- // Reactive authentication state
398
- $: if ($isAuthenticated) {
399
- console.log('User:', $currentUser);
400
- }
401
-
402
- // Login
403
- authStore.login({
404
- token: 'jwt-token',
405
- user: { id: 1, name: 'John', email: 'john@example.com' }
406
- });
215
+ const id = showSuccess('Saved', { title: 'Success', duration: 3000, persistent: true });
216
+ showError('Something went wrong');
217
+ clearAllNotifications();
218
+ ```
407
219
 
408
- // Logout
409
- authStore.logout();
220
+ - `showSuccess`, `showError`, `showWarning` e `showInfo` recebem `(message, options?)` e devolvem o id. A duração padrão é 8000 ms para erros e 5000 ms para as restantes; `0` não fecha automaticamente.
221
+ - `removeNotification(id)`, `clearNotificationsByType(type)`, `clearNonPersistentNotifications()` e `clearAllNotifications()` removem notificações.
222
+ - Stores: `notificationStore`, `notifications`, `errorNotifications`, `successNotifications`, `warningNotifications`, `infoNotifications`, `latestError`, `latestSuccess`, `hasNotifications`, `hasErrors`, `hasSuccess`.
223
+ - `useNavigationNotificationClear()`, no layout raiz, limpa as não persistentes ao navegar; `useClearNotificationsOnMount()` limpa-as quando é chamada.
410
224
 
411
- // Check if user has specific role
412
- if ($currentUser?.roles?.includes('admin')) {
413
- // Show admin content
414
- }
415
- ```
225
+ A app fornece o componente que mostra `$notifications`.
416
226
 
417
- ### API Store
227
+ ## Cookies de autenticação
418
228
 
419
229
  ```typescript
420
- import { apiStore, isLoading, currentError } from '@groundbrick/sveltekit-adapter';
421
-
422
- // Loading states
423
- $: if ($isLoading) {
424
- // Show spinner
425
- }
230
+ import { createAuthCookieHelper, isSecureRequest, resolveCookieDomain } from '@groundbrick/sveltekit-adapter/cookies';
426
231
 
427
- // Error handling
428
- $: if ($currentError) {
429
- // Show error message
430
- console.error('API Error:', $currentError);
431
- }
232
+ const cookie = (event: RequestEvent) =>
233
+ createAuthCookieHelper({
234
+ tokenKey: 'session',
235
+ isProduction: process.env.NODE_ENV === 'production',
236
+ secure: isSecureRequest(event),
237
+ sameSite: 'lax',
238
+ resolveDomain: (hostname) => resolveCookieDomain(hostname, process.env.COOKIE_DOMAIN)
239
+ });
432
240
 
433
- // Manual error clearing
434
- apiStore.clearError();
241
+ cookie(event).set(event.cookies, event.url.hostname, token, 3600);
242
+ cookie(event).get(event.cookies);
243
+ cookie(event).delete(event.cookies, event.url.hostname);
435
244
  ```
436
245
 
437
- ### Notification System
246
+ | Opção | Padrão | Descrição |
247
+ | --- | --- | --- |
248
+ | `isProduction` | obrigatória | Define os padrões de `secure` e `sameSite` |
249
+ | `tokenKey` | `'auth_token'` | Nome do cookie |
250
+ | `resolveDomain` | cookie host-only | Domínio a partir do hostname |
251
+ | `secure` | `isProduction` | Flag `secure` |
252
+ | `sameSite` | `strict` em produção, `lax` fora dela | Atributo `sameSite` |
438
253
 
439
- ```typescript
440
- import {
441
- showSuccess,
442
- showError,
443
- showWarning,
444
- showInfo,
445
- clearAllNotifications,
446
- useNavigationNotificationClear
447
- } from '@groundbrick/sveltekit-adapter';
448
-
449
- // Enable auto-clearing on navigation (add to your root layout)
450
- useNavigationNotificationClear();
451
-
452
- // Show different types of notifications
453
- showSuccess('Data saved successfully!');
454
- showError('Something went wrong!');
455
- showWarning('This action cannot be undone!');
456
- showInfo('New feature available!');
457
-
458
- // With options
459
- showSuccess('Operation complete!', {
460
- title: 'Success',
461
- duration: 3000,
462
- persistent: false // won't clear on navigation if true
463
- });
254
+ Os cookies usam `path: '/'` e `httpOnly: true`. O helper tem ainda `setNamed`, `deleteNamed`, `getDeleteOptions` e `getHookCookieOptions`. O módulo exporta também `createAuthCookieOptions`.
464
255
 
465
- // Clear notifications
466
- clearAllNotifications();
467
- ```
256
+ - As opções de escrita e de remoção têm de coincidir.
257
+ - `isSecureRequest(event, header?)` usa o primeiro valor de `x-forwarded-proto` e, na sua ausência, `event.url.protocol`.
258
+ - `resolveCookieDomain(hostname, configured?)` devolve o domínio configurado quando corresponde ao hostname. Sem correspondência, um hostname com mais de duas partes resolve para o domínio pai e os restantes para `undefined`. Se o hostname for igual ao domínio configurado e tiver mais de duas partes, resolve para o domínio pai.
468
259
 
469
- Add notification component to your layout:
260
+ ## Consentimento e analytics
470
261
 
471
262
  ```svelte
472
- <script>
473
- import { useNavigationNotificationClear } from '@groundbrick/sveltekit-adapter';
474
- import Notifications from '$lib/components/Notifications.svelte';
475
-
476
- // Enable auto-clearing
477
- useNavigationNotificationClear();
478
- </script>
263
+ <script lang="ts">
264
+ import { CookieConsent, GDPR_CONFIG } from '@groundbrick/sveltekit-adapter/consent';
265
+ import { GoogleAnalytics } from '@groundbrick/sveltekit-adapter/analytics';
479
266
 
480
- <main>
481
- <slot />
482
- </main>
267
+ let { children } = $props();
268
+ </script>
483
269
 
484
- <!-- Notifications -->
485
- <Notifications />
270
+ {@render children()}
271
+ <GoogleAnalytics measurementId="G-XXXXXXXXXX" />
272
+ <CookieConsent config={GDPR_CONFIG} />
486
273
  ```
487
274
 
488
- ### Logging Estruturado
275
+ `consent` exporta `ConsentService`, `CookieConsent`, `DEFAULT_CONSENT_CONFIG`, `GDPR_CONFIG`, `CCPA_CONFIG` e `GENERIC_CONFIG`.
489
276
 
490
- - **Request/Response**: Log automático com timing
491
- ```typescript
492
- // Configuração no hooks.server.ts
493
- const loggerHook = createLoggerHook({
494
- logRequests: true, // GET /api/users [timing: 245ms]
495
- logResponses: true // GET /api/users 200 OK [duration: 245ms]
496
- });
277
+ `analytics` exporta `AnalyticsService`, `GoogleAnalytics`, `FacebookPixel`, `createConsentAwareAnalytics`, `createConsentWrapper`, `createConsentAwarePixel`, `createFacebookEvents`, `AnalyticsEventBuilder`, `AnalyticsEvents` e as configurações `DEFAULT_ANALYTICS_CONFIG`, `GDPR_ANALYTICS_CONFIG`, `DEBUG_ANALYTICS_CONFIG` e `MINIMAL_ANALYTICS_CONFIG`.
497
278
 
498
- // Logs automáticos no console/arquivo
499
- // INFO: Incoming request { method: 'GET', url: '/api/users', duration: 245 }
500
- ```
279
+ ## Tracking
501
280
 
502
- - **Context preservation**: Mantém contexto através da aplicação
503
281
  ```typescript
504
- // Contexto propagado automaticamente
505
- const logger = createLogger().child('user-service');
506
- // user-service: Processing user creation
507
- // user-service: Database query completed
508
- // user-service: User created successfully
509
- ```
282
+ import { TrackingService } from '@groundbrick/sveltekit-adapter/tracking';
510
283
 
511
- - **Structured data**: Logs estruturados com metadados
512
- ```typescript
513
- // Metadados automáticos em cada log
514
- logger.info('User login', {
515
- userId: 123,
516
- ip: '192.168.1.1',
517
- userAgent: 'Chrome/120.0',
518
- timestamp: '2024-01-15T10:30:00Z',
519
- requestId: 'req_abc123'
520
- });
284
+ const tracking = TrackingService.getInstance();
285
+ tracking.initialize({ h2b2Url: 'https://events.example.com', batchSize: 5, flushInterval: 10000 });
286
+ await tracking.trackEvent({ event_name: 'order_created', properties: { orderId: 1 } });
521
287
  ```
522
288
 
523
- - **Performance tracking**: Tracking de performance automático
524
- ```typescript
525
- // Timing automático de requests
526
- const startTime = Date.now();
527
- await apiClient.get('/heavy-endpoint');
528
- // Log: Request completed { duration: 1247ms, status: 200 }
289
+ - `initialize` envia `POST {h2b2Url}/tracking/sessions`; cada evento é enviado para `POST {h2b2Url}/tracking/events`.
290
+ - A fila é enviada ao atingir `batchSize` (padrão 5), a cada `flushInterval` ms (padrão 10000) e em `beforeunload`. Um pedido rejeitado volta à fila.
291
+ - O id do visitante fica em `localStorage` (`h2b2_visitor_id`). `h2b2_tracking_optout` com o valor `true` impede novos eventos.
292
+ - Métodos: `trackEvent`, `identifyUser`, `clearUser`, `getSessionId`, `flush`, `isEnabled`, `getState` e `destroy`.
529
293
 
530
- // Timing de hooks
531
- // Log: Request processed { url: '/dashboard', duration: 89ms }
532
- ```
533
-
534
- ## Sentry (opcional) — `@groundbrick/sveltekit-adapter/sentry`
535
-
536
- Error tracking do cliente e do SSR, **opt-in por DSN**. Sem DSN nada é carregado: o
537
- `@sentry/sveltekit` é importado sob demanda num chunk à parte, e todos os exports abaixo
538
- funcionam como pass-through. Uma falha a carregar ou a iniciar o Sentry nunca bloqueia a app.
539
-
540
- O subpath não é reexportado pela raiz: apps que não o importam não levam nada. Quem o usa
541
- precisa de ter o `@sentry/sveltekit` instalado (peer opcional), porque o bundler tem de o resolver.
294
+ ## Sentry
542
295
 
543
296
  ```bash
544
297
  pnpm add @sentry/sveltekit
@@ -550,17 +303,15 @@ import type { HandleClientError } from '@sveltejs/kit';
550
303
  import { env } from '$env/dynamic/public';
551
304
  import { initSentry, handleErrorWithSentry } from '@groundbrick/sveltekit-adapter/sentry';
552
305
 
553
- export const init = () =>
554
- initSentry({
555
- dsn: env.PUBLIC_SENTRY_DSN,
556
- environment: env.PUBLIC_SENTRY_ENVIRONMENT,
557
- tracesSampleRate: env.PUBLIC_SENTRY_TRACES_SAMPLE_RATE // padrão 0.1
558
- });
559
-
560
- const baseHandleError: HandleClientError = ({ error }) => {
561
- console.error(error);
562
- return { message: 'Ocorreu um erro inesperado.' };
306
+ export const init = async () => {
307
+ await initSentry({
308
+ dsn: env.PUBLIC_SENTRY_DSN,
309
+ environment: env.PUBLIC_SENTRY_ENVIRONMENT,
310
+ tracesSampleRate: env.PUBLIC_SENTRY_TRACES_SAMPLE_RATE
311
+ });
563
312
  };
313
+
314
+ const baseHandleError: HandleClientError = () => ({ message: 'Ocorreu um erro inesperado.' });
564
315
  export const handleError = handleErrorWithSentry(baseHandleError);
565
316
  ```
566
317
 
@@ -568,64 +319,19 @@ export const handleError = handleErrorWithSentry(baseHandleError);
568
319
  // src/hooks.server.ts
569
320
  import { sequence } from '@sveltejs/kit/hooks';
570
321
  import { env } from '$env/dynamic/public';
322
+ import { createSvelteKitHooks } from '@groundbrick/sveltekit-adapter/hooks';
571
323
  import { initSentry, sentryHandle, handleErrorWithSentry } from '@groundbrick/sveltekit-adapter/sentry';
572
324
 
573
- export const init = () => initSentry({ dsn: env.PUBLIC_SENTRY_DSN, environment: env.PUBLIC_SENTRY_ENVIRONMENT });
325
+ const { hooks, handleError: baseHandleError } = createSvelteKitHooks();
326
+
327
+ export const init = async () => {
328
+ await initSentry({ dsn: env.PUBLIC_SENTRY_DSN });
329
+ };
574
330
  export const handle = sequence(sentryHandle(), ...hooks);
575
331
  export const handleError = handleErrorWithSentry(baseHandleError);
576
332
  ```
577
333
 
578
- Também exporta `captureException`, `captureMessage`, `flushSentry` e `isSentryEnabled`
579
- (todos no-op sem Sentry).
580
-
581
- **Dados pessoais:** `sendDefaultPii` desligado e os mesmos filtros do backend
582
- (`@groundbrick/logger/privacy`): corpo dos pedidos, cookies e query strings removidos (o
583
- `?token=` de um link de reset não sai), cabeçalhos de autenticação mascarados, e-mails e
584
- telefones mascarados, breadcrumbs de consola descartados. Session Replay não é ativado.
585
-
586
- ## Melhores Práticas
587
-
588
- 1. **Inicialize stores cedo** no ciclo de vida da aplicação
589
- 2. **Use stores reativas** em vez de gerenciamento manual de estado
590
- 3. **Configure hooks apropriadamente** para as necessidades da sua aplicação
591
- 4. **Use TypeScript** para melhor experiência de desenvolvimento
592
- 5. **Trate erros graciosamente** com os error stores
593
- 6. **Configure paths públicos** no hook de autenticação
594
- 7. **Use retry mechanism** para endpoints instáveis
595
- 8. **Implemente consent** desde o início para compliance
596
- 9. **Configure analytics** com consent awareness
597
- 10. **Use presets** de configuração para diferentes regiões
598
-
599
- ## Compatibilidade
600
-
601
- - **Svelte 5.x** com runes support
602
- - **SvelteKit 2.x** com app directory structure
603
- - **Node.js 18+** para funcionalidades de servidor
604
- - **TypeScript 5.x** para tipagem completa
605
-
606
- ## Dependencies
607
-
608
- ### Required
609
- - `@groundbrick/logger` - Sistema de logging
610
-
611
- ### Peer Dependencies
612
- - `@sveltejs/kit` - SvelteKit framework (^2.0.0)
613
- - `svelte` - Svelte framework (^5.0.0)
614
-
615
- ## License
616
-
617
- MIT
618
-
619
- ## Packaging & build notes
620
-
621
- - During the package build we copy some source assets (for example, `.svelte` components) from `src/` into the published `dist/` folder. This is handled by the script `scripts/copy-assets.js` which runs after `tsc` in the package `build` script.
622
-
623
- - Why: some modules are intentionally re-exported as source Svelte components (for example `analytics/components/GoogleAnalytics.svelte`). The compiled TypeScript output in `dist` contains runtime imports to those `.svelte` files. To make the package consumable by apps that will compile Svelte components in their own build (SvelteKit apps), we ship the `.svelte` files alongside the compiled JS so imports resolve correctly.
624
-
625
- - Why not rsync: earlier we used `rsync` to copy files, but that requires `rsync` to be present on the build server. To make builds portable across environments we now use a small cross-platform Node script.
626
-
627
- - Alternatives:
628
- - Precompile Svelte components into JavaScript during the package build (using Rollup/Vite or `svelte/compiler`). This produces a distribution with JS only (no `.svelte` sources), which is cleaner for non-Svelte consumers but requires adding a Svelte compilation step to the package build.
629
- - Keep shipping `.svelte` files (the current approach). This is the simplest and lets SvelteKit apps compile components during app build time.
630
-
631
- - If you prefer a precompiled distribution, open an issue or request and we can add a Rollup/Vite build step (low-risk, slightly larger change).
334
+ - O módulo requer `@sentry/sveltekit` instalado. Só é carregado com um DSN; sem DSN os exports funcionam como pass-through.
335
+ - `initSentry` aceita `dsn`, `environment`, `release` e `tracesSampleRate` (padrão 0.1). Devolve se o Sentry está ativo e não lança.
336
+ - `captureException`, `captureMessage` e `flushSentry` não têm efeito sem Sentry; `isSentryEnabled` indica se está ativo.
337
+ - `sendDefaultPii` está desligado. Os filtros de `@groundbrick/logger/privacy` removem o corpo, os cookies e as query strings dos pedidos, mascaram cabeçalhos de autenticação, e-mails e telefones e descartam breadcrumbs de consola.