@monster-orange/den-ui 0.0.0-stage → 0.5.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.
package/src/busy.js ADDED
@@ -0,0 +1,592 @@
1
+ /**
2
+ * UK-2: the working pop-up, <den-busy>, and busyAction.
3
+ *
4
+ * A slow click never looks dead: the button is held at once; after OPEN_MS
5
+ * with no answer the pop-up names what is happening; it stays until the
6
+ * server answers, then says what happened. Framework-free; the product
7
+ * plugs in its words, its Report, its toast and its routes:
8
+ *
9
+ * configureBusy({
10
+ * lang: () => "en", the page's language (en, es, ja)
11
+ * words: { en: {...}, ... }, extra or replaced shared words
12
+ * idHeader: "X-Request-Id", the header the request id rides in
13
+ * statusUrl: (id) => url, Check again's GET (never resends)
14
+ * report: (info) => void, Report: { title, details, requestId }
15
+ * toast: (text) => void, a fast success, said without a pop-up
16
+ * open: (url) => void, a held answer's page (default: go)
17
+ * logUrl: "/logs", Open the log (reconnect mode)
18
+ * reconnect: { reconnect mode (a product restarting)
19
+ * url, polled until the product is back
20
+ * back: (now, before) => bool, is this a new run of the product?
21
+ * waitMs: (before) => number, how long before "not back" (60 s)
22
+ * version: (now) => string,
23
+ * done: (now) => void, after "back" (default: reload)
24
+ * },
25
+ * })
26
+ *
27
+ * registerActions({ name: {
28
+ * who: "Hub", whose answer it waits for (a name)
29
+ * autoClose: true, (kept for older callers: every success
30
+ * now closes at once, with the toast)
31
+ * inline: true, its place shows a quick failure itself
32
+ * mode: "reconnect",
33
+ * words: { en: { working, success, failure, ... }, es: {...}, ja: {...} },
34
+ * } })
35
+ *
36
+ * busyAction(name, run, opts) → Promise<data | null>
37
+ * run(headers) the request; it must send `headers` (the id).
38
+ * opts.button held (disabled, aria-busy) and focused again.
39
+ * opts.vars words' {placeholders}.
40
+ * opts.success(data) the success line, worked out from the answer.
41
+ * opts.onDone(data), opts.onFail(err)
42
+ * opts.toastFast a fast success says so in a toast (default true).
43
+ * opts.quietFail a refusal under OPEN_MS goes back to the caller
44
+ * (the promise rejects with it).
45
+ * opts.inlineError a network error before the pop-up opens goes back
46
+ * to the caller.
47
+ * opts.skipDone(res) true: no success line (closes quietly).
48
+ * opts.extra(res) a node under the success line; waits for Close.
49
+ * opts.before reconnect: the product's answer from before (else
50
+ * the kit asks reconnect.url first).
51
+ *
52
+ * Reconnect mode: the request may get no answer (the product stopped
53
+ * first); that counts as going down, and the pop-up waits for it to come
54
+ * back. busyAction then resolves with the new answer from reconnect.url.
55
+ *
56
+ * The request contract (Settled in v2): Try again sends the same id only
57
+ * when no answer came back; after the server answered with an error it
58
+ * sends a new one. Check again asks statusUrl(id) and never resends:
59
+ * done, failed, running ("still running") or unknown ("no record").
60
+ * An answer { held: { id, url } } closes the pop-up with no success line
61
+ * and opens url.
62
+ */
63
+ import { BUSY_WORDS } from "./busy-words.js";
64
+
65
+ export const OPEN_MS = 300;
66
+ export const MIN_MS = 600;
67
+ export const STILL_MS = 10_000;
68
+ export const NO_ANSWER_MS = 60_000;
69
+ export const SUCCESS_CLOSE_MS = 1200;
70
+ export const POLL_MS = 1000;
71
+ export const POLL_MAX_MS = 3000;
72
+
73
+ const hook = {
74
+ lang: () =>
75
+ (typeof document !== "undefined" &&
76
+ document.documentElement.lang?.slice(0, 2)) ||
77
+ "en",
78
+ words: {},
79
+ idHeader: "X-Request-Id",
80
+ statusUrl: (id) => `/requests/${encodeURIComponent(id)}`,
81
+ report: null,
82
+ toast: null,
83
+ open: (url) => window.location.assign(url),
84
+ logUrl: null,
85
+ reconnect: null,
86
+ };
87
+ const actions = new Map();
88
+
89
+ /** The product's words, routes and services (see the top of this file). */
90
+ export function configureBusy(h) {
91
+ Object.assign(hook, h ?? {});
92
+ }
93
+
94
+ /** Each action's words and rules, by name. */
95
+ export function registerActions(map) {
96
+ for (const [name, a] of Object.entries(map ?? {})) actions.set(name, a);
97
+ }
98
+
99
+ /** The registered action, for a product's own checks. */
100
+ export function busyActionOf(name) {
101
+ return actions.get(name) ?? null;
102
+ }
103
+
104
+ const fill = (s, vars) =>
105
+ String(s ?? "").replace(/\{(\w+)\}/g, (m, k) =>
106
+ vars && vars[k] !== undefined ? String(vars[k]) : m,
107
+ );
108
+
109
+ /** A shared word, in the page's language, with the product's own on top. */
110
+ function word(key, vars) {
111
+ const l = hook.lang();
112
+ const s =
113
+ hook.words?.[l]?.[key] ??
114
+ BUSY_WORDS[l]?.[key] ??
115
+ hook.words?.en?.[key] ??
116
+ BUSY_WORDS.en[key] ??
117
+ key;
118
+ return fill(s, vars);
119
+ }
120
+
121
+ /** One of the action's own words (working, success, failure, …). */
122
+ function actionWord(a, key, vars) {
123
+ const l = hook.lang();
124
+ return fill(a.words?.[l]?.[key] ?? a.words?.en?.[key] ?? "", vars);
125
+ }
126
+
127
+ const esc = (s) =>
128
+ String(s ?? "").replace(
129
+ /[&<>"']/g,
130
+ (c) =>
131
+ ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[
132
+ c
133
+ ],
134
+ );
135
+
136
+ const ICONS = {
137
+ clock:
138
+ '<circle cx="12" cy="12" r="9" fill="none" stroke="currentColor" stroke-width="2"/><path d="M12 7v5l3 2" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>',
139
+ ok: '<circle cx="12" cy="12" r="9" fill="none" stroke="currentColor" stroke-width="2"/><path d="M8 12.5l3 3 5-6" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"/>',
140
+ bad: '<path d="M12 4l9 16H3z" fill="none" stroke="currentColor" stroke-width="2" stroke-linejoin="round"/><path d="M12 10v4.5M12 17.5v.01" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>',
141
+ };
142
+ const icon = (k) =>
143
+ `<svg class="bz-ico bz-${k}" viewBox="0 0 24 24" aria-hidden="true">${ICONS[k]}</svg>`;
144
+
145
+ /* Tokens only (UK-1): no colour of its own. */
146
+ const CSS = `
147
+ .bz-dlg{font-family:var(--sans);position:fixed;inset-block:auto;inset-inline:0;top:50%;transform:translateY(-50%);margin:0 auto;height:auto;max-height:calc(100vh - 32px);max-height:calc(100dvh - 32px);overflow:auto;width:min(420px,calc(100vw - 32px));max-width:100%;padding:0;border:1px solid var(--border-strong);border-radius:var(--radius);background:var(--surface);color:var(--text);box-shadow:var(--shadow-dialog)}
148
+ .bz-dlg::backdrop{background:color-mix(in srgb,var(--sunken) 70%,transparent)}
149
+ .bz-b{padding:var(--space-4) calc(var(--space-4) + 2px);display:grid;gap:10px}
150
+ .bz-b h2{font-size:var(--fs-l);margin:0;outline:none;display:flex;gap:var(--space-2);align-items:center}
151
+ .bz-b p{margin:0;font-size:var(--fs-s);line-height:1.5}
152
+ .bz-ico{width:18px;height:18px;flex:none}
153
+ .bz-ok{color:var(--ok)}.bz-bad{color:var(--bad)}
154
+ .bz-dlg[data-state="noanswer"] .bz-clock{color:var(--warn)}
155
+ .bz-bar{height:2px;background:color-mix(in srgb,var(--accent) 22%,transparent);position:relative;overflow:hidden;border-radius:2px}
156
+ .bz-bar i{position:absolute;inset:0 auto 0 0;width:35%;background:var(--accent);animation:bz-ind 1.4s ease-in-out infinite}
157
+ @keyframes bz-ind{0%{transform:translateX(-100%)}100%{transform:translateX(300%)}}
158
+ @media (prefers-reduced-motion: reduce){.bz-bar i{animation:none;width:100%;opacity:.7}}
159
+ .bz-b details{font-size:var(--fs-xs);color:var(--muted)}
160
+ .bz-b pre{margin:6px 0 0;font:11.5px/1.5 var(--mono);background:var(--sunken);padding:var(--space-2);border-radius:var(--radius-button);white-space:pre-wrap;overflow-wrap:anywhere}
161
+ .bz-ft{display:flex;flex-wrap:wrap;gap:var(--space-2);justify-content:flex-end;align-items:center}
162
+ .bz-btn{font:inherit;font-size:var(--fs-s);min-height:var(--tap-min);padding:0 var(--space-3);border-radius:var(--radius-button);border:1px solid var(--border-strong);background:var(--surface);color:var(--text);cursor:pointer}
163
+ .bz-btn:focus-visible{outline:2px solid var(--accent);outline-offset:2px}
164
+ .bz-btn.bz-primary{background:var(--accent-fill);border-color:var(--accent-fill);color:var(--on-accent)}
165
+ @media (max-width:480px){.bz-btn{min-height:var(--tap)}.bz-ft .bz-primary{flex-basis:100%;order:9}}
166
+ `;
167
+
168
+ function ensureCss() {
169
+ if (document.getElementById("bz-css")) return;
170
+ const s = document.createElement("style");
171
+ s.id = "bz-css";
172
+ s.textContent = CSS;
173
+ document.head.append(s);
174
+ }
175
+
176
+ /** <den-busy>: the pop-up's element, defined on first use (a browser only). */
177
+ function defineElement() {
178
+ if (typeof customElements === "undefined" || customElements.get("den-busy"))
179
+ return;
180
+ customElements.define("den-busy", class extends HTMLElement {});
181
+ }
182
+
183
+ function makeDialog(host) {
184
+ const d = document.createElement("dialog");
185
+ d.className = "bz-dlg";
186
+ d.setAttribute("aria-labelledby", "bz-h");
187
+ d.setAttribute("aria-modal", "true");
188
+ host.append(d);
189
+ return d;
190
+ }
191
+
192
+ function newId() {
193
+ try {
194
+ return crypto.randomUUID();
195
+ } catch {
196
+ return (
197
+ Date.now().toString(16) +
198
+ "-" +
199
+ Math.random().toString(16).slice(2, 12).padEnd(10, "0")
200
+ );
201
+ }
202
+ }
203
+
204
+ const later = (ms) => new Promise((r) => setTimeout(r, ms));
205
+
206
+ /** The first message with words: the error's own, its answer's, nothing. */
207
+ export function messageOf(err) {
208
+ const tries = [
209
+ err?.message,
210
+ err?.error?.message,
211
+ err?.error,
212
+ err?.body?.message,
213
+ err?.body?.error?.message,
214
+ err?.body?.error,
215
+ ];
216
+ for (const m of tries)
217
+ if (typeof m === "string" && m.trim() !== "") return m.trim();
218
+ return "";
219
+ }
220
+
221
+ /** The server answered (with an error), as opposed to no answer at all. */
222
+ const answeredWithError = (err) =>
223
+ !!err && !err.network && typeof err.status === "number";
224
+
225
+ /** Details: status code · request id · time (never the API path). */
226
+ function detailsText(err, id, at) {
227
+ const bits = [];
228
+ if (err?.status) bits.push(`status ${err.status}`);
229
+ bits.push(`request ${id}`);
230
+ bits.push(at.toLocaleTimeString([], { hour12: false }));
231
+ const said = messageOf(err);
232
+ return said ? `${bits.join(" · ")}\n${said}` : bits.join(" · ");
233
+ }
234
+
235
+ export function busyAction(name, run, opts = {}) {
236
+ const a = actions.get(name);
237
+ if (!a) throw new Error(`busyAction: no action named "${name}"`);
238
+ const { button } = opts;
239
+ const who = a.who ?? "";
240
+ const vars = { ...(opts.vars ?? {}), who };
241
+ const reconnect = a.mode === "reconnect";
242
+ let id = newId();
243
+ let el = null;
244
+ let d = null;
245
+ let openedAt = 0;
246
+ let state = "working";
247
+ let ticker = 0;
248
+ let settled = false;
249
+ let lastErr = null;
250
+ let okData = null;
251
+ let lastAt = new Date();
252
+ let finish;
253
+ let fail;
254
+ const result = new Promise((res, rej) => {
255
+ finish = res;
256
+ fail = rej;
257
+ });
258
+
259
+ const hold = (on) => {
260
+ if (!button) return;
261
+ button.disabled = on;
262
+ if (on) button.setAttribute("aria-busy", "true");
263
+ else button.removeAttribute("aria-busy");
264
+ };
265
+
266
+ function ensureDialog() {
267
+ if (d) return d;
268
+ ensureCss();
269
+ defineElement();
270
+ el = document.createElement("den-busy");
271
+ document.body.append(el);
272
+ d = makeDialog(el);
273
+ // Working: Esc does nothing. Otherwise Esc is Close.
274
+ d.addEventListener("cancel", (e) => {
275
+ e.preventDefault();
276
+ if (state !== "working") close(null);
277
+ });
278
+ // The backdrop: a press on the dialog itself, outside its body.
279
+ d.addEventListener("click", (e) => {
280
+ if (e.target === d && state !== "working") close(null);
281
+ });
282
+ return d;
283
+ }
284
+
285
+ function paint(html, focusSel) {
286
+ const dl = ensureDialog();
287
+ dl.dataset.state = state;
288
+ dl.setAttribute("aria-busy", String(state === "working"));
289
+ dl.innerHTML = `<div class="bz-b">${html}</div>`;
290
+ if (!dl.open) {
291
+ if (typeof dl.showModal === "function") dl.showModal();
292
+ else dl.setAttribute("open", "");
293
+ openedAt = Date.now();
294
+ }
295
+ dl.querySelector(focusSel ?? "#bz-h")?.focus?.();
296
+ }
297
+
298
+ const title = (ic, text) =>
299
+ `<h2 id="bz-h" tabindex="-1">${icon(ic)}${esc(text)}</h2>`;
300
+ const btn = (key, primary) =>
301
+ `<button type="button" class="bz-btn${primary ? " bz-primary" : ""}" data-bz="${key}">${esc(word(key))}</button>`;
302
+
303
+ /** Report · Close · [Open the log] · the primary, last. */
304
+ const footer = (primary, withLog) =>
305
+ `<div class="bz-ft">` +
306
+ (hook.report ? btn("report") : "") +
307
+ btn("close") +
308
+ (withLog && hook.logUrl ? btn("log") : "") +
309
+ btn(primary, true) +
310
+ `</div>`;
311
+
312
+ function paintWorking(secs, note) {
313
+ state = "working";
314
+ const line = note
315
+ ? note
316
+ : secs >= STILL_MS / 1000
317
+ ? word("still", { s: secs })
318
+ : reconnect && actionWord(a, "working_body", vars)
319
+ ? actionWord(a, "working_body", vars)
320
+ : word("wait", { who });
321
+ paint(
322
+ title("clock", actionWord(a, "working", vars)) +
323
+ `<p aria-live="polite" class="bz-live">${esc(line)}</p>` +
324
+ `<div class="bz-bar" role="progressbar" aria-label="${esc(word("wait", { who }))}"><i></i></div>`,
325
+ );
326
+ }
327
+
328
+ function tick(startedAt) {
329
+ clearInterval(ticker);
330
+ ticker = setInterval(() => {
331
+ if (state !== "working") return clearInterval(ticker);
332
+ const ms = Date.now() - startedAt;
333
+ if (ms >= NO_ANSWER_MS) {
334
+ clearInterval(ticker);
335
+ return paintNoAnswer();
336
+ }
337
+ if (ms >= STILL_MS && !reconnect) {
338
+ const live = d?.querySelector(".bz-live");
339
+ if (live)
340
+ live.textContent = word("still", { s: Math.floor(ms / 1000) });
341
+ }
342
+ }, 1000);
343
+ }
344
+
345
+ function wire() {
346
+ const on = (k, fn) =>
347
+ d.querySelector(`[data-bz="${k}"]`)?.addEventListener("click", fn);
348
+ on("close", () => close(state === "success" ? okData : null));
349
+ on("done", () => close(okData));
350
+ on("retry", () => attempt());
351
+ on("check", () => (reconnect ? waitBack(Date.now()) : checkAgain()));
352
+ on("log", () => hook.open(hook.logUrl));
353
+ on("report", () =>
354
+ hook.report?.({
355
+ title: actionWord(a, "failure", vars),
356
+ details: detailsText(lastErr, id, lastAt),
357
+ requestId: id,
358
+ }),
359
+ );
360
+ }
361
+
362
+ function paintFailure(err) {
363
+ state = "failure";
364
+ lastErr = err;
365
+ lastAt = new Date();
366
+ // The server's own words, only when it answered (a network error's
367
+ // message is the client's, not the server's).
368
+ const said = answeredWithError(err) ? messageOf(err) : "";
369
+ const why = err?.network
370
+ ? word("network", { who })
371
+ : err?.status
372
+ ? word("err_code", { who, code: err.status })
373
+ : messageOf(err) || word("network", { who });
374
+ opts.onFail?.(err);
375
+ paint(
376
+ title("bad", actionWord(a, "failure", vars)) +
377
+ `<p>${esc(why)}</p>` +
378
+ (said && said !== why ? `<p class="bz-said">${esc(said)}</p>` : "") +
379
+ `<details><summary>${esc(word("details"))}</summary><pre>${esc(detailsText(err, id, lastAt))}</pre></details>` +
380
+ footer("retry"),
381
+ '[data-bz="retry"]',
382
+ );
383
+ wire();
384
+ }
385
+
386
+ function paintNoAnswer(note) {
387
+ state = "noanswer";
388
+ const t = reconnect
389
+ ? actionWord(a, "failure", vars)
390
+ : word("noans_t", { who });
391
+ const b = reconnect ? actionWord(a, "failure_body", vars) : word("noans_b");
392
+ paint(
393
+ title("clock", t) +
394
+ `<p>${esc(b)}</p>` +
395
+ (note ? `<p class="bz-note">${esc(note)}</p>` : "") +
396
+ footer("check", reconnect),
397
+ '[data-bz="check"]',
398
+ );
399
+ wire();
400
+ }
401
+
402
+ function paintSuccess(data, node) {
403
+ state = "success";
404
+ const text = opts.success
405
+ ? opts.success(data)
406
+ : actionWord(a, "success", vars);
407
+ paint(
408
+ title("ok", text) +
409
+ (reconnect && data?.version
410
+ ? `<p>${esc(actionWord(a, "success_body", { ...vars, v: data.version }))}</p>`
411
+ : "") +
412
+ `<div class="bz-extra"></div>` +
413
+ `<div class="bz-ft">${btn(node ? "close" : "done", true)}</div>`,
414
+ node ? '[data-bz="close"]' : '[data-bz="done"]',
415
+ );
416
+ if (node) d.querySelector(".bz-extra")?.append(node);
417
+ else d.querySelector(".bz-extra")?.remove();
418
+ wire();
419
+ if (a.autoClose && !node)
420
+ setTimeout(() => {
421
+ if (state === "success") close(data);
422
+ }, SUCCESS_CLOSE_MS);
423
+ }
424
+
425
+ function close(data) {
426
+ if (settled) return;
427
+ settled = true;
428
+ clearInterval(ticker);
429
+ if (d?.open && typeof d.close === "function") d.close();
430
+ el?.remove();
431
+ hold(false);
432
+ button?.focus?.();
433
+ finish(data);
434
+ }
435
+
436
+ /** Back to the caller, with the error: its place shows it. */
437
+ function giveBack(err) {
438
+ if (settled) return;
439
+ settled = true;
440
+ clearInterval(ticker);
441
+ el?.remove();
442
+ hold(false);
443
+ opts.onFail?.(err);
444
+ fail(err);
445
+ }
446
+
447
+ /** The answer came; the pop-up may not be open (a fast action). */
448
+ async function answered(ok, data, err) {
449
+ if (settled) return;
450
+ if (!ok && !d?.open) {
451
+ // Settled 5: a quick failure goes back where the place says it
452
+ // itself; elsewhere the Failure pop-up opens at once.
453
+ const network = !!err?.network || !answeredWithError(err);
454
+ if ((opts.inlineError || a.inline) && network) return giveBack(err);
455
+ if ((opts.quietFail || a.inline) && !network) return giveBack(err);
456
+ }
457
+ if (d?.open) {
458
+ const shown = Date.now() - openedAt;
459
+ if (shown < MIN_MS) await later(MIN_MS - shown);
460
+ }
461
+ if (settled) return;
462
+ if (ok) {
463
+ okData = data;
464
+ // Settled 6: held for a person: no success line, its page instead.
465
+ if (data && typeof data === "object" && data.held?.url) {
466
+ close(data);
467
+ hook.open(data.held.url);
468
+ return;
469
+ }
470
+ opts.onDone?.(data);
471
+ if (opts.skipDone?.(data)) return close(data);
472
+ if (reconnect) return waitBack(Date.now());
473
+ const node = opts.extra?.(data) ?? null;
474
+ // UK-2 (Ward): success never waits for a click. The pop-up closes at
475
+ // once and the toast says it, as for a fast action. Only `extra`
476
+ // (something to read) keeps it open, with Close.
477
+ if (!node) {
478
+ if (d?.open || opts.toastFast !== false)
479
+ hook.toast?.(
480
+ opts.success ? opts.success(data) : actionWord(a, "success", vars),
481
+ );
482
+ return close(data);
483
+ }
484
+ return paintSuccess(data, node);
485
+ }
486
+ // Reconnect: no answer is the product going down; wait for it.
487
+ if (reconnect && !answeredWithError(err)) return waitBack(Date.now());
488
+ paintFailure(err);
489
+ }
490
+
491
+ function attempt() {
492
+ // Try again: the same id only when no answer came back.
493
+ if (answeredWithError(lastErr)) id = newId();
494
+ lastErr = null;
495
+ const startedAt = Date.now();
496
+ state = "working";
497
+ hold(true);
498
+ if (d?.open) {
499
+ paintWorking(0);
500
+ tick(startedAt);
501
+ }
502
+ const opener = setTimeout(() => {
503
+ if (state === "working" && !settled && !d?.open) {
504
+ paintWorking(0);
505
+ tick(startedAt);
506
+ }
507
+ }, OPEN_MS);
508
+ Promise.resolve()
509
+ .then(() => run({ [hook.idHeader]: id }))
510
+ .then(
511
+ (data) => {
512
+ clearTimeout(opener);
513
+ clearInterval(ticker);
514
+ return answered(true, data);
515
+ },
516
+ (err) => {
517
+ clearTimeout(opener);
518
+ clearInterval(ticker);
519
+ lastErr = err;
520
+ return answered(false, null, err);
521
+ },
522
+ );
523
+ }
524
+
525
+ /** Check again: how did this id end? Never resends. */
526
+ async function checkAgain() {
527
+ let st = null;
528
+ try {
529
+ const r = await fetch(hook.statusUrl(id), { cache: "no-store" });
530
+ st = r.ok ? await r.json() : null;
531
+ } catch {
532
+ st = null;
533
+ }
534
+ if (settled) return;
535
+ if (st?.state === "done") return answered(true, st.result ?? okData);
536
+ if (st?.state === "failed")
537
+ return answered(false, null, {
538
+ status: st.error?.code,
539
+ message: st.error?.message || undefined,
540
+ });
541
+ if (st?.state === "running") return paintNoAnswer(word("still_running"));
542
+ if (st?.state === "unknown")
543
+ return paintNoAnswer(word("noans_unknown", { who }));
544
+ return answered(false, null, { network: true });
545
+ }
546
+
547
+ /** Reconnect mode: poll until the product is back, 1 s backing off to 3 s. */
548
+ async function waitBack(startedAt) {
549
+ const rc = hook.reconnect;
550
+ if (!rc) return paintNoAnswer();
551
+ state = "working";
552
+ paintWorking(0);
553
+ let gap = POLL_MS;
554
+ const limit = Number(rc.waitMs?.(before)) || NO_ANSWER_MS;
555
+ while (!settled && Date.now() - startedAt < limit) {
556
+ await later(gap);
557
+ gap = Math.min(POLL_MAX_MS, gap + 500);
558
+ let now = null;
559
+ try {
560
+ const r = await fetch(rc.url, { cache: "no-store" });
561
+ now = r.ok ? await r.json() : null;
562
+ } catch {
563
+ now = null;
564
+ }
565
+ if (settled) return;
566
+ if (now && rc.back(now, before)) {
567
+ const v = rc.version?.(now) ?? "";
568
+ paintSuccess({ version: v }, null);
569
+ setTimeout(() => {
570
+ if (settled) return;
571
+ (rc.done ?? (() => location.reload()))(now);
572
+ close(now);
573
+ }, SUCCESS_CLOSE_MS);
574
+ return;
575
+ }
576
+ }
577
+ if (!settled) paintNoAnswer();
578
+ }
579
+
580
+ // Reconnect mode: how the product answered before it went away.
581
+ let before = opts.before ?? null;
582
+ if (reconnect && hook.reconnect && !before)
583
+ fetch(hook.reconnect.url, { cache: "no-store" })
584
+ .then((r) => (r.ok ? r.json() : null))
585
+ .catch(() => null)
586
+ .then((b) => {
587
+ before = b;
588
+ attempt();
589
+ });
590
+ else attempt();
591
+ return result;
592
+ }