@groundbrick/sveltekit-adapter 0.8.0 → 0.10.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.
- package/README.md +227 -502
- package/dist/analytics/components/FacebookPixel.svelte +8 -27
- package/dist/analytics/components/GoogleAnalytics.svelte +12 -16
- package/dist/analytics/config/analytics.config.js +1 -1
- package/dist/analytics/config/analytics.config.js.map +1 -1
- package/dist/analytics/interfaces/IAnalyticsService.d.ts +5 -6
- package/dist/analytics/interfaces/IAnalyticsService.d.ts.map +1 -1
- package/dist/analytics/services/AnalyticsService.d.ts +2 -4
- package/dist/analytics/services/AnalyticsService.d.ts.map +1 -1
- package/dist/analytics/services/AnalyticsService.js +10 -9
- package/dist/analytics/services/AnalyticsService.js.map +1 -1
- package/dist/analytics/utils/consent.js +3 -3
- package/dist/analytics/utils/consent.js.map +1 -1
- package/dist/auth/index.d.ts.map +1 -1
- package/dist/auth/index.js +1 -5
- package/dist/auth/index.js.map +1 -1
- package/dist/client/ApiClient.d.ts.map +1 -1
- package/dist/client/ApiClient.js +4 -10
- package/dist/client/ApiClient.js.map +1 -1
- package/dist/client/apiWrapper.d.ts +49 -41
- package/dist/client/apiWrapper.d.ts.map +1 -1
- package/dist/client/apiWrapper.js +35 -35
- package/dist/client/apiWrapper.js.map +1 -1
- package/dist/client/authErrorHandler.d.ts.map +1 -1
- package/dist/client/authErrorHandler.js +3 -7
- package/dist/client/authErrorHandler.js.map +1 -1
- package/dist/client/hooks.d.ts +2 -2
- package/dist/client/hooks.js +2 -2
- package/dist/client/index.d.ts +2 -1
- package/dist/client/index.d.ts.map +1 -1
- package/dist/client/index.js +3 -1
- package/dist/client/index.js.map +1 -1
- package/dist/client/jwtDecoder.d.ts +8 -8
- package/dist/client/jwtDecoder.d.ts.map +1 -1
- package/dist/client/jwtDecoder.js +12 -15
- package/dist/client/jwtDecoder.js.map +1 -1
- package/dist/client/stores.d.ts.map +1 -1
- package/dist/client/stores.js +7 -16
- package/dist/client/stores.js.map +1 -1
- package/dist/consent/components/CookieConsent.svelte +3 -4
- package/dist/consent/config/consent.config.js +13 -13
- package/dist/consent/config/consent.config.js.map +1 -1
- package/dist/consent/index.js +1 -1
- package/dist/consent/index.js.map +1 -1
- package/dist/consent/services/ConsentService.d.ts.map +1 -1
- package/dist/consent/services/ConsentService.js +5 -11
- package/dist/consent/services/ConsentService.js.map +1 -1
- package/dist/consent/utils/analytics.js +2 -2
- package/dist/consent/utils/analytics.js.map +1 -1
- package/dist/cookies/index.d.ts +10 -23
- package/dist/cookies/index.d.ts.map +1 -1
- package/dist/cookies/index.js +9 -22
- package/dist/cookies/index.js.map +1 -1
- package/dist/hooks/index.d.ts +1 -0
- package/dist/hooks/index.d.ts.map +1 -1
- package/dist/hooks/index.js +68 -65
- package/dist/hooks/index.js.map +1 -1
- package/dist/navigation/returnUrl.d.ts +17 -0
- package/dist/navigation/returnUrl.d.ts.map +1 -0
- package/dist/navigation/returnUrl.js +32 -0
- package/dist/navigation/returnUrl.js.map +1 -0
- package/dist/sentry/index.d.ts.map +1 -1
- package/dist/sentry/index.js +1 -1
- package/dist/sentry/index.js.map +1 -1
- package/dist/tracking/services/TrackingService.d.ts.map +1 -1
- package/dist/tracking/services/TrackingService.js +6 -7
- package/dist/tracking/services/TrackingService.js.map +1 -1
- package/dist/types/index.d.ts +19 -10
- package/dist/types/index.d.ts.map +1 -1
- package/package.json +5 -3
package/README.md
CHANGED
|
@@ -1,64 +1,44 @@
|
|
|
1
1
|
# @groundbrick/sveltekit-adapter
|
|
2
2
|
|
|
3
|
-
SvelteKit
|
|
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
|
-
|
|
8
|
+
pnpm add @groundbrick/sveltekit-adapter
|
|
22
9
|
```
|
|
23
10
|
|
|
24
|
-
|
|
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
|
-
|
|
27
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
41
|
-
|
|
42
|
-
|
|
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,271 @@ export const handle = sequence(...hooks);
|
|
|
66
46
|
export { handleError };
|
|
67
47
|
```
|
|
68
48
|
|
|
69
|
-
|
|
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
|
-
|
|
72
|
-
// src/lib/api.ts
|
|
73
|
-
import { createApiClient } from '@groundbrick/sveltekit-adapter';
|
|
51
|
+
### Logger (`LoggerHookConfig`)
|
|
74
52
|
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
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
|
-
|
|
61
|
+
Um redirect lançado durante o pedido é devolvido como resposta. Outras exceções são registadas e relançadas.
|
|
87
62
|
|
|
88
|
-
|
|
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
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
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
|
-
|
|
78
|
+
- Sem token num caminho protegido: redirect 302 para `redirectPath`, com `?returnUrl=` (caminho e query) 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
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
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>
|
|
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 |
|
|
141
88
|
|
|
142
|
-
|
|
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}
|
|
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.
|
|
151
90
|
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
{/
|
|
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
|
+
}
|
|
155
99
|
```
|
|
156
100
|
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
### Main Package
|
|
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`.
|
|
160
103
|
|
|
161
|
-
|
|
162
|
-
// Everything from client and hooks
|
|
163
|
-
import {
|
|
164
|
-
createApiClient,
|
|
165
|
-
authStore,
|
|
166
|
-
createSvelteKitHooks
|
|
167
|
-
} from '@groundbrick/sveltekit-adapter';
|
|
168
|
-
```
|
|
104
|
+
### Página de regresso
|
|
169
105
|
|
|
170
|
-
|
|
106
|
+
`createAuthHook` e `handleAuthError` põem a página atual em `returnUrl`. `hooks` e `client` exportam:
|
|
171
107
|
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
authStore,
|
|
178
|
-
apiStore,
|
|
179
|
-
isAuthenticated,
|
|
180
|
-
currentUser,
|
|
181
|
-
isLoading,
|
|
182
|
-
currentError,
|
|
183
|
-
initializeStores,
|
|
184
|
-
clearErrors
|
|
185
|
-
} from '@groundbrick/sveltekit-adapter/client';
|
|
186
|
-
```
|
|
108
|
+
| Função | Descrição |
|
|
109
|
+
| --- | --- |
|
|
110
|
+
| `safeReturnUrl(value, origin, loginPath = '/login')` | Caminho, query e hash quando `value` é um caminho dentro de `origin`; caso contrário `null`. Também devolve `null` para a própria página de login |
|
|
111
|
+
| `withReturnUrl(loginPath, { pathname, search })` | URL de login com `returnUrl` |
|
|
112
|
+
| `RETURN_URL_PARAM` | `'returnUrl'` |
|
|
187
113
|
|
|
188
|
-
|
|
114
|
+
```ts
|
|
115
|
+
// src/routes/login/+page.server.ts
|
|
116
|
+
import { safeReturnUrl } from '@groundbrick/sveltekit-adapter/hooks';
|
|
189
117
|
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
createSvelteKitHooks,
|
|
194
|
-
createAuthHook,
|
|
195
|
-
createLoggerHook,
|
|
196
|
-
createErrorHandlerHook
|
|
197
|
-
} from '@groundbrick/sveltekit-adapter/hooks';
|
|
118
|
+
export const load = ({ url }) => ({
|
|
119
|
+
returnUrl: safeReturnUrl(url.searchParams.get('returnUrl'), url.origin)
|
|
120
|
+
});
|
|
198
121
|
```
|
|
199
122
|
|
|
200
|
-
###
|
|
123
|
+
### Cabeçalhos de proxy (`ProxyHookConfig`)
|
|
201
124
|
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
} from '@groundbrick/sveltekit-adapter/consent';
|
|
211
|
-
```
|
|
125
|
+
| Opção | Padrão | Descrição |
|
|
126
|
+
| --- | --- | --- |
|
|
127
|
+
| `trustForwardedHeaders` | `true` | Aplica os cabeçalhos encaminhados |
|
|
128
|
+
| `forwardedHostHeader` | `'x-forwarded-host'` | Cabeçalho que substitui `host` |
|
|
129
|
+
| `forwardedProtoHeader` | `'x-forwarded-proto'` | Cabeçalho do protocolo (usa o primeiro valor) |
|
|
130
|
+
| `overrideOrigin` | `true` | Substitui um `origin` existente quando há host e protocolo |
|
|
131
|
+
|
|
132
|
+
### Erros (`ErrorHandlerConfig`)
|
|
212
133
|
|
|
213
|
-
|
|
134
|
+
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
135
|
|
|
215
|
-
|
|
136
|
+
## ApiClient
|
|
216
137
|
|
|
217
138
|
```typescript
|
|
218
|
-
import { createApiClient } from '@groundbrick/sveltekit-adapter';
|
|
139
|
+
import { createApiClient } from '@groundbrick/sveltekit-adapter/client';
|
|
219
140
|
|
|
220
|
-
const
|
|
141
|
+
export const apiClient = createApiClient({
|
|
221
142
|
baseUrl: 'https://api.example.com',
|
|
222
143
|
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'
|
|
233
|
-
});
|
|
234
|
-
|
|
235
|
-
// Request with auth token
|
|
236
|
-
const profile = await client.get('/profile', {
|
|
237
|
-
headers: { Authorization: 'Bearer token' }
|
|
144
|
+
retries: 3,
|
|
145
|
+
defaultHeaders: { 'X-App-Version': '1.0.0' }
|
|
238
146
|
});
|
|
239
|
-
```
|
|
240
147
|
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
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
|
-
});
|
|
148
|
+
const users = await apiClient.get('/users');
|
|
149
|
+
await apiClient.post('/users', { name: 'John Doe' });
|
|
150
|
+
await apiClient.requestWithRetry('/users', { method: 'GET' });
|
|
274
151
|
```
|
|
275
152
|
|
|
276
|
-
|
|
153
|
+
| Método | Assinatura |
|
|
154
|
+
| --- | --- |
|
|
155
|
+
| `get` | `get<T>(endpoint, options?): Promise<T>` |
|
|
156
|
+
| `post`, `put`, `patch` | `post<T>(endpoint, data?, options?): Promise<T>` |
|
|
157
|
+
| `delete` | `delete<T>(endpoint, options?): Promise<T>` |
|
|
158
|
+
| `requestWithRetry` | `requestWithRetry<T>(endpoint, options?, retries?): Promise<T>` |
|
|
277
159
|
|
|
278
|
-
|
|
160
|
+
- Configuração: `baseUrl`, `timeout` (padrão 10000 ms), `retries` (padrão 3, usado por `requestWithRetry`) e `defaultHeaders`.
|
|
161
|
+
- Opções por pedido: as de `RequestInit`, `timeout` e `expectedStatuses` (status que não são registados como aviso).
|
|
162
|
+
- Envia cookies (`credentials: 'include'`). O corpo é enviado como JSON, ou sem alterações quando é `FormData`.
|
|
163
|
+
- Uma resposta HTTP de erro não lança: é devolvida com `error.message` e `error.status`.
|
|
164
|
+
- JSON inválido é convertido num erro; um corpo vazio resulta em `{ success, status }`.
|
|
165
|
+
- Uma falha de rede ou um timeout lança `Error`.
|
|
166
|
+
- `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
167
|
|
|
280
|
-
|
|
168
|
+
## ApiWrapper
|
|
281
169
|
|
|
282
|
-
|
|
283
|
-
|
|
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
|
|
170
|
+
```typescript
|
|
171
|
+
import { createApiWrapper } from '@groundbrick/sveltekit-adapter/client';
|
|
287
172
|
|
|
288
|
-
|
|
173
|
+
const api = createApiWrapper(apiClient);
|
|
174
|
+
const result = await api.get<User[]>('/users', { expectedStatuses: [404] });
|
|
289
175
|
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
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
|
-
});
|
|
176
|
+
if (result.success) {
|
|
177
|
+
console.log(result.data);
|
|
178
|
+
} else {
|
|
179
|
+
console.error(result.error?.code, result.error?.status, result.error?.details);
|
|
180
|
+
}
|
|
308
181
|
```
|
|
309
182
|
|
|
310
|
-
|
|
183
|
+
Métodos: `get`, `post`, `put`, `patch`, `delete`, `call(apiCall, options?)` e `parallel(apiCalls, options?)`, que devolve os resultados em `data`, ou o primeiro erro. A API tem de responder com `{ success, data?, error?, message? }`; `success: false` é acompanhado de `error`.
|
|
311
184
|
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
185
|
+
| Opção | Padrão | Descrição |
|
|
186
|
+
| --- | --- | --- |
|
|
187
|
+
| `showLoading` | `true` | Atualiza `apiStore.loading` |
|
|
188
|
+
| `showErrorNotification` | `true` | Mostra uma notificação de erro no browser |
|
|
189
|
+
| `customErrorMessage` | - | Mensagem da notificação de erro |
|
|
190
|
+
| `expectedStatuses` | - | Status não registados como aviso (aplica-se a `get`) |
|
|
191
|
+
| `skipAuthHandling` | `false` | Não faz logout nem redirect |
|
|
316
192
|
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
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
|
-
```
|
|
193
|
+
- 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.
|
|
194
|
+
- 403: mostra a notificação e mantém a sessão, exceto com um dos `sessionInvalidCodes` da instância, tratado com logout e redirect. Nenhum código por omissão: `createApiWrapper(apiClient, { sessionInvalidCodes: ['WRONG_TENANT'] })`.
|
|
195
|
+
- Os erros são devolvidos como `{ success: false, error: { message, status, code, details } }`.
|
|
332
196
|
|
|
333
|
-
`
|
|
197
|
+
`authErrorHandler` e `handleAuthError(error)` expõem o logout e redirect; `error.redirectTo` altera o destino.
|
|
334
198
|
|
|
335
|
-
##
|
|
199
|
+
## Stores
|
|
336
200
|
|
|
337
|
-
|
|
201
|
+
| Export | Descrição |
|
|
202
|
+
| --- | --- |
|
|
203
|
+
| `authStore` | `isAuthenticated`, `user`, `loading`, `error`; métodos `login(user)`, `logout()`, `setLoading`, `setError`, `initialize` (sem efeito), `initializeFromJwt`, `initializeFromToken` |
|
|
204
|
+
| `apiStore` | `loading`, `error`, `lastRequest`; métodos `setLoading`, `setError`, `setLastRequest` |
|
|
205
|
+
| `currentUser`, `isLoading`, `currentError` | Stores derivadas |
|
|
206
|
+
| `initializeFromJwt(payload)` | Preenche a `authStore` com o payload |
|
|
207
|
+
| `initializeFromToken(token)` | Descodifica e preenche; devolve `false` se inválido ou expirado |
|
|
208
|
+
| `initializeAuth(apiClient)` | Obsoleta: usar `initializeFromJwt`. Chama `GET /auth/me` e guarda a resposta como utilizador |
|
|
209
|
+
| `initializeStores()` | Chama `authStore.initialize()` no browser |
|
|
210
|
+
| `clearErrors()` | Limpa os erros das duas stores |
|
|
338
211
|
|
|
339
|
-
```
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
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
|
-
});
|
|
212
|
+
```svelte
|
|
213
|
+
<script lang="ts">
|
|
214
|
+
import { authStore, apiStore, currentUser } from '@groundbrick/sveltekit-adapter/client';
|
|
215
|
+
</script>
|
|
354
216
|
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
label: 'signup'
|
|
360
|
-
});
|
|
217
|
+
{#if $authStore.isAuthenticated}
|
|
218
|
+
<h1>{$currentUser?.name}</h1>
|
|
219
|
+
{/if}
|
|
220
|
+
{#if $apiStore.loading}<p>Loading...</p>{/if}
|
|
361
221
|
```
|
|
362
222
|
|
|
363
|
-
|
|
223
|
+
## JWT
|
|
364
224
|
|
|
365
|
-
|
|
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
|
-
```
|
|
225
|
+
`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
226
|
|
|
390
|
-
|
|
227
|
+
`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
228
|
|
|
392
|
-
|
|
229
|
+
## Notificações
|
|
393
230
|
|
|
394
231
|
```typescript
|
|
395
|
-
import {
|
|
232
|
+
import { showSuccess, showError, clearAllNotifications } from '@groundbrick/sveltekit-adapter/client';
|
|
396
233
|
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
234
|
+
const id = showSuccess('Saved', { title: 'Success', duration: 3000, persistent: true });
|
|
235
|
+
showError('Something went wrong');
|
|
236
|
+
clearAllNotifications();
|
|
237
|
+
```
|
|
401
238
|
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
});
|
|
239
|
+
- `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.
|
|
240
|
+
- `removeNotification(id)`, `clearNotificationsByType(type)`, `clearNonPersistentNotifications()` e `clearAllNotifications()` removem notificações.
|
|
241
|
+
- Stores: `notificationStore`, `notifications`, `errorNotifications`, `successNotifications`, `warningNotifications`, `infoNotifications`, `latestError`, `latestSuccess`, `hasNotifications`, `hasErrors`, `hasSuccess`.
|
|
242
|
+
- `useNavigationNotificationClear()`, no layout raiz, limpa as não persistentes ao navegar; `useClearNotificationsOnMount()` limpa-as quando é chamada.
|
|
407
243
|
|
|
408
|
-
|
|
409
|
-
authStore.logout();
|
|
244
|
+
A app fornece o componente que mostra `$notifications`.
|
|
410
245
|
|
|
411
|
-
|
|
412
|
-
if ($currentUser?.roles?.includes('admin')) {
|
|
413
|
-
// Show admin content
|
|
414
|
-
}
|
|
415
|
-
```
|
|
416
|
-
|
|
417
|
-
### API Store
|
|
246
|
+
## Cookies de autenticação
|
|
418
247
|
|
|
419
248
|
```typescript
|
|
420
|
-
import {
|
|
421
|
-
|
|
422
|
-
// Loading states
|
|
423
|
-
$: if ($isLoading) {
|
|
424
|
-
// Show spinner
|
|
425
|
-
}
|
|
249
|
+
import { createAuthCookieHelper, isSecureRequest, resolveCookieDomain } from '@groundbrick/sveltekit-adapter/cookies';
|
|
426
250
|
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
251
|
+
const cookie = (event: RequestEvent) =>
|
|
252
|
+
createAuthCookieHelper({
|
|
253
|
+
tokenKey: 'session',
|
|
254
|
+
isProduction: process.env.NODE_ENV === 'production',
|
|
255
|
+
secure: isSecureRequest(event),
|
|
256
|
+
sameSite: 'lax',
|
|
257
|
+
resolveDomain: (hostname) => resolveCookieDomain(hostname, process.env.COOKIE_DOMAIN)
|
|
258
|
+
});
|
|
432
259
|
|
|
433
|
-
|
|
434
|
-
|
|
260
|
+
cookie(event).set(event.cookies, event.url.hostname, token, 3600);
|
|
261
|
+
cookie(event).get(event.cookies);
|
|
262
|
+
cookie(event).delete(event.cookies, event.url.hostname);
|
|
435
263
|
```
|
|
436
264
|
|
|
437
|
-
|
|
265
|
+
| Opção | Padrão | Descrição |
|
|
266
|
+
| --- | --- | --- |
|
|
267
|
+
| `isProduction` | obrigatória | Define os padrões de `secure` e `sameSite` |
|
|
268
|
+
| `tokenKey` | `'auth_token'` | Nome do cookie |
|
|
269
|
+
| `resolveDomain` | cookie host-only | Domínio a partir do hostname |
|
|
270
|
+
| `secure` | `isProduction` | Flag `secure` |
|
|
271
|
+
| `sameSite` | `strict` em produção, `lax` fora dela | Atributo `sameSite` |
|
|
438
272
|
|
|
439
|
-
|
|
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
|
-
});
|
|
273
|
+
Os cookies usam `path: '/'` e `httpOnly: true`. O helper tem ainda `setNamed`, `deleteNamed`, `getDeleteOptions` e `getHookCookieOptions`. O módulo exporta também `createAuthCookieOptions`.
|
|
464
274
|
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
275
|
+
- As opções de escrita e de remoção têm de coincidir.
|
|
276
|
+
- `isSecureRequest(event, header?)` usa o primeiro valor de `x-forwarded-proto` e, na sua ausência, `event.url.protocol`.
|
|
277
|
+
- `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
278
|
|
|
469
|
-
|
|
279
|
+
## Consentimento e analytics
|
|
470
280
|
|
|
471
281
|
```svelte
|
|
472
|
-
<script>
|
|
473
|
-
import {
|
|
474
|
-
import
|
|
475
|
-
|
|
476
|
-
// Enable auto-clearing
|
|
477
|
-
useNavigationNotificationClear();
|
|
478
|
-
</script>
|
|
282
|
+
<script lang="ts">
|
|
283
|
+
import { CookieConsent, GDPR_CONFIG } from '@groundbrick/sveltekit-adapter/consent';
|
|
284
|
+
import { GoogleAnalytics } from '@groundbrick/sveltekit-adapter/analytics';
|
|
479
285
|
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
</main>
|
|
286
|
+
let { children } = $props();
|
|
287
|
+
</script>
|
|
483
288
|
|
|
484
|
-
|
|
485
|
-
<
|
|
289
|
+
{@render children()}
|
|
290
|
+
<GoogleAnalytics measurementId="G-XXXXXXXXXX" />
|
|
291
|
+
<CookieConsent config={GDPR_CONFIG} />
|
|
486
292
|
```
|
|
487
293
|
|
|
488
|
-
|
|
294
|
+
`consent` exporta `ConsentService`, `CookieConsent`, `DEFAULT_CONSENT_CONFIG`, `GDPR_CONFIG`, `CCPA_CONFIG` e `GENERIC_CONFIG`.
|
|
489
295
|
|
|
490
|
-
|
|
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
|
-
});
|
|
497
|
-
|
|
498
|
-
// Logs automáticos no console/arquivo
|
|
499
|
-
// INFO: Incoming request { method: 'GET', url: '/api/users', duration: 245 }
|
|
500
|
-
```
|
|
296
|
+
`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`.
|
|
501
297
|
|
|
502
|
-
|
|
503
|
-
```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
|
-
```
|
|
510
|
-
|
|
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
|
-
});
|
|
521
|
-
```
|
|
298
|
+
## Tracking
|
|
522
299
|
|
|
523
|
-
- **Performance tracking**: Tracking de performance automático
|
|
524
300
|
```typescript
|
|
525
|
-
|
|
526
|
-
const startTime = Date.now();
|
|
527
|
-
await apiClient.get('/heavy-endpoint');
|
|
528
|
-
// Log: Request completed { duration: 1247ms, status: 200 }
|
|
301
|
+
import { TrackingService } from '@groundbrick/sveltekit-adapter/tracking';
|
|
529
302
|
|
|
530
|
-
|
|
531
|
-
|
|
303
|
+
const tracking = TrackingService.getInstance();
|
|
304
|
+
tracking.initialize({ h2b2Url: 'https://events.example.com', batchSize: 5, flushInterval: 10000 });
|
|
305
|
+
await tracking.trackEvent({ event_name: 'order_created', properties: { orderId: 1 } });
|
|
532
306
|
```
|
|
533
307
|
|
|
534
|
-
|
|
308
|
+
- `initialize` envia `POST {h2b2Url}/tracking/sessions`; cada evento é enviado para `POST {h2b2Url}/tracking/events`.
|
|
309
|
+
- A fila é enviada ao atingir `batchSize` (padrão 5), a cada `flushInterval` ms (padrão 10000) e em `beforeunload`. Um pedido rejeitado volta à fila.
|
|
310
|
+
- O id do visitante fica em `localStorage` (`h2b2_visitor_id`). `h2b2_tracking_optout` com o valor `true` impede novos eventos.
|
|
311
|
+
- Métodos: `trackEvent`, `identifyUser`, `clearUser`, `getSessionId`, `flush`, `isEnabled`, `getState` e `destroy`.
|
|
535
312
|
|
|
536
|
-
|
|
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.
|
|
313
|
+
## Sentry
|
|
542
314
|
|
|
543
315
|
```bash
|
|
544
316
|
pnpm add @sentry/sveltekit
|
|
@@ -550,17 +322,15 @@ import type { HandleClientError } from '@sveltejs/kit';
|
|
|
550
322
|
import { env } from '$env/dynamic/public';
|
|
551
323
|
import { initSentry, handleErrorWithSentry } from '@groundbrick/sveltekit-adapter/sentry';
|
|
552
324
|
|
|
553
|
-
export const init = () =>
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
const baseHandleError: HandleClientError = ({ error }) => {
|
|
561
|
-
console.error(error);
|
|
562
|
-
return { message: 'Ocorreu um erro inesperado.' };
|
|
325
|
+
export const init = async () => {
|
|
326
|
+
await initSentry({
|
|
327
|
+
dsn: env.PUBLIC_SENTRY_DSN,
|
|
328
|
+
environment: env.PUBLIC_SENTRY_ENVIRONMENT,
|
|
329
|
+
tracesSampleRate: env.PUBLIC_SENTRY_TRACES_SAMPLE_RATE
|
|
330
|
+
});
|
|
563
331
|
};
|
|
332
|
+
|
|
333
|
+
const baseHandleError: HandleClientError = () => ({ message: 'Ocorreu um erro inesperado.' });
|
|
564
334
|
export const handleError = handleErrorWithSentry(baseHandleError);
|
|
565
335
|
```
|
|
566
336
|
|
|
@@ -568,64 +338,19 @@ export const handleError = handleErrorWithSentry(baseHandleError);
|
|
|
568
338
|
// src/hooks.server.ts
|
|
569
339
|
import { sequence } from '@sveltejs/kit/hooks';
|
|
570
340
|
import { env } from '$env/dynamic/public';
|
|
341
|
+
import { createSvelteKitHooks } from '@groundbrick/sveltekit-adapter/hooks';
|
|
571
342
|
import { initSentry, sentryHandle, handleErrorWithSentry } from '@groundbrick/sveltekit-adapter/sentry';
|
|
572
343
|
|
|
573
|
-
|
|
344
|
+
const { hooks, handleError: baseHandleError } = createSvelteKitHooks();
|
|
345
|
+
|
|
346
|
+
export const init = async () => {
|
|
347
|
+
await initSentry({ dsn: env.PUBLIC_SENTRY_DSN });
|
|
348
|
+
};
|
|
574
349
|
export const handle = sequence(sentryHandle(), ...hooks);
|
|
575
350
|
export const handleError = handleErrorWithSentry(baseHandleError);
|
|
576
351
|
```
|
|
577
352
|
|
|
578
|
-
|
|
579
|
-
(
|
|
580
|
-
|
|
581
|
-
|
|
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).
|
|
353
|
+
- O módulo requer `@sentry/sveltekit` instalado. Só é carregado com um DSN; sem DSN os exports funcionam como pass-through.
|
|
354
|
+
- `initSentry` aceita `dsn`, `environment`, `release` e `tracesSampleRate` (padrão 0.1). Devolve se o Sentry está ativo e não lança.
|
|
355
|
+
- `captureException`, `captureMessage` e `flushSentry` não têm efeito sem Sentry; `isSentryEnabled` indica se está ativo.
|
|
356
|
+
- `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.
|