@djangocfg/monitor 2.1.331 → 2.1.332

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,10 +1,10 @@
1
1
  // AUTO-GENERATED by django_generator / ts_extras.wrapper
2
2
  // Group barrel. DO NOT EDIT — re-run `make gen`.
3
3
 
4
- // Wrapper class + per-group SDK re-exports
5
- export { API, type APIOptions, } from './api';
4
+ // Wrapper class + per-group SDK re-exports + global auth.
5
+ export { API, type APIOptions, auth, } from './api';
6
6
 
7
- // Shared utilities (storage / errors / logger / validation events)
7
+ // Shared utilities.
8
8
  export {
9
9
  type StorageAdapter,
10
10
  LocalStorageAdapter,
@@ -25,5 +25,5 @@ export {
25
25
  type ValidationErrorEvent,
26
26
  } from '../helpers';
27
27
 
28
- // Generated artifacts (Hey API)
28
+ // Generated artifacts (Hey API).
29
29
  export type * from '../types.gen';
@@ -14,3 +14,6 @@ import type { ClientOptions as ClientOptions2 } from './types.gen';
14
14
  export type CreateClientConfig<T extends ClientOptions = ClientOptions2> = (override?: Config<ClientOptions & T>) => Config<Required<ClientOptions> & T>;
15
15
 
16
16
  export const client = createClient(createConfig<ClientOptions2>({ baseUrl: 'http://localhost:8000' }));
17
+
18
+ // auto-init: load auth interceptor
19
+ import './helpers/auth';
@@ -0,0 +1,223 @@
1
+ // AUTO-GENERATED by django_generator / ts_extras.wrapper
2
+ // Global auth store. ONE source of truth for token / API key / locale /
3
+ // baseUrl. Installs the request interceptor as a side-effect on import.
4
+ // DO NOT EDIT — re-run `make gen`.
5
+
6
+ import { client } from '../client.gen';
7
+
8
+ const ACCESS_KEY = 'cfg.access_token';
9
+ const REFRESH_KEY = 'cfg.refresh_token';
10
+ const API_KEY_KEY = 'cfg.api_key';
11
+
12
+ const isBrowser = typeof window !== 'undefined';
13
+
14
+ export type StorageMode = 'localStorage' | 'cookie';
15
+
16
+ // ── Storage backends (browser-only; server-side reads return null) ─────────
17
+
18
+ interface KVStore {
19
+ get(key: string): string | null;
20
+ set(key: string, value: string | null): void;
21
+ }
22
+
23
+ const localStorageBackend: KVStore = {
24
+ get(key) {
25
+ if (!isBrowser) return null;
26
+ try { return window.localStorage.getItem(key); } catch { return null; }
27
+ },
28
+ set(key, value) {
29
+ if (!isBrowser) return;
30
+ try {
31
+ if (value === null) window.localStorage.removeItem(key);
32
+ else window.localStorage.setItem(key, value);
33
+ } catch {}
34
+ },
35
+ };
36
+
37
+ /** 30 days, matches typical refresh-token lifetime. */
38
+ const COOKIE_MAX_AGE = 60 * 60 * 24 * 30;
39
+
40
+ const cookieBackend: KVStore = {
41
+ get(key) {
42
+ if (!isBrowser) return null;
43
+ try {
44
+ const re = new RegExp(`(?:^|;\\s*)${encodeURIComponent(key)}=([^;]*)`);
45
+ const m = document.cookie.match(re);
46
+ return m ? decodeURIComponent(m[1]) : null;
47
+ } catch { return null; }
48
+ },
49
+ set(key, value) {
50
+ if (!isBrowser) return;
51
+ try {
52
+ const k = encodeURIComponent(key);
53
+ const secure = window.location.protocol === 'https:' ? '; Secure' : '';
54
+ if (value === null) {
55
+ document.cookie = `${k}=; Path=/; Max-Age=0; SameSite=Lax${secure}`;
56
+ } else {
57
+ const v = encodeURIComponent(value);
58
+ document.cookie = `${k}=${v}; Path=/; Max-Age=${COOKIE_MAX_AGE}; SameSite=Lax${secure}`;
59
+ }
60
+ } catch {}
61
+ },
62
+ };
63
+
64
+ let _storage: KVStore = localStorageBackend;
65
+ let _storageMode: StorageMode = 'localStorage';
66
+
67
+ /** Detect locale from `NEXT_LOCALE` cookie or `navigator.language`. */
68
+ function detectLocale(): string | null {
69
+ try {
70
+ if (typeof document !== 'undefined') {
71
+ const m = document.cookie.match(/(?:^|;\s*)NEXT_LOCALE=([^;]*)/);
72
+ if (m) return decodeURIComponent(m[1]);
73
+ }
74
+ if (typeof navigator !== 'undefined' && navigator.language) {
75
+ return navigator.language;
76
+ }
77
+ } catch {}
78
+ return null;
79
+ }
80
+
81
+ /** Default baseUrl from `NEXT_PUBLIC_API_URL` (empty for static builds). */
82
+ function defaultBaseUrl(): string {
83
+ try {
84
+ if (typeof process !== 'undefined' && process.env) {
85
+ if (process.env.NEXT_PUBLIC_STATIC_BUILD === 'true') return '';
86
+ return process.env.NEXT_PUBLIC_API_URL || '';
87
+ }
88
+ } catch {}
89
+ return '';
90
+ }
91
+
92
+ /** Default API key fallback from `NEXT_PUBLIC_API_KEY`. */
93
+ function defaultApiKey(): string | null {
94
+ try {
95
+ if (typeof process !== 'undefined' && process.env?.NEXT_PUBLIC_API_KEY) {
96
+ return process.env.NEXT_PUBLIC_API_KEY;
97
+ }
98
+ } catch {}
99
+ return null;
100
+ }
101
+
102
+ // ── In-memory overrides (win over storage / env) ───────────────────────────
103
+ let _localeOverride: string | null = null;
104
+ let _apiKeyOverride: string | null = null;
105
+ let _baseUrlOverride: string | null = null;
106
+ let _withCredentials = true;
107
+ let _onUnauthorized: ((response: Response) => void) | null = null;
108
+
109
+ /**
110
+ * Global auth/config store. All getters read live state every call —
111
+ * the interceptor below uses these to attach headers per-request.
112
+ *
113
+ * Default storage backend is `localStorage`. Switch to cookies (e.g.
114
+ * for Next.js SSR cookie access) via `auth.setStorageMode('cookie')`
115
+ * early in the app bootstrap.
116
+ *
117
+ * @example
118
+ * import { auth } from '@your/api';
119
+ *
120
+ * // After login
121
+ * auth.setToken(jwt);
122
+ * auth.setRefreshToken(refresh);
123
+ *
124
+ * // After logout
125
+ * auth.clearTokens();
126
+ *
127
+ * // Switch to cookie storage (call once during app init)
128
+ * auth.setStorageMode('cookie');
129
+ */
130
+ export const auth = {
131
+ // ── Storage mode ──────────────────────────────────────────────────
132
+ getStorageMode(): StorageMode { return _storageMode; },
133
+ /**
134
+ * Switch the storage backend. Existing values in the *previous*
135
+ * backend are NOT migrated — set fresh values after switching.
136
+ */
137
+ setStorageMode(mode: StorageMode): void {
138
+ _storageMode = mode;
139
+ _storage = mode === 'cookie' ? cookieBackend : localStorageBackend;
140
+ },
141
+
142
+ // ── Bearer token ──────────────────────────────────────────────────
143
+ getToken(): string | null { return _storage.get(ACCESS_KEY); },
144
+ setToken(token: string | null): void { _storage.set(ACCESS_KEY, token); },
145
+ getRefreshToken(): string | null { return _storage.get(REFRESH_KEY); },
146
+ setRefreshToken(token: string | null): void { _storage.set(REFRESH_KEY, token); },
147
+ clearTokens(): void { _storage.set(ACCESS_KEY, null); _storage.set(REFRESH_KEY, null); },
148
+ isAuthenticated(): boolean { return _storage.get(ACCESS_KEY) !== null; },
149
+
150
+ // ── API key ───────────────────────────────────────────────────────
151
+ /** In-memory API key. Falls back to storage, then NEXT_PUBLIC_API_KEY. */
152
+ getApiKey(): string | null {
153
+ return _apiKeyOverride ?? _storage.get(API_KEY_KEY) ?? defaultApiKey();
154
+ },
155
+ /** In-memory only (cleared on reload). */
156
+ setApiKey(key: string | null): void { _apiKeyOverride = key; },
157
+ /** Persist to active storage backend (localStorage or cookie). */
158
+ setApiKeyPersist(key: string | null): void {
159
+ _apiKeyOverride = key;
160
+ _storage.set(API_KEY_KEY, key);
161
+ },
162
+ clearApiKey(): void { _apiKeyOverride = null; _storage.set(API_KEY_KEY, null); },
163
+
164
+ // ── Locale ────────────────────────────────────────────────────────
165
+ /** Override locale → falls back to NEXT_LOCALE cookie / navigator.language. */
166
+ getLocale(): string | null { return _localeOverride ?? detectLocale(); },
167
+ setLocale(locale: string | null): void { _localeOverride = locale; },
168
+
169
+ // ── Base URL ──────────────────────────────────────────────────────
170
+ getBaseUrl(): string {
171
+ const url = (_baseUrlOverride ?? defaultBaseUrl());
172
+ return url.replace(/\/$/, '');
173
+ },
174
+ setBaseUrl(url: string | null): void {
175
+ _baseUrlOverride = url ? url.replace(/\/$/, '') : null;
176
+ client.setConfig({ baseUrl: this.getBaseUrl() });
177
+ },
178
+
179
+ // ── Credentials toggle (Django session/CSRF cross-origin) ─────────
180
+ getWithCredentials(): boolean { return _withCredentials; },
181
+ setWithCredentials(value: boolean): void {
182
+ _withCredentials = value;
183
+ client.setConfig({ credentials: value ? 'include' : 'same-origin' });
184
+ },
185
+
186
+ // ── 401 handler ───────────────────────────────────────────────────
187
+ /**
188
+ * Register a callback fired on every 401 response. Use this to wire
189
+ * a token-refresh flow or a forced logout. Setting `null` removes
190
+ * the handler.
191
+ */
192
+ onUnauthorized(cb: ((response: Response) => void) | null): void {
193
+ _onUnauthorized = cb;
194
+ },
195
+ };
196
+
197
+ // ── One-time client wiring (side-effect on first import) ───────────────────
198
+ client.setConfig({
199
+ baseUrl: auth.getBaseUrl(),
200
+ credentials: _withCredentials ? 'include' : 'same-origin',
201
+ });
202
+
203
+ client.interceptors.request.use((request) => {
204
+ const token = auth.getToken();
205
+ if (token) request.headers.set('Authorization', `Bearer ${token}`);
206
+
207
+ const locale = auth.getLocale();
208
+ if (locale) request.headers.set('Accept-Language', locale);
209
+
210
+ const apiKey = auth.getApiKey();
211
+ if (apiKey) request.headers.set('X-API-Key', apiKey);
212
+
213
+ return request;
214
+ });
215
+
216
+ client.interceptors.response.use((response) => {
217
+ if (response.status === 401 && _onUnauthorized) {
218
+ try { _onUnauthorized(response); } catch {}
219
+ }
220
+ return response;
221
+ });
222
+
223
+ export type Auth = typeof auth;
@@ -1,6 +1,7 @@
1
1
  // AUTO-GENERATED by django_generator / ts_extras.wrapper
2
2
  // Shared utilities barrel. DO NOT EDIT — re-run `make gen`.
3
3
 
4
+ export { auth, type Auth } from './auth';
4
5
  export {
5
6
  type StorageAdapter,
6
7
  LocalStorageAdapter,
@@ -1,21 +1,25 @@
1
1
  // AUTO-GENERATED by django_generator / ts_extras.wrapper
2
- // Top-level barrel — one singleton API per group, baseUrl from Next.js env.
2
+ // Top-level barrel — global `auth` + per-group facades.
3
3
  // DO NOT EDIT — re-run `make gen`.
4
4
 
5
- import { API as CfgMonitorAPI, LocalStorageAdapter as CfgMonitorStorage } from './_cfg_monitor';
5
+ // Side-effect: ensure auth interceptor is installed even if consumers
6
+ // only ever import this barrel (it'll also load via client.gen.ts).
7
+ import './helpers/auth';
6
8
 
7
- const isStaticBuild = process.env.NEXT_PUBLIC_STATIC_BUILD === 'true';
8
- const baseUrl = isStaticBuild ? '' : process.env.NEXT_PUBLIC_API_URL || '';
9
+ // Global auth/config store single source of truth.
10
+ export { auth, type Auth } from './helpers/auth';
9
11
 
10
- export const CfgMonitorApi = new CfgMonitorAPI(baseUrl, { storage: new CfgMonitorStorage() });
12
+ import { API as CfgMonitorAPI } from './_cfg_monitor';
11
13
 
12
- // API wrapper classes for users who need to construct their own
13
- // instance (e.g. with MemoryStorageAdapter in SSR/tests).
14
+ // Singletons for ergonomic access (`import { apiAccounts } from '@your/api'`).
15
+ // All instances share the same global `auth` store.
16
+ export const CfgMonitorApi = new CfgMonitorAPI();
17
+
18
+ // Per-group wrapper classes (e.g. for tests / SSR isolation of options).
14
19
  export { API as CfgMonitorAPI } from './_cfg_monitor';
15
20
 
16
21
  // Hey API SDK classes — one per OpenAPI tag. Lets consumers call
17
- // `Centrifugo.cfgCentrifugoAuthTokenRetrieve({...})` directly without
18
- // going through the wrapper singleton.
22
+ // `Centrifugo.cfgCentrifugoAuthTokenRetrieve({...})` directly.
19
23
 
20
24
 
21
25
  // Shared utilities (errors, storage adapters, logger).