@meldgrove/ui 0.0.0-stage → 0.1.1

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 (139) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +213 -2
  3. package/dist/components/alert-dialog.d.ts +18 -0
  4. package/dist/components/alert-dialog.js +44 -0
  5. package/dist/components/alert.d.ts +9 -0
  6. package/dist/components/alert.js +25 -0
  7. package/dist/components/avatar.d.ts +11 -0
  8. package/dist/components/avatar.js +24 -0
  9. package/dist/components/badge.d.ts +9 -0
  10. package/dist/components/badge.js +25 -0
  11. package/dist/components/breadcrumb.d.ts +11 -0
  12. package/dist/components/breadcrumb.js +28 -0
  13. package/dist/components/button-group.d.ts +11 -0
  14. package/dist/components/button-group.js +27 -0
  15. package/dist/components/button.d.ts +10 -0
  16. package/dist/components/button.js +36 -0
  17. package/dist/components/calendar.d.ts +8 -0
  18. package/dist/components/calendar.js +73 -0
  19. package/dist/components/card.d.ts +9 -0
  20. package/dist/components/card.js +25 -0
  21. package/dist/components/chart.d.ts +44 -0
  22. package/dist/components/chart.js +117 -0
  23. package/dist/components/checkbox.d.ts +4 -0
  24. package/dist/components/checkbox.js +10 -0
  25. package/dist/components/collapsible.d.ts +5 -0
  26. package/dist/components/collapsible.js +13 -0
  27. package/dist/components/command.d.ts +18 -0
  28. package/dist/components/command.js +35 -0
  29. package/dist/components/confirm-dialog.d.ts +15 -0
  30. package/dist/components/confirm-dialog.js +26 -0
  31. package/dist/components/copy-button.d.ts +6 -0
  32. package/dist/components/copy-button.js +23 -0
  33. package/dist/components/dialog.d.ts +17 -0
  34. package/dist/components/dialog.js +39 -0
  35. package/dist/components/dropdown-menu.d.ts +25 -0
  36. package/dist/components/dropdown-menu.js +53 -0
  37. package/dist/components/empty.d.ts +11 -0
  38. package/dist/components/empty.js +33 -0
  39. package/dist/components/field.d.ts +24 -0
  40. package/dist/components/field.js +74 -0
  41. package/dist/components/hover-card.d.ts +6 -0
  42. package/dist/components/hover-card.js +16 -0
  43. package/dist/components/input-group.d.ts +16 -0
  44. package/dist/components/input-group.js +64 -0
  45. package/dist/components/input.d.ts +3 -0
  46. package/dist/components/input.js +7 -0
  47. package/dist/components/item.d.ts +23 -0
  48. package/dist/components/item.js +67 -0
  49. package/dist/components/kbd.d.ts +3 -0
  50. package/dist/components/kbd.js +11 -0
  51. package/dist/components/label.d.ts +4 -0
  52. package/dist/components/label.js +9 -0
  53. package/dist/components/native-select.d.ts +8 -0
  54. package/dist/components/native-select.js +14 -0
  55. package/dist/components/pager.d.ts +7 -0
  56. package/dist/components/pager.js +11 -0
  57. package/dist/components/pagination.d.ts +13 -0
  58. package/dist/components/pagination.js +30 -0
  59. package/dist/components/popover.d.ts +10 -0
  60. package/dist/components/popover.js +28 -0
  61. package/dist/components/progress.d.ts +4 -0
  62. package/dist/components/progress.js +9 -0
  63. package/dist/components/radio-group.d.ts +5 -0
  64. package/dist/components/radio-group.js +13 -0
  65. package/dist/components/scroll-area.d.ts +5 -0
  66. package/dist/components/scroll-area.js +12 -0
  67. package/dist/components/secret-field.d.ts +23 -0
  68. package/dist/components/secret-field.js +47 -0
  69. package/dist/components/select.d.ts +15 -0
  70. package/dist/components/select.js +40 -0
  71. package/dist/components/separator.d.ts +4 -0
  72. package/dist/components/separator.js +9 -0
  73. package/dist/components/sheet.d.ts +14 -0
  74. package/dist/components/sheet.js +42 -0
  75. package/dist/components/sidebar.d.ts +70 -0
  76. package/dist/components/sidebar.js +212 -0
  77. package/dist/components/skeleton.d.ts +2 -0
  78. package/dist/components/skeleton.js +6 -0
  79. package/dist/components/sonner.d.ts +5 -0
  80. package/dist/components/sonner.js +14 -0
  81. package/dist/components/spinner.d.ts +2 -0
  82. package/dist/components/spinner.js +7 -0
  83. package/dist/components/states.d.ts +14 -0
  84. package/dist/components/states.js +18 -0
  85. package/dist/components/switch.d.ts +6 -0
  86. package/dist/components/switch.js +9 -0
  87. package/dist/components/table.d.ts +17 -0
  88. package/dist/components/table.js +34 -0
  89. package/dist/components/tabs.d.ts +11 -0
  90. package/dist/components/tabs.js +30 -0
  91. package/dist/components/textarea.d.ts +3 -0
  92. package/dist/components/textarea.js +7 -0
  93. package/dist/components/toggle-group.d.ts +9 -0
  94. package/dist/components/toggle-group.js +23 -0
  95. package/dist/components/toggle.d.ts +9 -0
  96. package/dist/components/toggle.js +27 -0
  97. package/dist/components/tooltip.d.ts +7 -0
  98. package/dist/components/tooltip.js +19 -0
  99. package/dist/hooks/use-mobile.d.ts +2 -0
  100. package/dist/hooks/use-mobile.js +13 -0
  101. package/dist/lib/format.d.ts +8 -0
  102. package/dist/lib/format.js +38 -0
  103. package/dist/lib/i18n-core.d.ts +38 -0
  104. package/dist/lib/i18n-core.js +61 -0
  105. package/dist/lib/i18n.d.ts +11 -0
  106. package/dist/lib/i18n.js +19 -0
  107. package/dist/lib/portal.d.ts +13 -0
  108. package/dist/lib/portal.js +17 -0
  109. package/dist/lib/theme.d.ts +5 -0
  110. package/dist/lib/theme.js +17 -0
  111. package/dist/lib/utils.d.ts +2 -0
  112. package/dist/lib/utils.js +5 -0
  113. package/dist/standalone/meldgrove-updates.js +57 -0
  114. package/dist/styles.css +11 -0
  115. package/dist/theme.css +62 -0
  116. package/dist/tokens.css +94 -0
  117. package/dist/updates/controller.d.ts +249 -0
  118. package/dist/updates/controller.js +657 -0
  119. package/dist/updates/core.d.ts +10 -0
  120. package/dist/updates/core.js +10 -0
  121. package/dist/updates/index.d.ts +15 -0
  122. package/dist/updates/index.js +15 -0
  123. package/dist/updates/messages.d.ts +92 -0
  124. package/dist/updates/messages.js +182 -0
  125. package/dist/updates/notice.d.ts +3 -0
  126. package/dist/updates/notice.js +6 -0
  127. package/dist/updates/react.d.ts +56 -0
  128. package/dist/updates/react.js +72 -0
  129. package/dist/updates/state.d.ts +224 -0
  130. package/dist/updates/state.js +411 -0
  131. package/dist/updates/transport.d.ts +50 -0
  132. package/dist/updates/transport.js +76 -0
  133. package/dist/updates/types.d.ts +77 -0
  134. package/dist/updates/types.js +68 -0
  135. package/dist/updates/update-button.d.ts +9 -0
  136. package/dist/updates/update-button.js +161 -0
  137. package/dist/updates/updates-settings.d.ts +17 -0
  138. package/dist/updates/updates-settings.js +97 -0
  139. package/package.json +159 -4
