@akinon/next 2.0.99-beta.0 → 2.0.99-rc.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.
@@ -0,0 +1,265 @@
1
+ 'use client';
2
+
3
+ import { useEffect, useState } from 'react';
4
+
5
+ /**
6
+ * Runtime access to public (`NEXT_PUBLIC_*`) environment variables from Client
7
+ * Components.
8
+ *
9
+ * `process.env.NEXT_PUBLIC_*` is inlined at *build* time, so on platforms where
10
+ * the build has no environment (e.g. Akinon Cloud Commerce) it resolves to
11
+ * `undefined` in the browser. These helpers read the value from the server
12
+ * runtime through the `/api/client-env` route handler instead
13
+ * (`@akinon/next/api/client-env`).
14
+ *
15
+ * Always pass the full variable name, including the `NEXT_PUBLIC_` prefix:
16
+ *
17
+ * ```tsx
18
+ * // inside a Client Component
19
+ * const { value, isLoading } = useClientEnv('NEXT_PUBLIC_MAP_API_KEY');
20
+ *
21
+ * // imperative (event handlers, third-party init, ...)
22
+ * const key = await getClientEnv('NEXT_PUBLIC_MAP_API_KEY');
23
+ * ```
24
+ *
25
+ * Server Components do not need this — read the value with computed access
26
+ * (`process.env['NEXT_PUBLIC_MAP_API_KEY']`) so it is not build-time inlined.
27
+ */
28
+
29
+ const ENDPOINT = '/api/client-env';
30
+
31
+ // Shared across every caller so each variable is fetched at most once per page
32
+ // load, no matter how many components ask for it.
33
+ const cache = new Map<string, string | null>();
34
+ const inflight = new Map<string, Promise<string | null>>();
35
+
36
+ function request(names: string[]): void {
37
+ const pending = names.filter(
38
+ (name) => !cache.has(name) && !inflight.has(name)
39
+ );
40
+
41
+ if (pending.length === 0) return;
42
+
43
+ const query = pending
44
+ .map((name) => `env=${encodeURIComponent(name)}`)
45
+ .join('&');
46
+
47
+ const response = fetch(`${ENDPOINT}?${query}`, {
48
+ headers: { Accept: 'application/json' }
49
+ })
50
+ .then((res) => {
51
+ if (!res.ok) {
52
+ throw new Error(`Failed to load client env (status ${res.status}).`);
53
+ }
54
+ return res.json() as Promise<Record<string, string | null>>;
55
+ })
56
+ .then((data) => {
57
+ pending.forEach((name) => cache.set(name, data?.[name] ?? null));
58
+ });
59
+
60
+ // One in-flight entry per name so concurrent callers dedupe. On failure the
61
+ // entry is cleared (not cached) so a later render can retry.
62
+ pending.forEach((name) => {
63
+ inflight.set(
64
+ name,
65
+ response
66
+ .then(() => cache.get(name) ?? null)
67
+ .finally(() => inflight.delete(name))
68
+ );
69
+ });
70
+ }
71
+
72
+ function resolve(name: string): Promise<string | null> {
73
+ if (cache.has(name)) return Promise.resolve(cache.get(name) ?? null);
74
+ return inflight.get(name) ?? Promise.resolve(null);
75
+ }
76
+
77
+ /**
78
+ * Read a single public (`NEXT_PUBLIC_*`) environment variable at runtime,
79
+ * outside React (event handlers, third-party SDK init, …). Cached and
80
+ * deduplicated across callers.
81
+ *
82
+ * @param name - Full variable name, including the `NEXT_PUBLIC_` prefix.
83
+ * @returns The runtime value, or `null` when the variable is unset. Rejects if
84
+ * the request fails, so wrap direct calls in `try`/`catch`. A failed request is
85
+ * not cached — a later call retries.
86
+ *
87
+ * @example
88
+ * ```tsx
89
+ * import { getClientEnv } from '@akinon/next/hooks'
90
+ *
91
+ * const handleShare = async () => {
92
+ * const baseUrl = await getClientEnv('NEXT_PUBLIC_URL')
93
+ * navigator.clipboard.writeText(`${baseUrl}/product/123`)
94
+ * }
95
+ * ```
96
+ */
97
+ export async function getClientEnv(name: string): Promise<string | null> {
98
+ request([name]);
99
+ return resolve(name);
100
+ }
101
+
102
+ /**
103
+ * Read several public (`NEXT_PUBLIC_*`) environment variables at runtime in a
104
+ * single request, outside React.
105
+ *
106
+ * @param names - Full variable names, each including the `NEXT_PUBLIC_` prefix.
107
+ * @returns A `{ [name]: value | null }` map. Rejects if the request fails.
108
+ *
109
+ * @example
110
+ * ```ts
111
+ * import { getClientEnvs } from '@akinon/next/hooks'
112
+ *
113
+ * const env = await getClientEnvs(['NEXT_PUBLIC_GTM_KEY', 'NEXT_PUBLIC_URL'])
114
+ * // env['NEXT_PUBLIC_URL']
115
+ * ```
116
+ */
117
+ export async function getClientEnvs(
118
+ names: string[]
119
+ ): Promise<Record<string, string | null>> {
120
+ request(names);
121
+ const values = await Promise.all(names.map((name) => resolve(name)));
122
+ return names.reduce<Record<string, string | null>>((acc, name, index) => {
123
+ acc[name] = values[index];
124
+ return acc;
125
+ }, {});
126
+ }
127
+
128
+ /**
129
+ * Read a single public (`NEXT_PUBLIC_*`) environment variable at runtime from a
130
+ * Client Component.
131
+ *
132
+ * @param name - Full variable name, including the `NEXT_PUBLIC_` prefix.
133
+ * @returns `{ value, isLoading, error }`. `value` is `null` while loading, when
134
+ * the variable is unset, or on failure.
135
+ *
136
+ * @example
137
+ * ```tsx
138
+ * 'use client'
139
+ * import { useClientEnv } from '@akinon/next/hooks'
140
+ *
141
+ * export const StoreMap = () => {
142
+ * const { value: mapApiKey, isLoading } = useClientEnv('NEXT_PUBLIC_MAP_API_KEY')
143
+ *
144
+ * if (isLoading) return <Spinner />
145
+ * if (!mapApiKey) return null
146
+ *
147
+ * return <GoogleMap apiKey={mapApiKey} />
148
+ * }
149
+ * ```
150
+ */
151
+ export function useClientEnv(name: string) {
152
+ const [value, setValue] = useState<string | null>(
153
+ () => cache.get(name) ?? null
154
+ );
155
+ const [isLoading, setIsLoading] = useState(() => !cache.has(name));
156
+ const [error, setError] = useState<Error | null>(null);
157
+
158
+ useEffect(() => {
159
+ let active = true;
160
+
161
+ if (cache.has(name)) {
162
+ setValue(cache.get(name) ?? null);
163
+ setIsLoading(false);
164
+ setError(null);
165
+ return;
166
+ }
167
+
168
+ setIsLoading(true);
169
+ setError(null);
170
+
171
+ getClientEnv(name)
172
+ .then((resolved) => {
173
+ if (!active) return;
174
+ setValue(resolved);
175
+ setIsLoading(false);
176
+ })
177
+ .catch((err) => {
178
+ if (!active) return;
179
+ setError(err instanceof Error ? err : new Error(String(err)));
180
+ setIsLoading(false);
181
+ });
182
+
183
+ return () => {
184
+ active = false;
185
+ };
186
+ }, [name]);
187
+
188
+ return { value, isLoading, error };
189
+ }
190
+
191
+ /**
192
+ * Read several public (`NEXT_PUBLIC_*`) environment variables at runtime in a
193
+ * single request from a Client Component.
194
+ *
195
+ * @param names - Full variable names, each including the `NEXT_PUBLIC_` prefix.
196
+ * @returns `{ values, isLoading, error }` where `values` is a
197
+ * `{ [name]: value | null }` map.
198
+ *
199
+ * @example
200
+ * ```tsx
201
+ * 'use client'
202
+ * import { useClientEnvs } from '@akinon/next/hooks'
203
+ *
204
+ * const { values, isLoading } = useClientEnvs([
205
+ * 'NEXT_PUBLIC_GTM_KEY',
206
+ * 'NEXT_PUBLIC_URL'
207
+ * ])
208
+ *
209
+ * const gtmKey = values['NEXT_PUBLIC_GTM_KEY']
210
+ * ```
211
+ */
212
+ export function useClientEnvs(names: string[]) {
213
+ // Stable serialization so the effect re-runs only when the set changes, not
214
+ // on every render (a new array identity would otherwise loop it forever).
215
+ const key = names.join(',');
216
+
217
+ const [values, setValues] = useState<Record<string, string | null>>(() => {
218
+ const initial: Record<string, string | null> = {};
219
+ names.forEach((name) => {
220
+ if (cache.has(name)) initial[name] = cache.get(name) ?? null;
221
+ });
222
+ return initial;
223
+ });
224
+ const [isLoading, setIsLoading] = useState(
225
+ () => !names.every((name) => cache.has(name))
226
+ );
227
+ const [error, setError] = useState<Error | null>(null);
228
+
229
+ useEffect(() => {
230
+ let active = true;
231
+ const list = key ? key.split(',') : [];
232
+
233
+ if (list.every((name) => cache.has(name))) {
234
+ const resolved: Record<string, string | null> = {};
235
+ list.forEach((name) => (resolved[name] = cache.get(name) ?? null));
236
+ setValues(resolved);
237
+ setIsLoading(false);
238
+ setError(null);
239
+ return;
240
+ }
241
+
242
+ setIsLoading(true);
243
+ setError(null);
244
+
245
+ getClientEnvs(list)
246
+ .then((resolved) => {
247
+ if (!active) return;
248
+ setValues(resolved);
249
+ setIsLoading(false);
250
+ })
251
+ .catch((err) => {
252
+ if (!active) return;
253
+ setError(err instanceof Error ? err : new Error(String(err)));
254
+ setIsLoading(false);
255
+ });
256
+
257
+ return () => {
258
+ active = false;
259
+ };
260
+ // `key` is the stable serialization of `names`.
261
+ // eslint-disable-next-line react-hooks/exhaustive-deps
262
+ }, [key]);
263
+
264
+ return { values, isLoading, error };
265
+ }