@devopsplaybook.io/common-web 0.13.0 → 0.14.0-beta.25.5639705

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,436 @@
1
+ import {
2
+ computed,
3
+ onMounted,
4
+ onUnmounted,
5
+ ref,
6
+ type ComputedRef,
7
+ type Ref,
8
+ } from "vue";
9
+ import {
10
+ LoginCodeError,
11
+ LoginCodeService,
12
+ type LoginCodeCapabilities,
13
+ type LoginCodePollResult,
14
+ } from "../services/LoginCodeService";
15
+
16
+ export type LoginCodeStatus =
17
+ | "idle"
18
+ | "creating"
19
+ | "waiting"
20
+ | "approved"
21
+ | "expired"
22
+ | "cancelled"
23
+ | "error";
24
+
25
+ export const LOGIN_CODE_DEFAULT_POLL_INTERVAL_MS = 2000;
26
+ export const LOGIN_CODE_MAX_POLL_FAILURES = 5;
27
+ export const LOGIN_CODE_MAX_POLL_BACKOFF_MS = 30_000;
28
+
29
+ const TICK_INTERVAL_MS = 1000;
30
+ const TERMINAL_STATUSES: ReadonlySet<LoginCodeStatus> = new Set([
31
+ "approved",
32
+ "expired",
33
+ "cancelled",
34
+ "error",
35
+ ]);
36
+
37
+ export interface UseLoginCodeOptions {
38
+ service?: LoginCodeService;
39
+ onSession?: (token: string, user: unknown) => void | Promise<void>;
40
+ }
41
+
42
+ export interface UseLoginCodeResult {
43
+ status: Ref<LoginCodeStatus>;
44
+ code: Ref<string | null>;
45
+ formattedCode: ComputedRef<string | null>;
46
+ secondsUntilRefresh: ComputedRef<number | null>;
47
+ secondsUntilExpiry: ComputedRef<number | null>;
48
+ error: Ref<LoginCodeError | null>;
49
+ enabled: ComputedRef<boolean>;
50
+ available: ComputedRef<boolean>;
51
+ capabilities: Ref<LoginCodeCapabilities | null>;
52
+ session: Ref<{ token: string; user: unknown } | null>;
53
+ user: ComputedRef<unknown>;
54
+ start: () => Promise<void>;
55
+ cancel: () => Promise<void>;
56
+ retry: () => Promise<void>;
57
+ }
58
+
59
+ function parseTimestamp(value: unknown): number | null {
60
+ if (typeof value !== "string") return null;
61
+ const parsed = Date.parse(value);
62
+ return Number.isFinite(parsed) ? parsed : null;
63
+ }
64
+
65
+ function formatCode(value: string): string {
66
+ return value.match(/.{1,4}/g)?.join("-") ?? value;
67
+ }
68
+
69
+ export function useLoginCode(
70
+ options: UseLoginCodeOptions = {},
71
+ ): UseLoginCodeResult {
72
+ const service =
73
+ options.service ??
74
+ // The composable owns `onSession`; an injected service may own it instead.
75
+ new LoginCodeService();
76
+ const sessionHandler = options.onSession;
77
+
78
+ const status = ref<LoginCodeStatus>("idle");
79
+ const code = ref<string | null>(null);
80
+ const error = ref<LoginCodeError | null>(null);
81
+ const capabilities = ref<LoginCodeCapabilities | null>(null);
82
+ const session = ref<{ token: string; user: unknown } | null>(null);
83
+ const clock = ref(Date.now());
84
+ const clockOffset = ref(0);
85
+ const codeDeadline = ref<number | null>(null);
86
+ const expiryDeadline = ref<number | null>(null);
87
+
88
+ let capabilitiesPromise: Promise<LoginCodeCapabilities | null> | null = null;
89
+ let capabilitiesController: AbortController | null = null;
90
+ let inFlight: AbortController | null = null;
91
+ let requestToken: string | null = null;
92
+ let pollTimer: ReturnType<typeof setTimeout> | null = null;
93
+ let tickTimer: ReturnType<typeof setInterval> | null = null;
94
+ let failures = 0;
95
+ let polling = false;
96
+ // Two counters guard asynchronous continuations: `generation` invalidates a
97
+ // whole flow (start/cancel/unmount) and `pollAttempt` invalidates a single
98
+ // poll (pause/resume) so a stale answer can never win.
99
+ let generation = 0;
100
+ let pollAttempt = 0;
101
+
102
+ const enabled = computed(() => capabilities.value?.enabled === true);
103
+ const available = computed(() => capabilities.value?.available === true);
104
+ const formattedCode = computed(() =>
105
+ code.value ? formatCode(code.value) : null,
106
+ );
107
+ const user = computed(() => session.value?.user ?? null);
108
+
109
+ function remainingSeconds(deadline: number | null): number | null {
110
+ if (deadline === null) return null;
111
+ const serverNow = clock.value + clockOffset.value;
112
+ return Math.max(0, Math.ceil((deadline - serverNow) / 1000));
113
+ }
114
+
115
+ const secondsUntilRefresh = computed(() => remainingSeconds(codeDeadline.value));
116
+ const secondsUntilExpiry = computed(() => remainingSeconds(expiryDeadline.value));
117
+
118
+ function pollInterval(): number {
119
+ const advertised = capabilities.value?.pollIntervalMs;
120
+ return typeof advertised === "number" &&
121
+ Number.isFinite(advertised) &&
122
+ advertised > 0
123
+ ? advertised
124
+ : LOGIN_CODE_DEFAULT_POLL_INTERVAL_MS;
125
+ }
126
+
127
+ function adoptServerTime(serverTime: unknown): void {
128
+ const now = Date.now();
129
+ clock.value = now;
130
+ const parsed = parseTimestamp(serverTime);
131
+ if (parsed !== null) clockOffset.value = parsed - now;
132
+ }
133
+
134
+ function applyDeadlines(codeExpiresAt: unknown, expiresAt: unknown): void {
135
+ codeDeadline.value = parseTimestamp(codeExpiresAt);
136
+ expiryDeadline.value = parseTimestamp(expiresAt);
137
+ }
138
+
139
+ function clearPollTimer(): void {
140
+ if (pollTimer !== null) {
141
+ clearTimeout(pollTimer);
142
+ pollTimer = null;
143
+ }
144
+ }
145
+
146
+ function clearTicker(): void {
147
+ if (tickTimer !== null) {
148
+ clearInterval(tickTimer);
149
+ tickTimer = null;
150
+ }
151
+ }
152
+
153
+ function stopTimers(): void {
154
+ clearPollTimer();
155
+ clearTicker();
156
+ }
157
+
158
+ function startTicker(): void {
159
+ clearTicker();
160
+ tickTimer = setInterval(() => {
161
+ clock.value = Date.now();
162
+ }, TICK_INTERVAL_MS);
163
+ }
164
+
165
+ function abortInFlight(): void {
166
+ inFlight?.abort();
167
+ inFlight = null;
168
+ }
169
+
170
+ function abortCapabilities(): void {
171
+ capabilitiesController?.abort();
172
+ capabilitiesController = null;
173
+ }
174
+
175
+ function loadCapabilities(): Promise<LoginCodeCapabilities | null> {
176
+ if (capabilities.value) return Promise.resolve(capabilities.value);
177
+ if (capabilitiesPromise) return capabilitiesPromise;
178
+
179
+ const controller = new AbortController();
180
+ capabilitiesController = controller;
181
+ const promise = service
182
+ .capabilities({ signal: controller.signal })
183
+ .then((result) => {
184
+ capabilities.value = result;
185
+ return result;
186
+ })
187
+ .catch(() => null)
188
+ .finally(() => {
189
+ if (capabilitiesController === controller) capabilitiesController = null;
190
+ // A failed probe is retried by the next start/retry.
191
+ if (!capabilities.value) capabilitiesPromise = null;
192
+ });
193
+ capabilitiesPromise = promise;
194
+ return promise;
195
+ }
196
+
197
+ function schedulePoll(delay: number): void {
198
+ clearPollTimer();
199
+ pollTimer = setTimeout(() => {
200
+ pollTimer = null;
201
+ void poll();
202
+ }, delay);
203
+ }
204
+
205
+ async function poll(): Promise<void> {
206
+ if (status.value !== "waiting" || polling) return;
207
+ if (typeof window === "undefined") return;
208
+ if (typeof document !== "undefined" && document.visibilityState === "hidden") {
209
+ return;
210
+ }
211
+
212
+ const flow = generation;
213
+ const attempt = ++pollAttempt;
214
+ const controller = new AbortController();
215
+ inFlight = controller;
216
+ polling = true;
217
+
218
+ try {
219
+ const result = await service.poll(requestToken ?? "", {
220
+ signal: controller.signal,
221
+ });
222
+ if (flow !== generation || attempt !== pollAttempt) return;
223
+ applyPollResult(result);
224
+ } catch (caught) {
225
+ if (flow !== generation || attempt !== pollAttempt) return;
226
+ handlePollFailure(caught);
227
+ } finally {
228
+ polling = false;
229
+ if (inFlight === controller) inFlight = null;
230
+ }
231
+ }
232
+
233
+ function applyPollResult(result: LoginCodePollResult): void {
234
+ failures = 0;
235
+ adoptServerTime(result.serverTime);
236
+
237
+ switch (result.status) {
238
+ case "pending":
239
+ if (typeof result.code === "string" && result.code.length > 0) {
240
+ code.value = result.code;
241
+ }
242
+ applyDeadlines(result.codeExpiresAt, result.expiresAt);
243
+ schedulePoll(pollInterval());
244
+ return;
245
+ case "approved":
246
+ session.value = { token: result.token, user: result.user };
247
+ codeDeadline.value = null;
248
+ expiryDeadline.value = parseTimestamp(result.expiresAt);
249
+ status.value = "approved";
250
+ stopTimers();
251
+ void notifySession(result.token, result.user);
252
+ return;
253
+ case "expired":
254
+ status.value = "expired";
255
+ stopTimers();
256
+ return;
257
+ case "cancelled":
258
+ status.value = "cancelled";
259
+ stopTimers();
260
+ return;
261
+ case "failed":
262
+ error.value = new LoginCodeError("FAILED");
263
+ status.value = "error";
264
+ stopTimers();
265
+ }
266
+ }
267
+
268
+ async function notifySession(token: string, userValue: unknown): Promise<void> {
269
+ if (!sessionHandler) return;
270
+ try {
271
+ await sessionHandler(token, userValue);
272
+ } catch {
273
+ // Redemption already succeeded; a failing session writer is not a login
274
+ // failure.
275
+ }
276
+ }
277
+
278
+ function handlePollFailure(caught: unknown): void {
279
+ const failure =
280
+ caught instanceof LoginCodeError
281
+ ? caught
282
+ : new LoginCodeError("NETWORK", undefined, { retryable: true });
283
+ if (failure.code === "ABORTED") return;
284
+
285
+ failures += 1;
286
+ if (!failure.retryable || failures >= LOGIN_CODE_MAX_POLL_FAILURES) {
287
+ error.value = failure;
288
+ status.value = "error";
289
+ stopTimers();
290
+ return;
291
+ }
292
+ const backoff = Math.min(
293
+ LOGIN_CODE_MAX_POLL_BACKOFF_MS,
294
+ pollInterval() * 2 ** (failures - 1),
295
+ );
296
+ schedulePoll(backoff);
297
+ }
298
+
299
+ function pausePolling(): void {
300
+ if (status.value !== "waiting") return;
301
+ pollAttempt += 1;
302
+ abortInFlight();
303
+ stopTimers();
304
+ }
305
+
306
+ function resumePolling(): void {
307
+ if (status.value !== "waiting") return;
308
+ clock.value = Date.now();
309
+ startTicker();
310
+ void poll();
311
+ }
312
+
313
+ function handleVisibilityChange(): void {
314
+ if (typeof document === "undefined") return;
315
+ if (document.visibilityState === "hidden") pausePolling();
316
+ else resumePolling();
317
+ }
318
+
319
+ function handleFocus(): void {
320
+ if (typeof document !== "undefined" && document.visibilityState === "hidden") {
321
+ return;
322
+ }
323
+ resumePolling();
324
+ }
325
+
326
+ async function start(): Promise<void> {
327
+ if (typeof window === "undefined") return;
328
+
329
+ const flow = ++generation;
330
+ pollAttempt += 1;
331
+ abortInFlight();
332
+ stopTimers();
333
+ status.value = "creating";
334
+ code.value = null;
335
+ error.value = null;
336
+ session.value = null;
337
+ codeDeadline.value = null;
338
+ expiryDeadline.value = null;
339
+ requestToken = null;
340
+ failures = 0;
341
+ clock.value = Date.now();
342
+
343
+ const resolved = await loadCapabilities();
344
+ if (flow !== generation) return;
345
+ if (!resolved || !resolved.enabled || !resolved.available) {
346
+ error.value = new LoginCodeError("LOGIN_CODE_UNAVAILABLE");
347
+ status.value = "error";
348
+ return;
349
+ }
350
+ adoptServerTime(resolved.serverTime);
351
+
352
+ const controller = new AbortController();
353
+ inFlight = controller;
354
+ try {
355
+ const request = await service.create({ signal: controller.signal });
356
+ if (flow !== generation) return;
357
+ requestToken = request.requestToken;
358
+ code.value = request.code;
359
+ applyDeadlines(request.codeExpiresAt, request.expiresAt);
360
+ adoptServerTime(request.serverTime);
361
+ status.value = "waiting";
362
+ startTicker();
363
+ schedulePoll(pollInterval());
364
+ } catch (caught) {
365
+ if (flow !== generation) return;
366
+ const failure =
367
+ caught instanceof LoginCodeError
368
+ ? caught
369
+ : new LoginCodeError("NETWORK", undefined, { retryable: true });
370
+ if (failure.code === "ABORTED") return;
371
+ error.value = failure;
372
+ status.value = "error";
373
+ stopTimers();
374
+ } finally {
375
+ if (inFlight === controller) inFlight = null;
376
+ }
377
+ }
378
+
379
+ async function cancel(): Promise<void> {
380
+ if (TERMINAL_STATUSES.has(status.value)) return;
381
+
382
+ const token = requestToken;
383
+ generation += 1;
384
+ pollAttempt += 1;
385
+ abortInFlight();
386
+ stopTimers();
387
+ requestToken = null;
388
+ status.value = "cancelled";
389
+
390
+ if (token) {
391
+ try {
392
+ await service.cancel(token);
393
+ } catch {
394
+ // Best effort: the request may already be terminal server-side.
395
+ }
396
+ }
397
+ }
398
+
399
+ function retry(): Promise<void> {
400
+ return start();
401
+ }
402
+
403
+ onMounted(() => {
404
+ if (typeof window === "undefined") return;
405
+ document.addEventListener("visibilitychange", handleVisibilityChange);
406
+ window.addEventListener("focus", handleFocus);
407
+ void loadCapabilities();
408
+ });
409
+
410
+ onUnmounted(() => {
411
+ generation += 1;
412
+ pollAttempt += 1;
413
+ abortInFlight();
414
+ abortCapabilities();
415
+ stopTimers();
416
+ document.removeEventListener("visibilitychange", handleVisibilityChange);
417
+ window.removeEventListener("focus", handleFocus);
418
+ });
419
+
420
+ return {
421
+ status,
422
+ code,
423
+ formattedCode,
424
+ secondsUntilRefresh,
425
+ secondsUntilExpiry,
426
+ error,
427
+ enabled,
428
+ available,
429
+ capabilities,
430
+ session,
431
+ user,
432
+ start,
433
+ cancel,
434
+ retry,
435
+ };
436
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@devopsplaybook.io/common-web",
3
- "version": "0.13.0",
3
+ "version": "0.14.0-beta.25.5639705",
4
4
  "description": "Shared Nuxt layer for DevOpsPlaybook web applications",
5
5
  "license": "ISC",
6
6
  "repository": {