@@ -0,0 +1,657 @@
1
+ import { errorMessage, translate } from "../lib/i18n-core.js";
2
+ import { messages } from "./messages.js";
3
+ import { answerInstall, buttonState, followStatus, hasPanel, ignoreInstall, installOutcome, installStorage, noteOutage, panelState, reconcileDeadline, SLOW_AFTER_MS, staleVersion, startAttempt, statusTimeout, unconfirmedEnd, } from "./state.js";
4
+ import { SignedOutError, } from "./transport.js";
5
+ import { parseUpdatesResponse, } from "./types.js";
6
+ /** Status requests: every 5 minutes, every 2 seconds while following an installation. */
7
+ export const NORMAL_INTERVAL_MS = 5 * 60_000;
8
+ export const INSTALL_INTERVAL_MS = 2_000;
9
+ /** A status older than this is asked again when the window regains focus or the network returns. */
10
+ export const STALE_MS = 60_000;
11
+ /** How long the install request may take (the app waits up to 10 s for the update service). */
12
+ export const INSTALL_TIMEOUT_MS = 15_000;
13
+ /** How long a check or a channel switch may take (the app waits up to 35 s). */
14
+ export const POST_TIMEOUT_MS = 45_000;
15
+ /** The page reloads this long after the new version answered. */
16
+ export const RELOAD_DELAY_MS = 1_500;
17
+ /** How often the snapshot's `now` moves, for relative times. */
18
+ const TICK_MS = 30_000;
19
+ /** Dates as people in the apps' organizations read them: "19 Nov 2026, 14:05" or "19.11.2026, 14:05". */
20
+ function defaultDateLocale(locale) {
21
+ return locale === "de" ? "de-DE" : "en-GB";
22
+ }
23
+ /** An answer without status, for a page whose first status request failed (the button stays). */
24
+ function noStatus(error) {
25
+ return { app: { version: null }, reachable: false, updater: null, error };
26
+ }
27
+ /** The version the app runs: its own, else what the updater considers installed. */
28
+ export function runningVersion(response) {
29
+ return response?.app.version ?? response?.updater?.installed ?? null;
30
+ }
31
+ /** The message of a route's answer that is not a status: its `error`, else the status code. */
32
+ function answerError(answer) {
33
+ const parsed = parseUpdatesResponse(answer.data);
34
+ if (parsed?.error)
35
+ return parsed.error;
36
+ const data = answer.data;
37
+ if (typeof data?.error === "string")
38
+ return data.error;
39
+ if (typeof data?.error === "object" && data.error !== null) {
40
+ const message = data.error.message;
41
+ if (typeof message === "string")
42
+ return message;
43
+ }
44
+ if (typeof data?.message === "string")
45
+ return data.message;
46
+ return `Request failed (${answer.status})`;
47
+ }
48
+ /**
49
+ * The session ended or no longer allows this: 401, 403, or the 404 that the
50
+ * routes answer everyone but app admins.
51
+ */
52
+ const isSignedOutStatus = (status) => status === 401 || status === 403 || status === 404;
53
+ const signedOutReason = (status) => (status === 401 ? "signed-out" : "forbidden");
54
+ /**
55
+ * The update button's behaviour for one page, free of React: asks the app's
56
+ * update routes for the status (on start, every 5 minutes, on focus at most
57
+ * once a minute; every 2 seconds while following an installation), checks and
58
+ * installs on request, follows an installation through the restart, reloads
59
+ * the page when the new version answers, and stops every automatic request
60
+ * once the session ended. Never checks by itself. The React components and
61
+ * the standalone element render its snapshot.
62
+ *
63
+ * No page keeps old code after an update: the page that saw an installation
64
+ * finish tells the app's other pages in this browser, and they reload too; a
65
+ * page that missed it (asleep, in another browser, an automatic install)
66
+ * reloads once a status names another app version than the page's first.
67
+ */
68
+ export class UpdatesController {
69
+ appName;
70
+ project;
71
+ locale;
72
+ dateLocale;
73
+ timeZone;
74
+ t;
75
+ transport;
76
+ storage;
77
+ notifyFn;
78
+ onSignedOutFn;
79
+ reloadFn;
80
+ clock;
81
+ fixedDateLocale;
82
+ pageStart;
83
+ restored = false;
84
+ listeners = new Set();
85
+ /** The request that asks for the status now, to cancel when an installation starts. */
86
+ statusAbort = null;
87
+ response;
88
+ /**
89
+ * The app's version in the page's first answer: the code this page runs.
90
+ * Never from `initialResponse`: a page served from a cache would reload
91
+ * again and again.
92
+ */
93
+ pageVersion = null;
94
+ /** Tells the app's other pages in this browser that an installation is done, and hears theirs. */
95
+ channel = null;
96
+ /** When the latest status request ended, and whether it failed (no status, or not reachable). */
97
+ lastPoll = null;
98
+ pending = null;
99
+ ignored = null;
100
+ recent = null;
101
+ checkRunning = false;
102
+ savingChannel = false;
103
+ open = false;
104
+ stopped = false;
105
+ reloading = false;
106
+ statusRunning = false;
107
+ lastStatusAt = 0;
108
+ started = false;
109
+ pollTimer = null;
110
+ deadlineTimer = null;
111
+ slowTimer = null;
112
+ reloadTimer = null;
113
+ tickTimer = null;
114
+ snapshot;
115
+ /** The snapshot before `start`: what a server renders, and so what hydration expects. */
116
+ initialSnapshot;
117
+ constructor(options) {
118
+ this.transport = options.transport;
119
+ this.appName = options.appName;
120
+ this.project = options.project;
121
+ this.locale = options.locale ?? "en";
122
+ this.fixedDateLocale = options.dateLocale ?? null;
123
+ this.dateLocale = this.fixedDateLocale ?? defaultDateLocale(this.locale);
124
+ this.timeZone = options.timeZone;
125
+ this.t = translate(messages, this.locale);
126
+ this.storage = options.storage ?? installStorage(`meldgrove.updates.${options.project}`);
127
+ this.notifyFn = options.notify ?? (() => undefined);
128
+ this.onSignedOutFn = options.onSignedOut ?? null;
129
+ this.reloadFn = options.reload ?? (() => window.location.reload());
130
+ this.clock = options.now ?? Date.now;
131
+ this.pageStart = this.clock();
132
+ this.response = options.initialResponse;
133
+ // The followed installation comes from sessionStorage in `start`, never while rendering.
134
+ this.snapshot = this.compute();
135
+ this.initialSnapshot = this.snapshot;
136
+ }
137
+ // --- Subscription -------------------------------------------------------------------------
138
+ subscribe = (listener) => {
139
+ this.listeners.add(listener);
140
+ return () => this.listeners.delete(listener);
141
+ };
142
+ getSnapshot = () => this.snapshot;
143
+ /** For `useSyncExternalStore` on the server and during hydration. */
144
+ getServerSnapshot = () => this.initialSnapshot;
145
+ emit() {
146
+ this.snapshot = this.compute();
147
+ for (const listener of this.listeners)
148
+ listener();
149
+ }
150
+ compute() {
151
+ const now = this.clock();
152
+ const pending = this.pending;
153
+ // A failed first status request keeps the button ("No update service"; a click checks).
154
+ const response = this.response ?? (this.lastPoll?.failed && !this.stopped ? noStatus(this.lastPoll.error) : undefined);
155
+ const status = response?.updater ?? null;
156
+ const checking = this.checkRunning || Boolean(status?.checking);
157
+ const state = buttonState(response, { checking, pending, recent: this.recent });
158
+ const shown = panelState(response, pending, this.recent);
159
+ const panel = hasPanel(shown, response, pending);
160
+ if (!panel)
161
+ this.open = false;
162
+ const restarting = pending !== null &&
163
+ this.lastPoll !== null &&
164
+ this.lastPoll.at >= pending.startedAt &&
165
+ this.lastPoll.failed;
166
+ return {
167
+ response,
168
+ status,
169
+ pending,
170
+ recent: this.recent,
171
+ checking,
172
+ state,
173
+ shown,
174
+ panel,
175
+ open: this.open && panel,
176
+ restarting,
177
+ slow: pending !== null && installOutcome(pending, undefined, now) === "slow",
178
+ waiting: pending !== null && !this.stopped,
179
+ stopped: this.stopped,
180
+ savingChannel: this.savingChannel,
181
+ now,
182
+ };
183
+ }
184
+ // --- Lifecycle ----------------------------------------------------------------------------
185
+ /** The language of the texts the controller writes (notices). */
186
+ setLocale(locale) {
187
+ if (locale === this.locale)
188
+ return;
189
+ this.locale = locale;
190
+ this.dateLocale = this.fixedDateLocale ?? defaultDateLocale(locale);
191
+ this.t = translate(messages, locale);
192
+ this.emit();
193
+ }
194
+ /** Options a page may change after the controller exists. */
195
+ configure(options) {
196
+ if (options.notify)
197
+ this.notifyFn = options.notify;
198
+ if (options.onSignedOut !== undefined)
199
+ this.onSignedOutFn = options.onSignedOut;
200
+ let changed = false;
201
+ if (options.appName && options.appName !== this.appName) {
202
+ this.appName = options.appName;
203
+ changed = true;
204
+ }
205
+ if (options.dateLocale !== undefined) {
206
+ this.fixedDateLocale = options.dateLocale;
207
+ const next = this.fixedDateLocale ?? defaultDateLocale(this.locale);
208
+ if (next !== this.dateLocale) {
209
+ this.dateLocale = next;
210
+ changed = true;
211
+ }
212
+ }
213
+ if (options.timeZone !== undefined && (options.timeZone ?? undefined) !== this.timeZone) {
214
+ this.timeZone = options.timeZone ?? undefined;
215
+ changed = true;
216
+ }
217
+ if (changed)
218
+ this.emit();
219
+ }
220
+ /** Starts asking for the status; idempotent. Arms the deadline of a restored attempt first. */
221
+ start() {
222
+ if (this.started)
223
+ return;
224
+ this.started = true;
225
+ if (!this.restored) {
226
+ this.restored = true;
227
+ this.pageStart = this.clock();
228
+ this.pending = this.storage.loadPending();
229
+ this.ignored = this.storage.loadIgnored();
230
+ this.emit();
231
+ }
232
+ this.armTimers();
233
+ window.addEventListener("focus", this.onFocus);
234
+ window.addEventListener("online", this.onFocus);
235
+ document.addEventListener("visibilitychange", this.onVisibility);
236
+ this.openChannel();
237
+ this.tickTimer = setInterval(() => this.emit(), TICK_MS);
238
+ void this.fetchStatus();
239
+ }
240
+ /** Stops every timer and listener (also a pending reload); `start` resumes. */
241
+ dispose() {
242
+ this.started = false;
243
+ this.channel?.close();
244
+ this.channel = null;
245
+ window.removeEventListener("focus", this.onFocus);
246
+ window.removeEventListener("online", this.onFocus);
247
+ document.removeEventListener("visibilitychange", this.onVisibility);
248
+ for (const timer of [this.pollTimer, this.deadlineTimer, this.slowTimer, this.reloadTimer]) {
249
+ if (timer !== null)
250
+ clearTimeout(timer);
251
+ }
252
+ if (this.tickTimer !== null)
253
+ clearInterval(this.tickTimer);
254
+ this.pollTimer = this.deadlineTimer = this.slowTimer = this.reloadTimer = this.tickTimer = null;
255
+ }
256
+ onFocus = () => {
257
+ if (this.pending || this.clock() - this.lastStatusAt < STALE_MS)
258
+ return;
259
+ void this.fetchStatus();
260
+ };
261
+ onVisibility = () => {
262
+ if (document.visibilityState === "visible")
263
+ this.onFocus();
264
+ };
265
+ /** The channel of the app's pages in this browser; without BroadcastChannel, the version check still reloads them. */
266
+ openChannel() {
267
+ if (this.channel || typeof BroadcastChannel === "undefined")
268
+ return;
269
+ try {
270
+ this.channel = new BroadcastChannel(`meldgrove.updates.${this.project}`);
271
+ this.channel.onmessage = this.onMessage;
272
+ }
273
+ catch {
274
+ this.channel = null;
275
+ }
276
+ }
277
+ /**
278
+ * Another page of the app saw an installation finish: reload once. Also a
279
+ * page whose first status already named the version: it may have loaded
280
+ * the old code just before the switch.
281
+ */
282
+ onMessage = (event) => {
283
+ const message = event.data;
284
+ if (message?.type !== "updated" || typeof message.version !== "string")
285
+ return;
286
+ this.reloadInto(message.version);
287
+ };
288
+ /** Tells the app's other pages in this browser that it runs `version` now. */
289
+ broadcast(version) {
290
+ const message = { type: "updated", version };
291
+ this.channel?.postMessage(message);
292
+ }
293
+ /**
294
+ * The app runs `version` now: says so and reloads the page once, after
295
+ * 1.5 s (a timer `dispose` clears). Not after `dispose`: an answer still
296
+ * on its way does nothing.
297
+ */
298
+ reloadInto(version) {
299
+ if (this.reloading || !this.started)
300
+ return;
301
+ this.reloading = true;
302
+ this.setPending(null);
303
+ this.notify({ kind: "success", title: this.t("updated", { version }) });
304
+ this.reloadTimer = setTimeout(() => this.reloadFn(), RELOAD_DELAY_MS);
305
+ }
306
+ /** Shows a message the way the page shows the controller's own (toast). */
307
+ notify(notice) {
308
+ this.notifyFn(notice);
309
+ }
310
+ // --- Timers -------------------------------------------------------------------------------
311
+ /** The next status request: every 2 s while following (also in the background), else every 5 min. */
312
+ schedule() {
313
+ if (this.pollTimer !== null)
314
+ clearTimeout(this.pollTimer);
315
+ this.pollTimer = null;
316
+ if (!this.started || this.stopped)
317
+ return;
318
+ const following = this.pending !== null;
319
+ this.pollTimer = setTimeout(() => {
320
+ this.pollTimer = null;
321
+ if (!following && document.visibilityState === "hidden")
322
+ return this.schedule();
323
+ void this.fetchStatus();
324
+ }, following ? INSTALL_INTERVAL_MS : NORMAL_INTERVAL_MS);
325
+ }
326
+ /**
327
+ * An unconfirmed attempt ends at its deadline on a timer of its own, whatever
328
+ * the status requests do (failing, stalled, or paused while offline); not
329
+ * while the page is signed out (kept for a later page load). A followed
330
+ * installation turns slow after 15 minutes on another.
331
+ */
332
+ armTimers() {
333
+ if (this.deadlineTimer !== null)
334
+ clearTimeout(this.deadlineTimer);
335
+ if (this.slowTimer !== null)
336
+ clearTimeout(this.slowTimer);
337
+ this.deadlineTimer = this.slowTimer = null;
338
+ const pending = this.pending;
339
+ if (!this.started || !pending)
340
+ return;
341
+ const deadline = reconcileDeadline(pending, this.pageStart);
342
+ if (deadline !== null && !this.stopped) {
343
+ this.deadlineTimer = setTimeout(() => {
344
+ this.deadlineTimer = null;
345
+ const current = this.pending;
346
+ if (!current || reconcileDeadline(current, this.pageStart) !== deadline)
347
+ return;
348
+ this.setPending(null);
349
+ const end = unconfirmedEnd(current);
350
+ this.notify({ kind: "error", title: this.t(end.message), description: end.detail ?? undefined });
351
+ }, Math.max(0, deadline - this.clock()));
352
+ }
353
+ const slowAt = pending.startedAt + SLOW_AFTER_MS + 1;
354
+ if (slowAt > this.clock()) {
355
+ this.slowTimer = setTimeout(() => {
356
+ this.slowTimer = null;
357
+ this.emit();
358
+ }, slowAt - this.clock());
359
+ }
360
+ }
361
+ setPending(next) {
362
+ const changed = next !== this.pending;
363
+ this.pending = next;
364
+ if (!changed)
365
+ return;
366
+ this.storage.savePending(next);
367
+ this.armTimers();
368
+ this.schedule();
369
+ this.emit();
370
+ }
371
+ /** 401, 403, 404 or a sign-in page: no automatic request on this page any more; a followed installation stays stored. */
372
+ signOut(reason) {
373
+ if (this.stopped)
374
+ return;
375
+ this.stopped = true;
376
+ if (this.pollTimer !== null)
377
+ clearTimeout(this.pollTimer);
378
+ if (this.deadlineTimer !== null)
379
+ clearTimeout(this.deadlineTimer);
380
+ this.pollTimer = this.deadlineTimer = null;
381
+ this.emit();
382
+ this.onSignedOutFn?.(reason);
383
+ }
384
+ // --- Requests -----------------------------------------------------------------------------
385
+ /** Runs one request with a timeout of its own; a timeout throws an Error with the "did not answer" text. */
386
+ async send(action, body, timeoutMs, controller = new AbortController()) {
387
+ let timedOut = false;
388
+ const timer = setTimeout(() => {
389
+ timedOut = true;
390
+ controller.abort();
391
+ }, timeoutMs);
392
+ try {
393
+ return await this.transport.request({ action, body, signal: controller.signal });
394
+ }
395
+ catch (error) {
396
+ if (timedOut)
397
+ throw new Error(this.t("noAnswer", { app: this.appName }), { cause: error });
398
+ throw error;
399
+ }
400
+ finally {
401
+ clearTimeout(timer);
402
+ }
403
+ }
404
+ /** Asks for the status; each request at most until the deadline of an unconfirmed attempt. */
405
+ async fetchStatus() {
406
+ if (this.stopped || this.statusRunning)
407
+ return;
408
+ this.statusRunning = true;
409
+ const sentAt = this.clock();
410
+ const timeout = statusTimeout(reconcileDeadline(this.pending, this.pageStart), sentAt);
411
+ const abort = new AbortController();
412
+ this.statusAbort = abort;
413
+ try {
414
+ const answer = await this.send("status", undefined, timeout, abort);
415
+ if (abort.signal.aborted)
416
+ return;
417
+ if (isSignedOutStatus(answer.status))
418
+ return this.signOut(signedOutReason(answer.status));
419
+ const parsed = parseUpdatesResponse(answer.data);
420
+ if (answer.status !== 200 || !parsed)
421
+ throw new Error(answerError(answer));
422
+ this.lastStatusAt = this.clock();
423
+ this.receive(parsed, sentAt);
424
+ }
425
+ catch (error) {
426
+ // Cancelled for an installation that just started: its own polls follow.
427
+ if (abort.signal.aborted && this.statusAbort !== abort)
428
+ return;
429
+ if (error instanceof SignedOutError)
430
+ return this.signOut("signed-out");
431
+ this.pollFailed(errorMessage(error));
432
+ }
433
+ finally {
434
+ if (this.statusAbort === abort) {
435
+ this.statusAbort = null;
436
+ this.statusRunning = false;
437
+ if (this.pollTimer === null)
438
+ this.schedule();
439
+ }
440
+ }
441
+ }
442
+ /** Drops the status request in flight, so that polling follows a new installation at once. */
443
+ cancelStatus() {
444
+ const abort = this.statusAbort;
445
+ if (!abort)
446
+ return;
447
+ this.statusAbort = null;
448
+ this.statusRunning = false;
449
+ abort.abort();
450
+ }
451
+ /** A status request failed (network error, timeout, 5xx): while following, an observed outage. */
452
+ pollFailed(error) {
453
+ const at = this.clock();
454
+ this.lastPoll = { at, failed: true, error };
455
+ const pending = this.pending;
456
+ if (pending && at >= pending.startedAt) {
457
+ const next = noteOutage(pending, error);
458
+ if (next !== pending)
459
+ return this.setPending(next);
460
+ }
461
+ this.emit();
462
+ }
463
+ /** A new status, from a status request (sent at `sentAt`) or from the answer of a POST. */
464
+ receive(response, sentAt) {
465
+ this.response = response;
466
+ this.pageVersion ??= response.app.version;
467
+ this.lastPoll = { at: this.clock(), failed: !response.updater, error: response.error };
468
+ this.follow(response, sentAt);
469
+ this.emit();
470
+ }
471
+ /**
472
+ * Confirms this tab's attempt, adopts a reported installation, and ends it
473
+ * once its result is known; done reloads every page of the app in this
474
+ * browser. Without an installation to follow, reloads a page whose code is
475
+ * older than the app's.
476
+ */
477
+ follow(response, sentAt) {
478
+ if (this.reloading)
479
+ return;
480
+ const now = this.clock();
481
+ const pending = this.pending;
482
+ const followed = followStatus(pending, response, now, this.ignored, sentAt);
483
+ if (!followed) {
484
+ const version = staleVersion(this.pageVersion, response);
485
+ if (version)
486
+ this.reloadInto(version);
487
+ return;
488
+ }
489
+ const result = installOutcome(followed, response, now);
490
+ if (result === "done") {
491
+ this.broadcast(followed.version);
492
+ this.reloadInto(followed.version);
493
+ }
494
+ else if (result === "failed") {
495
+ this.recent = response.updater?.last ?? null;
496
+ this.open = true;
497
+ this.setPending(null);
498
+ }
499
+ else if (followed !== pending) {
500
+ this.setPending(followed);
501
+ }
502
+ }
503
+ /** A POST to `check` or `channel`: a status into the snapshot, or an Error with the route's reason. */
504
+ async post(action, body) {
505
+ const sentAt = this.clock();
506
+ let answer;
507
+ try {
508
+ answer = await this.send(action, body, POST_TIMEOUT_MS);
509
+ }
510
+ catch (error) {
511
+ if (error instanceof SignedOutError)
512
+ this.signOut("signed-out");
513
+ throw error;
514
+ }
515
+ if (isSignedOutStatus(answer.status))
516
+ this.signOut(signedOutReason(answer.status));
517
+ const parsed = parseUpdatesResponse(answer.data);
518
+ if (answer.status >= 200 && answer.status < 300 && parsed) {
519
+ this.receive(parsed, sentAt);
520
+ return parsed;
521
+ }
522
+ // A refusal carries the latest status.
523
+ if (answer.status === 409 && parsed)
524
+ this.receive(parsed, sentAt);
525
+ throw new Error(answerError(answer));
526
+ }
527
+ // --- Actions ------------------------------------------------------------------------------
528
+ /** Opens or closes the popover; opening without anything to show checks instead. */
529
+ setOpen = (next) => {
530
+ const snapshot = this.snapshot;
531
+ if (!next) {
532
+ this.open = false;
533
+ }
534
+ else if (snapshot.panel) {
535
+ this.open = true;
536
+ }
537
+ else {
538
+ if (snapshot.state === "current" || snapshot.state === "off" || snapshot.state === "unreachable") {
539
+ void this.check();
540
+ }
541
+ return;
542
+ }
543
+ this.emit();
544
+ };
545
+ /** Checks for new versions (only ever on request) and says what it found. */
546
+ check = async () => {
547
+ if (this.checkRunning)
548
+ return;
549
+ this.checkRunning = true;
550
+ this.emit();
551
+ try {
552
+ const result = await this.post("check", {});
553
+ const next = panelState(result, null);
554
+ if (next === "available" || next === "attention" || next === "failed" || next === "installing") {
555
+ this.open = true;
556
+ }
557
+ else if (result.updater?.error) {
558
+ this.notify({ kind: "error", title: this.t("checkFailed", { error: result.updater.error }) });
559
+ }
560
+ else if (next === "current") {
561
+ const version = runningVersion(result);
562
+ this.notify({
563
+ kind: "success",
564
+ title: version ? this.t("upToDateVersion", { version }) : this.t("upToDate"),
565
+ });
566
+ }
567
+ else if (next === "unreachable") {
568
+ this.notify({ kind: "error", title: result.error ?? this.t("unreachable") });
569
+ }
570
+ }
571
+ catch (error) {
572
+ this.notify({ kind: "error", title: errorMessage(error) });
573
+ }
574
+ finally {
575
+ this.checkRunning = false;
576
+ this.emit();
577
+ }
578
+ };
579
+ /**
580
+ * Installs `update` (the person confirmed it). The attempt is remembered
581
+ * before the request, so that a restart before its answer keeps following it.
582
+ */
583
+ install = async (update) => {
584
+ this.recent = null;
585
+ this.cancelStatus();
586
+ const attempt = startAttempt(update.version, this.response, this.clock());
587
+ this.open = true;
588
+ this.setPending(attempt);
589
+ const sentAt = this.clock();
590
+ const { answer, response } = await this.requestInstall(update.version);
591
+ const current = this.pending;
592
+ // A status may have settled it meanwhile (or another installation took its place).
593
+ if (current?.version !== attempt.version || current.startedAt !== attempt.startedAt) {
594
+ if (response)
595
+ this.receive(response, sentAt);
596
+ return;
597
+ }
598
+ const next = answerInstall(current, answer, this.clock());
599
+ this.setPending(next.pending);
600
+ if (next.error)
601
+ this.notify({ kind: "error", title: next.error });
602
+ if (response)
603
+ this.receive(response, sentAt);
604
+ };
605
+ /**
606
+ * The answer to the install request, never an exception: accepted (202, also
607
+ * when its body cannot be read), refused (4xx; a 409 with the latest status),
608
+ * or unclear (no update service, a network error, a timeout, an unreadable
609
+ * answer, a sign-in page, or a 5xx): the installation may have started.
610
+ */
611
+ async requestInstall(version) {
612
+ let answer;
613
+ try {
614
+ answer = await this.send("install", { version }, INSTALL_TIMEOUT_MS);
615
+ }
616
+ catch (error) {
617
+ if (error instanceof SignedOutError)
618
+ this.signOut("signed-out");
619
+ return { answer: { kind: "unclear", error: errorMessage(error) }, response: null };
620
+ }
621
+ const parsed = parseUpdatesResponse(answer.data);
622
+ const response = parsed?.updater ? parsed : null;
623
+ if (answer.status === 202)
624
+ return { answer: { kind: "accepted", response }, response };
625
+ if (answer.status >= 400 && answer.status < 500) {
626
+ if (isSignedOutStatus(answer.status))
627
+ this.signOut(signedOutReason(answer.status));
628
+ return { answer: { kind: "refused", error: answerError(answer), response }, response };
629
+ }
630
+ return {
631
+ answer: { kind: "unclear", error: parsed?.error ?? answerError(answer) },
632
+ response: answer.status === 200 ? parsed : null,
633
+ };
634
+ }
635
+ /** Leaves the followed installation alone, by the identity stored on it, also while no status is there. */
636
+ stopWaiting = () => {
637
+ const pending = this.pending;
638
+ if (pending) {
639
+ this.ignored = ignoreInstall(pending);
640
+ this.storage.saveIgnored(this.ignored);
641
+ }
642
+ this.setPending(null);
643
+ };
644
+ /** Switches the channel; true when the update service answered with the new channel. */
645
+ setChannel = async (channel) => {
646
+ this.savingChannel = true;
647
+ this.emit();
648
+ try {
649
+ const result = await this.post("channel", { channel });
650
+ return result.reachable && result.updater?.channel === channel;
651
+ }
652
+ finally {
653
+ this.savingChannel = false;
654
+ this.emit();
655
+ }
656
+ };
657
+ }
@@ -0,0 +1,10 @@
1
+ /**
2
+ * The update button's logic without React: the controller, the state
3
+ * functions, the transport and the types. For tests and for apps that build
4
+ * their own view.
5
+ */
6
+ export * from "./controller.ts";
7
+ export * from "./messages.ts";
8
+ export * from "./state.ts";
9
+ export * from "./transport.ts";
10
+ export * from "./types.ts";
@@ -0,0 +1,10 @@
1
+ /**
2
+ * The update button's logic without React: the controller, the state
3
+ * functions, the transport and the types. For tests and for apps that build
4
+ * their own view.
5
+ */
6
+ export * from "./controller.js";
7
+ export * from "./messages.js";
8
+ export * from "./state.js";
9
+ export * from "./transport.js";
10
+ export * from "./types.js";
@@ -0,0 +1,15 @@
1
+ /**
2
+ * The update button and the "Updates" settings for React apps:
3
+ *
4
+ * <UpdatesProvider appName="Meldgrove Handbook" project="handbook" url="/api/admin/updates" guideUrl="…">
5
+ * <UpdateButton /> (top bar, admins only)
6
+ * <UpdatesSettingsCard /> (admin settings)
7
+ * </UpdatesProvider>
8
+ */
9
+ export { UpdateButton } from "./update-button.tsx";
10
+ export { UpdatesSettings, UpdatesSettingsCard, automaticText } from "./updates-settings.tsx";
11
+ export { UpdatesProvider, UpdatesContextProvider, useUpdatesController, useUpdatesSnapshot, type UpdatesProviderProps, } from "./react.tsx";
12
+ export { toastNotice } from "./notice.ts";
13
+ export { UpdatesController, runningVersion, type Notice, type SignedOutReason, type UpdatesControllerOptions, type UpdatesSnapshot, } from "./controller.ts";
14
+ export { fetchTransport, readCookie, SignedOutError, type UpdatesTransport } from "./transport.ts";
15
+ export * from "./types.ts";