@eifi1/ui-kit 0.44.0 → 0.46.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.
- package/README.md +29 -14
- package/dist/admin/admin-action-log-labels.js +9 -0
- package/dist/admin/admin-action-log-labels.js.map +1 -1
- package/dist/admin/admin-action-log.d.ts +18 -1
- package/dist/admin/admin-action-log.js +25 -16
- package/dist/admin/admin-action-log.js.map +1 -1
- package/dist/admin/admin-area-labels.d.ts +15 -0
- package/dist/admin/admin-area-labels.js +6 -1
- package/dist/admin/admin-area-labels.js.map +1 -1
- package/dist/admin/admin-overview.d.ts +16 -1
- package/dist/admin/admin-overview.js +12 -1
- package/dist/admin/admin-overview.js.map +1 -1
- package/dist/admin/mail-test-card-labels.d.ts +3 -0
- package/dist/admin/mail-test-card-labels.js +17 -0
- package/dist/admin/mail-test-card-labels.js.map +1 -0
- package/dist/admin/mail-test-card.d.ts +75 -0
- package/dist/admin/mail-test-card.js +82 -0
- package/dist/admin/mail-test-card.js.map +1 -0
- package/dist/components/appearance-labels.d.ts +10 -0
- package/dist/components/appearance-labels.js +6 -1
- package/dist/components/appearance-labels.js.map +1 -1
- package/dist/components/data-table-column-settings.js +2 -2
- package/dist/components/data-table-column-settings.js.map +1 -1
- package/dist/components/data-table-head.js +2 -2
- package/dist/components/data-table-head.js.map +1 -1
- package/dist/components/data-table-mobile.js +17 -2
- package/dist/components/data-table-mobile.js.map +1 -1
- package/dist/components/data-table-row-actions.d.ts +18 -2
- package/dist/components/data-table-row-actions.js +86 -2
- package/dist/components/data-table-row-actions.js.map +1 -1
- package/dist/components/data-table-shared.d.ts +2 -0
- package/dist/components/data-table-shared.js +17 -2
- package/dist/components/data-table-shared.js.map +1 -1
- package/dist/components/data-table.d.ts +43 -2
- package/dist/components/data-table.js +10 -10
- package/dist/components/data-table.js.map +1 -1
- package/dist/components/date-format-setting.d.ts +29 -0
- package/dist/components/date-format-setting.js +36 -0
- package/dist/components/date-format-setting.js.map +1 -0
- package/dist/components/swipeable-row.d.ts +8 -0
- package/dist/components/swipeable-row.js.map +1 -1
- package/dist/components/tabs.d.ts +3 -2
- package/dist/components/tabs.js +1 -1
- package/dist/components/tabs.js.map +1 -1
- package/dist/components/translation-review-editor.js +1 -0
- package/dist/components/translation-review-editor.js.map +1 -1
- package/dist/components/translation-review-labels.d.ts +5 -0
- package/dist/components/translation-review-labels.js +2 -0
- package/dist/components/translation-review-labels.js.map +1 -1
- package/dist/components/translation-review.d.ts +18 -8
- package/dist/components/translation-review.js +64 -7
- package/dist/components/translation-review.js.map +1 -1
- package/dist/components/write-lock-labels.js +2 -1
- package/dist/components/write-lock-labels.js.map +1 -1
- package/dist/components/write-lock.d.ts +33 -3
- package/dist/components/write-lock.js +9 -0
- package/dist/components/write-lock.js.map +1 -1
- package/dist/data-table.d.ts +1 -1
- package/dist/data-table.js.map +1 -1
- package/dist/eslint/index.js +1 -1
- package/dist/feedback/feedback-row-detail.d.ts +4 -2
- package/dist/feedback/feedback-row-detail.js +17 -26
- package/dist/feedback/feedback-row-detail.js.map +1 -1
- package/dist/feedback/feedback-swipe.d.ts +18 -0
- package/dist/feedback/feedback-swipe.js +10 -1
- package/dist/feedback/feedback-swipe.js.map +1 -1
- package/dist/i18n/defaults.js +9 -1
- package/dist/i18n/defaults.js.map +1 -1
- package/dist/i18n/german.js +81 -5
- package/dist/i18n/german.js.map +1 -1
- package/dist/i18n/kit-labels.d.ts +25 -1
- package/dist/i18n/kit-labels.js +8 -2
- package/dist/i18n/kit-labels.js.map +1 -1
- package/dist/i18n/locales/en.js +97 -7
- package/dist/i18n/locales/en.js.map +3 -3
- package/dist/i18n/locales/es.js +81 -5
- package/dist/i18n/locales/es.js.map +1 -1
- package/dist/i18n/locales/fr.js +81 -5
- package/dist/i18n/locales/fr.js.map +1 -1
- package/dist/i18n/locales/hu.js +81 -5
- package/dist/i18n/locales/hu.js.map +1 -1
- package/dist/i18n/locales/it.js +81 -5
- package/dist/i18n/locales/it.js.map +1 -1
- package/dist/i18n/locales/zh.js +81 -5
- package/dist/i18n/locales/zh.js.map +1 -1
- package/dist/i18n/review.js +16 -2
- package/dist/i18n/review.js.map +1 -1
- package/dist/index.d.ts +17 -2
- package/dist/index.js +40 -0
- package/dist/index.js.map +1 -1
- package/dist/lib/date-format.d.ts +81 -0
- package/dist/lib/date-format.js +56 -0
- package/dist/lib/date-format.js.map +1 -0
- package/dist/lib/format.d.ts +5 -1
- package/dist/lib/format.js +11 -5
- package/dist/lib/format.js.map +1 -1
- package/dist/notifications/device-zone-report.d.ts +27 -0
- package/dist/notifications/device-zone-report.js +24 -0
- package/dist/notifications/device-zone-report.js.map +1 -0
- package/dist/notifications/feedback-notification-types-labels.d.ts +7 -1
- package/dist/notifications/feedback-notification-types-labels.js +4 -1
- package/dist/notifications/feedback-notification-types-labels.js.map +1 -1
- package/dist/notifications/feedback-notification-types.d.ts +11 -5
- package/dist/notifications/feedback-notification-types.js +2 -1
- package/dist/notifications/feedback-notification-types.js.map +1 -1
- package/dist/notifications/notification-bell.d.ts +33 -0
- package/dist/notifications/notification-bell.js +74 -0
- package/dist/notifications/notification-bell.js.map +1 -0
- package/dist/notifications/notification-inbox.d.ts +77 -0
- package/dist/notifications/notification-inbox.js +206 -0
- package/dist/notifications/notification-inbox.js.map +1 -0
- package/dist/notifications/notification-types-setting.d.ts +6 -4
- package/dist/notifications/notification-types-setting.js +103 -45
- package/dist/notifications/notification-types-setting.js.map +1 -1
- package/dist/notifications/notification-types.d.ts +19 -7
- package/dist/notifications/notifications-labels.d.ts +41 -7
- package/dist/notifications/notifications-labels.js +18 -1
- package/dist/notifications/notifications-labels.js.map +1 -1
- package/dist/notifications/push-devices-setting.d.ts +20 -3
- package/dist/notifications/push-devices-setting.js +93 -33
- package/dist/notifications/push-devices-setting.js.map +1 -1
- package/dist/notifications/push-worker.d.ts +108 -0
- package/dist/notifications/push-worker.js +62 -0
- package/dist/notifications/push-worker.js.map +1 -0
- package/dist/notifications/quiet-hours-setting.d.ts +29 -17
- package/dist/notifications/quiet-hours-setting.js +9 -41
- package/dist/notifications/quiet-hours-setting.js.map +1 -1
- package/dist/notifications/time-zone-select.d.ts +5 -2
- package/dist/notifications/time-zone-select.js.map +1 -1
- package/dist/notifications/use-push-device.d.ts +4 -17
- package/dist/notifications/use-push-device.js +7 -15
- package/dist/notifications/use-push-device.js.map +1 -1
- package/dist/offline/local-first.d.ts +33 -0
- package/dist/offline/local-first.js +39 -0
- package/dist/offline/local-first.js.map +1 -0
- package/dist/offline/pwa-update-prompt-labels.d.ts +2 -0
- package/dist/offline/pwa-update-prompt-labels.js +9 -0
- package/dist/offline/pwa-update-prompt-labels.js.map +1 -0
- package/dist/offline/pwa-update-prompt.d.ts +32 -0
- package/dist/offline/pwa-update-prompt.js +36 -0
- package/dist/offline/pwa-update-prompt.js.map +1 -0
- package/dist/offline/query-persistence.d.ts +125 -0
- package/dist/offline/query-persistence.js +183 -0
- package/dist/offline/query-persistence.js.map +1 -0
- package/dist/offline/service-worker-updates.d.ts +46 -0
- package/dist/offline/service-worker-updates.js +39 -0
- package/dist/offline/service-worker-updates.js.map +1 -0
- package/dist/offline/shared-computer-labels.d.ts +2 -0
- package/dist/offline/shared-computer-labels.js +9 -0
- package/dist/offline/shared-computer-labels.js.map +1 -0
- package/dist/offline/shared-computer.d.ts +44 -0
- package/dist/offline/shared-computer.js +51 -0
- package/dist/offline/shared-computer.js.map +1 -0
- package/dist/offline/sign-out-pending-dialog-labels.d.ts +2 -0
- package/dist/offline/sign-out-pending-dialog-labels.js +14 -0
- package/dist/offline/sign-out-pending-dialog-labels.js.map +1 -0
- package/dist/offline/sign-out-pending-dialog.d.ts +58 -0
- package/dist/offline/sign-out-pending-dialog.js +66 -0
- package/dist/offline/sign-out-pending-dialog.js.map +1 -0
- package/dist/offline.d.ts +11 -0
- package/dist/offline.js +33 -0
- package/dist/offline.js.map +1 -0
- package/dist/push-worker.d.ts +2 -0
- package/dist/push-worker.js +14 -0
- package/dist/push-worker.js.map +1 -0
- package/dist/shell/account-menu-text-size.d.ts +33 -0
- package/dist/shell/account-menu-text-size.js +51 -0
- package/dist/shell/account-menu-text-size.js.map +1 -0
- package/dist/shell/admin-menu.d.ts +24 -0
- package/dist/shell/admin-menu.js +12 -3
- package/dist/shell/admin-menu.js.map +1 -1
- package/dist/shell/top-bar-actions.d.ts +6 -2
- package/dist/shell/top-bar-actions.js +1 -0
- package/dist/shell/top-bar-actions.js.map +1 -1
- package/dist/shell.d.ts +4 -0
- package/dist/shell.js +4 -0
- package/dist/shell.js.map +1 -1
- package/dist/sync/db.d.ts +76 -0
- package/dist/sync/db.js +24 -0
- package/dist/sync/db.js.map +1 -0
- package/dist/sync/engine.d.ts +124 -0
- package/dist/sync/engine.js +474 -0
- package/dist/sync/engine.js.map +1 -0
- package/dist/sync/hooks.d.ts +30 -0
- package/dist/sync/hooks.js +67 -0
- package/dist/sync/hooks.js.map +1 -0
- package/dist/sync/testing.d.ts +28 -0
- package/dist/sync/testing.js +41 -0
- package/dist/sync/testing.js.map +1 -0
- package/dist/sync/wire.d.ts +50 -0
- package/dist/sync/wire.js +2 -0
- package/dist/sync/wire.js.map +1 -0
- package/dist/sync.d.ts +7 -0
- package/dist/sync.js +22 -0
- package/dist/sync.js.map +1 -0
- package/dist/tour/tour-catalogue.d.ts +7 -1
- package/dist/tour/tour-catalogue.js.map +1 -1
- package/dist/tour/tour-labels.js +1 -0
- package/dist/tour/tour-labels.js.map +1 -1
- package/dist/tour/tour.d.ts +30 -0
- package/dist/tour/tour.js +54 -8
- package/dist/tour/tour.js.map +1 -1
- package/dist/tour/use-tour-progress.d.ts +99 -1
- package/dist/tour/use-tour-progress.js +228 -12
- package/dist/tour/use-tour-progress.js.map +1 -1
- package/dist/tour.d.ts +2 -0
- package/dist/tour.js +2 -0
- package/dist/tour.js.map +1 -1
- package/package.json +43 -1
- package/src/admin/admin-action-log-labels.ts +9 -0
- package/src/admin/admin-action-log.tsx +41 -5
- package/src/admin/admin-area-labels.ts +20 -0
- package/src/admin/admin-overview.tsx +37 -2
- package/src/admin/mail-test-card-labels.ts +19 -0
- package/src/admin/mail-test-card.tsx +190 -0
- package/src/components/appearance-labels.ts +16 -0
- package/src/components/data-table-column-settings.tsx +2 -2
- package/src/components/data-table-head.tsx +2 -2
- package/src/components/data-table-mobile.tsx +26 -3
- package/src/components/data-table-row-actions.tsx +118 -2
- package/src/components/data-table-shared.tsx +39 -3
- package/src/components/data-table.tsx +52 -21
- package/src/components/date-format-setting.tsx +64 -0
- package/src/components/swipeable-row.tsx +8 -0
- package/src/components/tabs.tsx +4 -3
- package/src/components/translation-review-editor.tsx +2 -0
- package/src/components/translation-review-labels.ts +7 -0
- package/src/components/translation-review.tsx +102 -14
- package/src/components/write-lock-labels.ts +1 -0
- package/src/components/write-lock.tsx +36 -3
- package/src/data-table.ts +1 -0
- package/src/feedback/feedback-row-detail.tsx +18 -23
- package/src/feedback/feedback-swipe.tsx +28 -1
- package/src/i18n/defaults.ts +8 -0
- package/src/i18n/german.ts +90 -4
- package/src/i18n/kit-labels.tsx +31 -1
- package/src/i18n/locales/en.ts +13 -0
- package/src/i18n/locales/es.ts +90 -4
- package/src/i18n/locales/fr.ts +90 -4
- package/src/i18n/locales/hu.ts +86 -4
- package/src/i18n/locales/it.ts +90 -4
- package/src/i18n/locales/zh.ts +84 -2
- package/src/i18n/review.ts +15 -1
- package/src/index.ts +45 -0
- package/src/lib/date-format.ts +151 -0
- package/src/lib/format.ts +23 -6
- package/src/notifications/device-zone-report.ts +54 -0
- package/src/notifications/feedback-notification-types-labels.ts +10 -1
- package/src/notifications/feedback-notification-types.ts +12 -5
- package/src/notifications/notification-bell.tsx +116 -0
- package/src/notifications/notification-inbox.tsx +304 -0
- package/src/notifications/notification-types-setting.tsx +151 -55
- package/src/notifications/notification-types.ts +20 -8
- package/src/notifications/notifications-labels.ts +69 -11
- package/src/notifications/push-devices-setting.tsx +123 -34
- package/src/notifications/push-worker.ts +160 -0
- package/src/notifications/quiet-hours-setting.tsx +41 -58
- package/src/notifications/time-zone-select.tsx +5 -2
- package/src/notifications/use-push-device.ts +20 -33
- package/src/offline/local-first.ts +76 -0
- package/src/offline/pwa-update-prompt-labels.ts +9 -0
- package/src/offline/pwa-update-prompt.tsx +72 -0
- package/src/offline/query-persistence.ts +356 -0
- package/src/offline/service-worker-updates.ts +81 -0
- package/src/offline/shared-computer-labels.ts +8 -0
- package/src/offline/shared-computer.tsx +87 -0
- package/src/offline/sign-out-pending-dialog-labels.ts +21 -0
- package/src/offline/sign-out-pending-dialog.tsx +135 -0
- package/src/offline.ts +32 -0
- package/src/push-worker.ts +25 -0
- package/src/shell/account-menu-text-size.tsx +77 -0
- package/src/shell/admin-menu.tsx +40 -3
- package/src/shell/top-bar-actions.tsx +6 -1
- package/src/shell.ts +7 -0
- package/src/sync/db.ts +103 -0
- package/src/sync/engine.ts +699 -0
- package/src/sync/hooks.ts +93 -0
- package/src/sync/testing.ts +73 -0
- package/src/sync/wire.ts +61 -0
- package/src/sync.ts +29 -0
- package/src/tour/tour-catalogue.tsx +7 -1
- package/src/tour/tour-labels.ts +1 -0
- package/src/tour/tour.tsx +105 -9
- package/src/tour/use-tour-progress.ts +378 -12
- package/src/tour.ts +3 -0
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
"use client";
|
|
2
|
+
import { isTransientRefreshFailure } from "../lib/session-refresh.js";
|
|
3
|
+
function stampAfter(previous) {
|
|
4
|
+
const now = Date.now();
|
|
5
|
+
const prior = typeof previous === "string" ? Date.parse(previous) : Number.NaN;
|
|
6
|
+
return new Date(Number.isFinite(prior) && prior >= now ? prior + 1 : now).toISOString();
|
|
7
|
+
}
|
|
8
|
+
function isOfflineError(err) {
|
|
9
|
+
if (isTransientRefreshFailure(err)) return true;
|
|
10
|
+
if (typeof err !== "object" || err === null) return false;
|
|
11
|
+
const bag = err;
|
|
12
|
+
if (bag.isAxiosError === true || "response" in bag) return bag.response == null;
|
|
13
|
+
return err instanceof TypeError;
|
|
14
|
+
}
|
|
15
|
+
async function readLocalFirst(online, offline, onOnline) {
|
|
16
|
+
try {
|
|
17
|
+
const result = await online();
|
|
18
|
+
await onOnline?.(result);
|
|
19
|
+
return result;
|
|
20
|
+
} catch (err) {
|
|
21
|
+
if (!isOfflineError(err)) throw err;
|
|
22
|
+
return offline();
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
async function writeLocalFirst(rest, queue) {
|
|
26
|
+
try {
|
|
27
|
+
return await rest();
|
|
28
|
+
} catch (err) {
|
|
29
|
+
if (!isOfflineError(err)) throw err;
|
|
30
|
+
return queue();
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
export {
|
|
34
|
+
isOfflineError,
|
|
35
|
+
readLocalFirst,
|
|
36
|
+
stampAfter,
|
|
37
|
+
writeLocalFirst
|
|
38
|
+
};
|
|
39
|
+
//# sourceMappingURL=local-first.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/offline/local-first.ts"],"sourcesContent":["import { isTransientRefreshFailure } from \"../lib/session-refresh\";\n\n/*\n * The leaf utilities of local-first (docs/local-first-harmonization.md §2.3, 0.46): what a\n * page and a sync engine both need, with no store behind them. One module that both\n * `@eifi1/ui-kit/offline` and `@eifi1/ui-kit/sync` export, so `/sync` never loads\n * `/offline`'s TanStack and idb-keyval peers, and `/offline` never loads Dexie. It imports\n * no package at all (packaging-contract.test.ts holds that).\n */\n\n/**\n * An `updated_at` that wins Last-Write-Wins over `previous`: now, or one millisecond past\n * `previous` when that is not behind this clock (keksdose's sync-client.ts:639-643).\n *\n * `/sync` keeps the server's row when it is STRICTLY newer, comparing this device's clock\n * with the server's. A row the server just wrote carries the server's time, so an edit\n * stamped by a clock a second slow would lose and come straight back. The millisecond is\n * enough although the server keeps microseconds: `Date.parse` truncates them.\n */\nexport function stampAfter(previous: unknown): string {\n const now = Date.now();\n const prior = typeof previous === \"string\" ? Date.parse(previous) : Number.NaN;\n return new Date(Number.isFinite(prior) && prior >= now ? prior + 1 : now).toISOString();\n}\n\n/**\n * The connection, not the server, failed: the request had no answer (an axios-like error\n * without `response`, or `fetch`'s `TypeError`), or the session refresh marked a 401 as\n * passing because the server was out of reach ({@link isTransientRefreshFailure}). A real\n * HTTP answer — a 4xx or a 5xx — is never offline: the caller must see it.\n */\nexport function isOfflineError(err: unknown): boolean {\n if (isTransientRefreshFailure(err)) return true;\n if (typeof err !== \"object\" || err === null) return false;\n const bag = err as { isAxiosError?: unknown; response?: unknown };\n if (bag.isAxiosError === true || \"response\" in bag) return bag.response == null;\n return err instanceof TypeError;\n}\n\n/**\n * Read from the server, and from the device's copy only when the connection failed\n * ({@link isOfflineError}); a 4xx or 5xx still throws. `onOnline` gets the server's answer\n * before it is returned (to refresh the copy, say); a throw from it counts as a failure of\n * the online path. The plain form of keksdose's net.ts:58, without its sealed-household\n * and cold-start branches (those stay keksdose's).\n */\nexport async function readLocalFirst<T>(\n online: () => Promise<T>,\n offline: () => Promise<T>,\n onOnline?: (result: T) => void | Promise<void>,\n): Promise<T> {\n try {\n const result = await online();\n await onOnline?.(result);\n return result;\n } catch (err) {\n if (!isOfflineError(err)) throw err;\n return offline();\n }\n}\n\n/**\n * Write through the server first (`rest`), and queue the change on the device (`queue`)\n * only when the connection failed; any other failure throws, nothing queued. Online writes\n * stay server-stamped (D2). A create mints its id BEFORE calling this and sends it on both\n * paths, so a REST create that timed out after the server applied it is not created twice\n * (D16).\n */\nexport async function writeLocalFirst<T>(rest: () => Promise<T>, queue: () => Promise<T>): Promise<T> {\n try {\n return await rest();\n } catch (err) {\n if (!isOfflineError(err)) throw err;\n return queue();\n }\n}\n"],"mappings":";AAAA,SAAS,iCAAiC;AAmBnC,SAAS,WAAW,UAA2B;AACpD,QAAM,MAAM,KAAK,IAAI;AACrB,QAAM,QAAQ,OAAO,aAAa,WAAW,KAAK,MAAM,QAAQ,IAAI,OAAO;AAC3E,SAAO,IAAI,KAAK,OAAO,SAAS,KAAK,KAAK,SAAS,MAAM,QAAQ,IAAI,GAAG,EAAE,YAAY;AACxF;AAQO,SAAS,eAAe,KAAuB;AACpD,MAAI,0BAA0B,GAAG,EAAG,QAAO;AAC3C,MAAI,OAAO,QAAQ,YAAY,QAAQ,KAAM,QAAO;AACpD,QAAM,MAAM;AACZ,MAAI,IAAI,iBAAiB,QAAQ,cAAc,IAAK,QAAO,IAAI,YAAY;AAC3E,SAAO,eAAe;AACxB;AASA,eAAsB,eACpB,QACA,SACA,UACY;AACZ,MAAI;AACF,UAAM,SAAS,MAAM,OAAO;AAC5B,UAAM,WAAW,MAAM;AACvB,WAAO;AAAA,EACT,SAAS,KAAK;AACZ,QAAI,CAAC,eAAe,GAAG,EAAG,OAAM;AAChC,WAAO,QAAQ;AAAA,EACjB;AACF;AASA,eAAsB,gBAAmB,MAAwB,OAAqC;AACpG,MAAI;AACF,WAAO,MAAM,KAAK;AAAA,EACpB,SAAS,KAAK;AACZ,QAAI,CAAC,eAAe,GAAG,EAAG,OAAM;AAChC,WAAO,MAAM;AAAA,EACf;AACF;","names":[]}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/offline/pwa-update-prompt-labels.ts"],"sourcesContent":["// The English words of ./pwa-update-prompt, in a module with no component code (0.34, KS U8).\n// keksdose's reviewed words (pwa.updateAvailable, pwa.reload) are the canon.\n\nimport type { PwaUpdatePromptLabels } from \"./pwa-update-prompt\";\n\nexport const DEFAULT_PWA_UPDATE_PROMPT_LABELS: PwaUpdatePromptLabels = {\n updateAvailable: \"A new version is available.\",\n reload: \"Reload\",\n};\n"],"mappings":";AAKO,MAAM,mCAA0D;AAAA,EACrE,iBAAiB;AAAA,EACjB,QAAQ;AACV;","names":[]}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { type LabelOverride } from "../i18n/kit-labels.js";
|
|
2
|
+
import { DEFAULT_PWA_UPDATE_PROMPT_LABELS } from "./pwa-update-prompt-labels.js";
|
|
3
|
+
/**
|
|
4
|
+
* "A new version is available. — Reload": keksdose's service-worker toast
|
|
5
|
+
* (app/pwa-update-prompt.tsx) as a kit component (docs/local-first-harmonization.md §1.5
|
|
6
|
+
* D8). The app keeps `useRegisterSW` (vite-plugin-pwa, `registerType: "prompt"`) and hands
|
|
7
|
+
* its state in: `needRefresh` from it, `onReload` = `updateServiceWorker(true)`,
|
|
8
|
+
* `onDismiss` = `setNeedRefresh(false)`.
|
|
9
|
+
*
|
|
10
|
+
* `hold` defers the prompt while a reload would hurt — a handover being signed, a tour
|
|
11
|
+
* running. Nothing shows while it holds; the toast appears once it drops. A hold that
|
|
12
|
+
* starts while the toast is up takes it down again until it drops.
|
|
13
|
+
*
|
|
14
|
+
* Renders nothing itself: the toast needs a mounted `<Toaster>`.
|
|
15
|
+
*/
|
|
16
|
+
export interface PwaUpdatePromptLabels {
|
|
17
|
+
updateAvailable: string;
|
|
18
|
+
reload: string;
|
|
19
|
+
}
|
|
20
|
+
export { DEFAULT_PWA_UPDATE_PROMPT_LABELS };
|
|
21
|
+
export interface PwaUpdatePromptProps {
|
|
22
|
+
/** A new service worker is waiting. */
|
|
23
|
+
needRefresh: boolean;
|
|
24
|
+
/** Activates it and reloads — `updateServiceWorker(true)`. */
|
|
25
|
+
onReload: () => void;
|
|
26
|
+
/** The toast was closed without reloading. */
|
|
27
|
+
onDismiss?: () => void;
|
|
28
|
+
/** Wait: a handover is open, a tour runs. */
|
|
29
|
+
hold?: boolean;
|
|
30
|
+
labels?: LabelOverride<PwaUpdatePromptLabels>;
|
|
31
|
+
}
|
|
32
|
+
export declare function PwaUpdatePrompt({ needRefresh, onReload, onDismiss, hold, labels: labelsProp }: PwaUpdatePromptProps): null;
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
"use client";
|
|
2
|
+
import { useEffect, useRef } from "react";
|
|
3
|
+
import { useKitLabels } from "../i18n/kit-labels.js";
|
|
4
|
+
import { toast } from "../components/toast.js";
|
|
5
|
+
import { DEFAULT_PWA_UPDATE_PROMPT_LABELS } from "./pwa-update-prompt-labels.js";
|
|
6
|
+
const PWA_UPDATE_TOAST_ID = "pwa-update";
|
|
7
|
+
function PwaUpdatePrompt({ needRefresh, onReload, onDismiss, hold = false, labels: labelsProp }) {
|
|
8
|
+
const labels = useKitLabels("pwaUpdate", DEFAULT_PWA_UPDATE_PROMPT_LABELS, labelsProp);
|
|
9
|
+
const handlers = useRef({ onReload, onDismiss });
|
|
10
|
+
useEffect(() => {
|
|
11
|
+
handlers.current = { onReload, onDismiss };
|
|
12
|
+
});
|
|
13
|
+
const show = needRefresh && !hold;
|
|
14
|
+
useEffect(() => {
|
|
15
|
+
if (!show) return;
|
|
16
|
+
let ours = false;
|
|
17
|
+
toast(labels.updateAvailable, {
|
|
18
|
+
id: PWA_UPDATE_TOAST_ID,
|
|
19
|
+
duration: Infinity,
|
|
20
|
+
action: { label: labels.reload, onClick: () => handlers.current.onReload() },
|
|
21
|
+
onDismiss: () => {
|
|
22
|
+
if (!ours) handlers.current.onDismiss?.();
|
|
23
|
+
}
|
|
24
|
+
});
|
|
25
|
+
return () => {
|
|
26
|
+
ours = true;
|
|
27
|
+
toast.dismiss(PWA_UPDATE_TOAST_ID);
|
|
28
|
+
};
|
|
29
|
+
}, [show, labels.updateAvailable, labels.reload]);
|
|
30
|
+
return null;
|
|
31
|
+
}
|
|
32
|
+
export {
|
|
33
|
+
DEFAULT_PWA_UPDATE_PROMPT_LABELS,
|
|
34
|
+
PwaUpdatePrompt
|
|
35
|
+
};
|
|
36
|
+
//# sourceMappingURL=pwa-update-prompt.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/offline/pwa-update-prompt.tsx"],"sourcesContent":["import { useEffect, useRef } from \"react\";\nimport { useKitLabels, type LabelOverride } from \"../i18n/kit-labels\";\nimport { toast } from \"../components/toast\";\nimport { DEFAULT_PWA_UPDATE_PROMPT_LABELS } from \"./pwa-update-prompt-labels\";\n\n/**\n * \"A new version is available. — Reload\": keksdose's service-worker toast\n * (app/pwa-update-prompt.tsx) as a kit component (docs/local-first-harmonization.md §1.5\n * D8). The app keeps `useRegisterSW` (vite-plugin-pwa, `registerType: \"prompt\"`) and hands\n * its state in: `needRefresh` from it, `onReload` = `updateServiceWorker(true)`,\n * `onDismiss` = `setNeedRefresh(false)`.\n *\n * `hold` defers the prompt while a reload would hurt — a handover being signed, a tour\n * running. Nothing shows while it holds; the toast appears once it drops. A hold that\n * starts while the toast is up takes it down again until it drops.\n *\n * Renders nothing itself: the toast needs a mounted `<Toaster>`.\n */\nexport interface PwaUpdatePromptLabels {\n updateAvailable: string;\n reload: string;\n}\n\n// Defined in ./pwa-update-prompt-labels, which holds no component code (0.34, KS U8).\nexport { DEFAULT_PWA_UPDATE_PROMPT_LABELS };\n\nexport interface PwaUpdatePromptProps {\n /** A new service worker is waiting. */\n needRefresh: boolean;\n /** Activates it and reloads — `updateServiceWorker(true)`. */\n onReload: () => void;\n /** The toast was closed without reloading. */\n onDismiss?: () => void;\n /** Wait: a handover is open, a tour runs. */\n hold?: boolean;\n labels?: LabelOverride<PwaUpdatePromptLabels>;\n}\n\n/** The toast's id: one prompt at a time, replaced in place. */\nconst PWA_UPDATE_TOAST_ID = \"pwa-update\";\n\nexport function PwaUpdatePrompt({ needRefresh, onReload, onDismiss, hold = false, labels: labelsProp }: PwaUpdatePromptProps) {\n const labels = useKitLabels(\"pwaUpdate\", DEFAULT_PWA_UPDATE_PROMPT_LABELS, labelsProp);\n // The callbacks are read at click time, so a new function each render does not\n // re-raise the toast.\n const handlers = useRef({ onReload, onDismiss });\n useEffect(() => {\n handlers.current = { onReload, onDismiss };\n });\n\n const show = needRefresh && !hold;\n useEffect(() => {\n if (!show) return;\n // sonner calls `onDismiss` for a programmatic dismiss too: the one this effect makes\n // when a hold starts must not tell the app the person waved the update away.\n let ours = false;\n toast(labels.updateAvailable, {\n id: PWA_UPDATE_TOAST_ID,\n duration: Infinity,\n action: { label: labels.reload, onClick: () => handlers.current.onReload() },\n onDismiss: () => {\n if (!ours) handlers.current.onDismiss?.();\n },\n });\n return () => {\n ours = true;\n toast.dismiss(PWA_UPDATE_TOAST_ID);\n };\n }, [show, labels.updateAvailable, labels.reload]);\n\n return null;\n}\n"],"mappings":";AAAA,SAAS,WAAW,cAAc;AAClC,SAAS,oBAAwC;AACjD,SAAS,aAAa;AACtB,SAAS,wCAAwC;AAoCjD,MAAM,sBAAsB;AAErB,SAAS,gBAAgB,EAAE,aAAa,UAAU,WAAW,OAAO,OAAO,QAAQ,WAAW,GAAyB;AAC5H,QAAM,SAAS,aAAa,aAAa,kCAAkC,UAAU;AAGrF,QAAM,WAAW,OAAO,EAAE,UAAU,UAAU,CAAC;AAC/C,YAAU,MAAM;AACd,aAAS,UAAU,EAAE,UAAU,UAAU;AAAA,EAC3C,CAAC;AAED,QAAM,OAAO,eAAe,CAAC;AAC7B,YAAU,MAAM;AACd,QAAI,CAAC,KAAM;AAGX,QAAI,OAAO;AACX,UAAM,OAAO,iBAAiB;AAAA,MAC5B,IAAI;AAAA,MACJ,UAAU;AAAA,MACV,QAAQ,EAAE,OAAO,OAAO,QAAQ,SAAS,MAAM,SAAS,QAAQ,SAAS,EAAE;AAAA,MAC3E,WAAW,MAAM;AACf,YAAI,CAAC,KAAM,UAAS,QAAQ,YAAY;AAAA,MAC1C;AAAA,IACF,CAAC;AACD,WAAO,MAAM;AACX,aAAO;AACP,YAAM,QAAQ,mBAAmB;AAAA,IACnC;AAAA,EACF,GAAG,CAAC,MAAM,OAAO,iBAAiB,OAAO,MAAM,CAAC;AAEhD,SAAO;AACT;","names":[]}
|
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
import type { QueryClient } from "@tanstack/react-query";
|
|
2
|
+
import type { PersistQueryClientOptions } from "@tanstack/react-query-persist-client";
|
|
3
|
+
/**
|
|
4
|
+
* The persisted TanStack Query cache, keksdose's policy as a kit helper
|
|
5
|
+
* (docs/local-first-harmonization.md §1.5 D4, D5, D7; §1.6). keksdose's
|
|
6
|
+
* shared/state/query-client.ts is the canon: an IndexedDB persister, a deny-list, the
|
|
7
|
+
* plain-JSON guard on write (`shouldDehydrateQuery`) and its twin on restore that keeps
|
|
8
|
+
* paused mutations. On top: a key per account (and company), a scrub list that removes
|
|
9
|
+
* secret fields from payloads that are otherwise wanted offline, and `removeStale` for
|
|
10
|
+
* another account's leftovers.
|
|
11
|
+
*
|
|
12
|
+
* The only module of the kit that imports TanStack and idb-keyval: both are optional peers
|
|
13
|
+
* of `@eifi1/ui-kit/offline` and never reached from the main barrel (packaging-contract).
|
|
14
|
+
*/
|
|
15
|
+
/** A field name the scrub removes: an exact name, or a pattern (`/^signature_/`). */
|
|
16
|
+
export type ScrubField = string | RegExp;
|
|
17
|
+
/**
|
|
18
|
+
* Removed from every query's data, at any depth, before it is persisted (D4, D7): bank
|
|
19
|
+
* account numbers and the handover protocol's signatures. A page restored offline shows
|
|
20
|
+
* such a field as missing ("Needs a connection").
|
|
21
|
+
*/
|
|
22
|
+
export declare const DEFAULT_SCRUB_FIELDS: readonly ScrubField[];
|
|
23
|
+
/** The storage the persister writes to. The default is IndexedDB through idb-keyval. */
|
|
24
|
+
export interface QueryPersistenceStorage {
|
|
25
|
+
getItem: (key: string) => Promise<string | null | undefined>;
|
|
26
|
+
setItem: (key: string, value: string) => Promise<unknown>;
|
|
27
|
+
removeItem: (key: string) => Promise<unknown>;
|
|
28
|
+
/** Every key in the store — what `removeStale` walks. */
|
|
29
|
+
keys: () => Promise<readonly unknown[]>;
|
|
30
|
+
}
|
|
31
|
+
export interface QueryPersistenceOptions {
|
|
32
|
+
/** The app's name, the key's first part: `kastlan` → `kastlan-query-cache-…`. */
|
|
33
|
+
app: string;
|
|
34
|
+
/** The signed-in account. One cache per account (D5). */
|
|
35
|
+
user: string | number;
|
|
36
|
+
/** The acting company, where the app has several (kastlan): the switch changes the key,
|
|
37
|
+
* so no wipe and no cross-company leak — provided the app switches as
|
|
38
|
+
* {@link QueryPersistence.leave} says (leave, then remount the provider per key). */
|
|
39
|
+
company?: string | number | null;
|
|
40
|
+
/** The app's own rule, beside `denyRoots` — keksdose denies one exact key and every key
|
|
41
|
+
* whose second segment is `"admin"`. `false` keeps the query out. */
|
|
42
|
+
shouldPersistKey?: (queryKey: readonly unknown[]) => boolean;
|
|
43
|
+
/** Query roots (`queryKey[0]`) that never reach the disk: admin, billing, reports… */
|
|
44
|
+
denyRoots?: readonly string[];
|
|
45
|
+
/** Replaces {@link DEFAULT_SCRUB_FIELDS}; spread it to add to it. `[]` scrubs nothing.
|
|
46
|
+
* A paused mutation whose variables carry one of these fields is never persisted (a
|
|
47
|
+
* scrubbed mutation would send something else), and one an older build wrote is dropped
|
|
48
|
+
* on restore. */
|
|
49
|
+
scrubFields?: readonly ScrubField[];
|
|
50
|
+
/** Told when a query's data is not plain JSON and is therefore not persisted. Default:
|
|
51
|
+
* `console.error`, as keksdose's `cacheSafeOrWarn`. */
|
|
52
|
+
onUnsafe?: (queryKey: readonly unknown[], data: unknown) => void;
|
|
53
|
+
/** Changes with each deploy (the app version), so a new build discards the old cache. */
|
|
54
|
+
buster: string;
|
|
55
|
+
/** How long a persisted cache is good for, in ms (keksdose: 24 h). The QueryClient's
|
|
56
|
+
* `gcTime` must be at least this, or restore drops every query. */
|
|
57
|
+
maxAge: number;
|
|
58
|
+
/** Default: IndexedDB (idb-keyval). Tests pass an in-memory one. */
|
|
59
|
+
storage?: QueryPersistenceStorage;
|
|
60
|
+
/** Default 1000 ms, as keksdose. */
|
|
61
|
+
throttleTime?: number;
|
|
62
|
+
/**
|
|
63
|
+
* 0.46 (kastlan K1): whether paused mutations are written with the cache. Default `true`
|
|
64
|
+
* (keksdose: an offline write waits in TanStack's queue and is sent after a reload).
|
|
65
|
+
* `false` keeps every mutation off the disk, and drops any an older build wrote on
|
|
66
|
+
* restore — for an app that queues offline writes in its own outbox (kastlan's Dexie
|
|
67
|
+
* outbox), instead of overriding `dehydrateOptions` by hand.
|
|
68
|
+
*/
|
|
69
|
+
persistMutations?: boolean;
|
|
70
|
+
}
|
|
71
|
+
/**
|
|
72
|
+
* One persisted cache, for one key. **Mount it per key**: the provider subscribes once and
|
|
73
|
+
* ignores a changed `persistOptions`, so give it the key as its React key —
|
|
74
|
+
*
|
|
75
|
+
* ```tsx
|
|
76
|
+
* <PersistQueryClientProvider key={persistence.key} client={queryClient} persistOptions={persistence.persistOptions}>
|
|
77
|
+
* ```
|
|
78
|
+
*
|
|
79
|
+
* — and create the persistence once the account (and company) is known (`useMemo` on
|
|
80
|
+
* them); before sign-in, mount the plain `QueryClientProvider`. On a company switch, call
|
|
81
|
+
* {@link QueryPersistence.leave} on the old one BEFORE the new key mounts, instead of a bare
|
|
82
|
+
* `queryClient.clear()`: otherwise the old subscription saves the emptied (or the next
|
|
83
|
+
* company's) cache under the old key.
|
|
84
|
+
*/
|
|
85
|
+
export interface QueryPersistence {
|
|
86
|
+
/** `<app>-query-cache-<user>[-<company>]`. */
|
|
87
|
+
key: string;
|
|
88
|
+
/** Everything `<PersistQueryClientProvider persistOptions>` needs. */
|
|
89
|
+
persistOptions: Omit<PersistQueryClientOptions, "queryClient">;
|
|
90
|
+
/** Sign-out: stops writing under this key, empties the in-memory cache and deletes this
|
|
91
|
+
* key's persisted copy. Best-effort; never throws. */
|
|
92
|
+
clear: (queryClient: QueryClient) => Promise<void>;
|
|
93
|
+
/** The company switch (or any change of key without a sign-out): stops writing under this
|
|
94
|
+
* key — a save already scheduled is dropped too — and empties the in-memory cache, so
|
|
95
|
+
* the next key's provider starts clean. The persisted copy stays for the way back. A
|
|
96
|
+
* provider that mounts this persistence again re-arms it with its restore. Never throws. */
|
|
97
|
+
leave: (queryClient: QueryClient) => Promise<void>;
|
|
98
|
+
/** At sign-in: deletes this app's OTHER persisted caches older than `maxAge` (another
|
|
99
|
+
* account's, another company's). Other apps' keys and fresh ones stay. Never throws. */
|
|
100
|
+
removeStale: () => Promise<void>;
|
|
101
|
+
}
|
|
102
|
+
export interface RemoveStaleQueryCopiesOptions {
|
|
103
|
+
/** Default: IndexedDB (idb-keyval), the store {@link createQueryPersistence} writes to. */
|
|
104
|
+
storage?: QueryPersistenceStorage;
|
|
105
|
+
/** One key to spare whatever its age — the signed-in account's own
|
|
106
|
+
* (`QueryPersistence.removeStale` passes its key). */
|
|
107
|
+
keep?: string;
|
|
108
|
+
}
|
|
109
|
+
/**
|
|
110
|
+
* 0.46 (kastlan K2): deletes this app's persisted query caches (`<app>-query-cache-…`)
|
|
111
|
+
* older than `maxAge`, with no persistence at hand — for the sign-in page, where no
|
|
112
|
+
* account is known. A session that ended with no user known (a refresh token refused at
|
|
113
|
+
* boot) cannot name its key for `clear`; this sweeps its copy once it is stale, without
|
|
114
|
+
* waiting for someone's next sign-in. Other apps' keys, other stores' keys and fresh
|
|
115
|
+
* caches stay; an unreadable one is stale. Never throws.
|
|
116
|
+
* {@link QueryPersistence.removeStale} is this with `keep` = its own key.
|
|
117
|
+
*/
|
|
118
|
+
export declare function removeStaleQueryCopies(app: string, maxAge: number, { storage, keep }?: RemoveStaleQueryCopiesOptions): Promise<void>;
|
|
119
|
+
/**
|
|
120
|
+
* True when `data` still means the same thing after JSON.stringify and JSON.parse —
|
|
121
|
+
* keksdose's `isCacheSafe` (query-client.ts:165). Class instances, Map/Set/Date/Blob, a
|
|
122
|
+
* non-finite number, a function: all refused. An `undefined` property survives.
|
|
123
|
+
*/
|
|
124
|
+
export declare function isCacheSafe(data: unknown, depth?: number): boolean;
|
|
125
|
+
export declare function createQueryPersistence({ app, user, company, shouldPersistKey, denyRoots, scrubFields, onUnsafe, buster, maxAge, storage, throttleTime, persistMutations, }: QueryPersistenceOptions): QueryPersistence;
|
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
"use client";
|
|
2
|
+
import { createAsyncStoragePersister } from "@tanstack/query-async-storage-persister";
|
|
3
|
+
import { del, get, keys, set } from "idb-keyval";
|
|
4
|
+
const DEFAULT_SCRUB_FIELDS = Object.freeze([
|
|
5
|
+
"iban",
|
|
6
|
+
"qr_iban",
|
|
7
|
+
"default_qr_iban",
|
|
8
|
+
/^signature_/
|
|
9
|
+
]);
|
|
10
|
+
const idbStorage = {
|
|
11
|
+
getItem: (key) => get(key),
|
|
12
|
+
setItem: (key, value) => set(key, value),
|
|
13
|
+
removeItem: (key) => del(key),
|
|
14
|
+
keys: () => keys()
|
|
15
|
+
};
|
|
16
|
+
async function removeStaleQueryCopies(app, maxAge, { storage = idbStorage, keep } = {}) {
|
|
17
|
+
const prefix = `${app}-query-cache-`;
|
|
18
|
+
try {
|
|
19
|
+
const now = Date.now();
|
|
20
|
+
for (const k of await storage.keys()) {
|
|
21
|
+
if (typeof k !== "string" || !k.startsWith(prefix) || k === keep) continue;
|
|
22
|
+
let timestamp = 0;
|
|
23
|
+
try {
|
|
24
|
+
const raw = await storage.getItem(k);
|
|
25
|
+
const parsed = raw ? JSON.parse(raw) : null;
|
|
26
|
+
if (parsed && typeof parsed === "object" && typeof parsed.timestamp === "number") {
|
|
27
|
+
timestamp = parsed.timestamp;
|
|
28
|
+
}
|
|
29
|
+
} catch {
|
|
30
|
+
}
|
|
31
|
+
if (now - timestamp > maxAge) await storage.removeItem(k);
|
|
32
|
+
}
|
|
33
|
+
} catch {
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
function isCacheSafe(data, depth = 0) {
|
|
37
|
+
if (depth > 12) return false;
|
|
38
|
+
if (data === null) return true;
|
|
39
|
+
const t = typeof data;
|
|
40
|
+
if (t === "string" || t === "boolean") return true;
|
|
41
|
+
if (t === "number") return Number.isFinite(data);
|
|
42
|
+
if (t !== "object") return false;
|
|
43
|
+
if (Array.isArray(data)) return data.every((v) => isCacheSafe(v, depth + 1));
|
|
44
|
+
const proto = Object.getPrototypeOf(data);
|
|
45
|
+
if (proto !== Object.prototype && proto !== null) return false;
|
|
46
|
+
return Object.values(data).every((v) => v === void 0 || isCacheSafe(v, depth + 1));
|
|
47
|
+
}
|
|
48
|
+
function scrub(data, fields) {
|
|
49
|
+
if (fields.length === 0 || data === null || typeof data !== "object") return data;
|
|
50
|
+
if (Array.isArray(data)) return data.map((v) => scrub(v, fields));
|
|
51
|
+
const out = {};
|
|
52
|
+
for (const [name, value] of Object.entries(data)) {
|
|
53
|
+
if (fields.some((f) => typeof f === "string" ? f === name : f.test(name))) continue;
|
|
54
|
+
out[name] = scrub(value, fields);
|
|
55
|
+
}
|
|
56
|
+
return out;
|
|
57
|
+
}
|
|
58
|
+
const defaultOnUnsafe = (queryKey) => {
|
|
59
|
+
console.error(
|
|
60
|
+
`[query-cache] refusing to persist ${JSON.stringify(queryKey)}: the value is not plain JSON (a class instance, Map, Set, Date or Blob). Return plain data from the queryFn and build the rich object at the call site.`
|
|
61
|
+
);
|
|
62
|
+
};
|
|
63
|
+
function createQueryPersistence({
|
|
64
|
+
app,
|
|
65
|
+
user,
|
|
66
|
+
company,
|
|
67
|
+
shouldPersistKey,
|
|
68
|
+
denyRoots = [],
|
|
69
|
+
scrubFields = DEFAULT_SCRUB_FIELDS,
|
|
70
|
+
onUnsafe = defaultOnUnsafe,
|
|
71
|
+
buster,
|
|
72
|
+
maxAge,
|
|
73
|
+
storage = idbStorage,
|
|
74
|
+
throttleTime = 1e3,
|
|
75
|
+
persistMutations = true
|
|
76
|
+
}) {
|
|
77
|
+
const prefix = `${app}-query-cache-`;
|
|
78
|
+
const key = `${prefix}${user}${company === void 0 || company === null || company === "" ? "" : `-${company}`}`;
|
|
79
|
+
const denied = new Set(denyRoots);
|
|
80
|
+
let retired = false;
|
|
81
|
+
const keyAllowed = (queryKey) => !denied.has(String(queryKey[0])) && (shouldPersistKey ? shouldPersistKey(queryKey) : true);
|
|
82
|
+
const shouldDehydrateQuery = (query) => {
|
|
83
|
+
if (query.state.status !== "success" || !keyAllowed(query.queryKey)) return false;
|
|
84
|
+
if (isCacheSafe(query.state.data)) return true;
|
|
85
|
+
onUnsafe(query.queryKey, query.state.data);
|
|
86
|
+
return false;
|
|
87
|
+
};
|
|
88
|
+
const restorable = (entry) => {
|
|
89
|
+
if (!entry || typeof entry !== "object") return null;
|
|
90
|
+
const { queryKey, state } = entry;
|
|
91
|
+
if (!Array.isArray(queryKey) || !keyAllowed(queryKey)) return null;
|
|
92
|
+
if (!isCacheSafe(state?.data)) return null;
|
|
93
|
+
return withScrubbedData(entry);
|
|
94
|
+
};
|
|
95
|
+
const carriesScrubbed = (value, depth = 0) => {
|
|
96
|
+
if (scrubFields.length === 0 || depth > 12 || value === null || typeof value !== "object") return false;
|
|
97
|
+
if (Array.isArray(value)) return value.some((v) => carriesScrubbed(v, depth + 1));
|
|
98
|
+
return Object.entries(value).some(
|
|
99
|
+
([name, v]) => scrubFields.some((f) => typeof f === "string" ? f === name : f.test(name)) || carriesScrubbed(v, depth + 1)
|
|
100
|
+
);
|
|
101
|
+
};
|
|
102
|
+
const shouldDehydrateMutation = (mutation) => persistMutations && mutation.state.isPaused && !carriesScrubbed(mutation.state.variables);
|
|
103
|
+
const withScrubbedData = (entry) => {
|
|
104
|
+
const query = entry;
|
|
105
|
+
if (!query.state || !("data" in query.state)) return entry;
|
|
106
|
+
return { ...query, state: { ...query.state, data: scrub(query.state.data, scrubFields) } };
|
|
107
|
+
};
|
|
108
|
+
const serialize = (client) => JSON.stringify({
|
|
109
|
+
...client,
|
|
110
|
+
clientState: { ...client.clientState, queries: client.clientState.queries.map(withScrubbedData) }
|
|
111
|
+
});
|
|
112
|
+
const deserialize = (raw) => {
|
|
113
|
+
const empty = { timestamp: 0, buster: "", clientState: { mutations: [], queries: [] } };
|
|
114
|
+
try {
|
|
115
|
+
const parsed = JSON.parse(raw);
|
|
116
|
+
if (!parsed || typeof parsed !== "object") return empty;
|
|
117
|
+
const { timestamp, buster: stored, clientState } = parsed;
|
|
118
|
+
if (typeof timestamp !== "number" || typeof stored !== "string") return empty;
|
|
119
|
+
if (!clientState || typeof clientState !== "object" || !Array.isArray(clientState.queries)) return empty;
|
|
120
|
+
return {
|
|
121
|
+
timestamp,
|
|
122
|
+
buster: stored,
|
|
123
|
+
clientState: {
|
|
124
|
+
mutations: persistMutations && Array.isArray(clientState.mutations) ? clientState.mutations.filter(
|
|
125
|
+
(m) => !carriesScrubbed(m?.state?.variables)
|
|
126
|
+
) : [],
|
|
127
|
+
queries: clientState.queries.map(restorable).filter((q) => q !== null)
|
|
128
|
+
}
|
|
129
|
+
};
|
|
130
|
+
} catch {
|
|
131
|
+
return empty;
|
|
132
|
+
}
|
|
133
|
+
};
|
|
134
|
+
const persister = createAsyncStoragePersister({
|
|
135
|
+
storage: {
|
|
136
|
+
// Only the provider's restore reads: mounting this persistence again re-arms it.
|
|
137
|
+
getItem: async (k) => {
|
|
138
|
+
retired = false;
|
|
139
|
+
return await storage.getItem(k) ?? null;
|
|
140
|
+
},
|
|
141
|
+
setItem: async (k, v) => {
|
|
142
|
+
if (!retired) await storage.setItem(k, v);
|
|
143
|
+
},
|
|
144
|
+
removeItem: async (k) => {
|
|
145
|
+
await storage.removeItem(k);
|
|
146
|
+
}
|
|
147
|
+
},
|
|
148
|
+
key,
|
|
149
|
+
throttleTime,
|
|
150
|
+
serialize,
|
|
151
|
+
deserialize
|
|
152
|
+
});
|
|
153
|
+
const leave = async (queryClient) => {
|
|
154
|
+
retired = true;
|
|
155
|
+
try {
|
|
156
|
+
queryClient.clear();
|
|
157
|
+
} catch {
|
|
158
|
+
}
|
|
159
|
+
};
|
|
160
|
+
const clear = async (queryClient) => {
|
|
161
|
+
retired = true;
|
|
162
|
+
try {
|
|
163
|
+
queryClient.clear();
|
|
164
|
+
await persister.removeClient();
|
|
165
|
+
} catch {
|
|
166
|
+
}
|
|
167
|
+
};
|
|
168
|
+
const removeStale = () => removeStaleQueryCopies(app, maxAge, { storage, keep: key });
|
|
169
|
+
return {
|
|
170
|
+
key,
|
|
171
|
+
persistOptions: { persister, maxAge, buster, dehydrateOptions: { shouldDehydrateQuery, shouldDehydrateMutation } },
|
|
172
|
+
clear,
|
|
173
|
+
leave,
|
|
174
|
+
removeStale
|
|
175
|
+
};
|
|
176
|
+
}
|
|
177
|
+
export {
|
|
178
|
+
DEFAULT_SCRUB_FIELDS,
|
|
179
|
+
createQueryPersistence,
|
|
180
|
+
isCacheSafe,
|
|
181
|
+
removeStaleQueryCopies
|
|
182
|
+
};
|
|
183
|
+
//# sourceMappingURL=query-persistence.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/offline/query-persistence.ts"],"sourcesContent":["import { createAsyncStoragePersister } from \"@tanstack/query-async-storage-persister\";\nimport type { QueryClient } from \"@tanstack/react-query\";\nimport type { PersistedClient, PersistQueryClientOptions } from \"@tanstack/react-query-persist-client\";\nimport { del, get, keys, set } from \"idb-keyval\";\n\n/**\n * The persisted TanStack Query cache, keksdose's policy as a kit helper\n * (docs/local-first-harmonization.md §1.5 D4, D5, D7; §1.6). keksdose's\n * shared/state/query-client.ts is the canon: an IndexedDB persister, a deny-list, the\n * plain-JSON guard on write (`shouldDehydrateQuery`) and its twin on restore that keeps\n * paused mutations. On top: a key per account (and company), a scrub list that removes\n * secret fields from payloads that are otherwise wanted offline, and `removeStale` for\n * another account's leftovers.\n *\n * The only module of the kit that imports TanStack and idb-keyval: both are optional peers\n * of `@eifi1/ui-kit/offline` and never reached from the main barrel (packaging-contract).\n */\n\n/** A field name the scrub removes: an exact name, or a pattern (`/^signature_/`). */\nexport type ScrubField = string | RegExp;\n\n/**\n * Removed from every query's data, at any depth, before it is persisted (D4, D7): bank\n * account numbers and the handover protocol's signatures. A page restored offline shows\n * such a field as missing (\"Needs a connection\").\n */\nexport const DEFAULT_SCRUB_FIELDS: readonly ScrubField[] = Object.freeze([\n \"iban\",\n \"qr_iban\",\n \"default_qr_iban\",\n /^signature_/,\n]);\n\n/** The storage the persister writes to. The default is IndexedDB through idb-keyval. */\nexport interface QueryPersistenceStorage {\n getItem: (key: string) => Promise<string | null | undefined>;\n setItem: (key: string, value: string) => Promise<unknown>;\n removeItem: (key: string) => Promise<unknown>;\n /** Every key in the store — what `removeStale` walks. */\n keys: () => Promise<readonly unknown[]>;\n}\n\nexport interface QueryPersistenceOptions {\n /** The app's name, the key's first part: `kastlan` → `kastlan-query-cache-…`. */\n app: string;\n /** The signed-in account. One cache per account (D5). */\n user: string | number;\n /** The acting company, where the app has several (kastlan): the switch changes the key,\n * so no wipe and no cross-company leak — provided the app switches as\n * {@link QueryPersistence.leave} says (leave, then remount the provider per key). */\n company?: string | number | null;\n /** The app's own rule, beside `denyRoots` — keksdose denies one exact key and every key\n * whose second segment is `\"admin\"`. `false` keeps the query out. */\n shouldPersistKey?: (queryKey: readonly unknown[]) => boolean;\n /** Query roots (`queryKey[0]`) that never reach the disk: admin, billing, reports… */\n denyRoots?: readonly string[];\n /** Replaces {@link DEFAULT_SCRUB_FIELDS}; spread it to add to it. `[]` scrubs nothing.\n * A paused mutation whose variables carry one of these fields is never persisted (a\n * scrubbed mutation would send something else), and one an older build wrote is dropped\n * on restore. */\n scrubFields?: readonly ScrubField[];\n /** Told when a query's data is not plain JSON and is therefore not persisted. Default:\n * `console.error`, as keksdose's `cacheSafeOrWarn`. */\n onUnsafe?: (queryKey: readonly unknown[], data: unknown) => void;\n /** Changes with each deploy (the app version), so a new build discards the old cache. */\n buster: string;\n /** How long a persisted cache is good for, in ms (keksdose: 24 h). The QueryClient's\n * `gcTime` must be at least this, or restore drops every query. */\n maxAge: number;\n /** Default: IndexedDB (idb-keyval). Tests pass an in-memory one. */\n storage?: QueryPersistenceStorage;\n /** Default 1000 ms, as keksdose. */\n throttleTime?: number;\n /**\n * 0.46 (kastlan K1): whether paused mutations are written with the cache. Default `true`\n * (keksdose: an offline write waits in TanStack's queue and is sent after a reload).\n * `false` keeps every mutation off the disk, and drops any an older build wrote on\n * restore — for an app that queues offline writes in its own outbox (kastlan's Dexie\n * outbox), instead of overriding `dehydrateOptions` by hand.\n */\n persistMutations?: boolean;\n}\n\n/**\n * One persisted cache, for one key. **Mount it per key**: the provider subscribes once and\n * ignores a changed `persistOptions`, so give it the key as its React key —\n *\n * ```tsx\n * <PersistQueryClientProvider key={persistence.key} client={queryClient} persistOptions={persistence.persistOptions}>\n * ```\n *\n * — and create the persistence once the account (and company) is known (`useMemo` on\n * them); before sign-in, mount the plain `QueryClientProvider`. On a company switch, call\n * {@link QueryPersistence.leave} on the old one BEFORE the new key mounts, instead of a bare\n * `queryClient.clear()`: otherwise the old subscription saves the emptied (or the next\n * company's) cache under the old key.\n */\nexport interface QueryPersistence {\n /** `<app>-query-cache-<user>[-<company>]`. */\n key: string;\n /** Everything `<PersistQueryClientProvider persistOptions>` needs. */\n persistOptions: Omit<PersistQueryClientOptions, \"queryClient\">;\n /** Sign-out: stops writing under this key, empties the in-memory cache and deletes this\n * key's persisted copy. Best-effort; never throws. */\n clear: (queryClient: QueryClient) => Promise<void>;\n /** The company switch (or any change of key without a sign-out): stops writing under this\n * key — a save already scheduled is dropped too — and empties the in-memory cache, so\n * the next key's provider starts clean. The persisted copy stays for the way back. A\n * provider that mounts this persistence again re-arms it with its restore. Never throws. */\n leave: (queryClient: QueryClient) => Promise<void>;\n /** At sign-in: deletes this app's OTHER persisted caches older than `maxAge` (another\n * account's, another company's). Other apps' keys and fresh ones stay. Never throws. */\n removeStale: () => Promise<void>;\n}\n\nconst idbStorage: QueryPersistenceStorage = {\n getItem: (key) => get<string>(key),\n setItem: (key, value) => set(key, value),\n removeItem: (key) => del(key),\n keys: () => keys(),\n};\n\nexport interface RemoveStaleQueryCopiesOptions {\n /** Default: IndexedDB (idb-keyval), the store {@link createQueryPersistence} writes to. */\n storage?: QueryPersistenceStorage;\n /** One key to spare whatever its age — the signed-in account's own\n * (`QueryPersistence.removeStale` passes its key). */\n keep?: string;\n}\n\n/**\n * 0.46 (kastlan K2): deletes this app's persisted query caches (`<app>-query-cache-…`)\n * older than `maxAge`, with no persistence at hand — for the sign-in page, where no\n * account is known. A session that ended with no user known (a refresh token refused at\n * boot) cannot name its key for `clear`; this sweeps its copy once it is stale, without\n * waiting for someone's next sign-in. Other apps' keys, other stores' keys and fresh\n * caches stay; an unreadable one is stale. Never throws.\n * {@link QueryPersistence.removeStale} is this with `keep` = its own key.\n */\nexport async function removeStaleQueryCopies(\n app: string,\n maxAge: number,\n { storage = idbStorage, keep }: RemoveStaleQueryCopiesOptions = {},\n): Promise<void> {\n const prefix = `${app}-query-cache-`;\n try {\n const now = Date.now();\n for (const k of await storage.keys()) {\n if (typeof k !== \"string\" || !k.startsWith(prefix) || k === keep) continue;\n let timestamp = 0;\n try {\n const raw = await storage.getItem(k);\n const parsed: unknown = raw ? JSON.parse(raw) : null;\n if (parsed && typeof parsed === \"object\" && typeof (parsed as PersistedClient).timestamp === \"number\") {\n timestamp = (parsed as PersistedClient).timestamp;\n }\n } catch {\n /* unreadable: stale */\n }\n if (now - timestamp > maxAge) await storage.removeItem(k);\n }\n } catch {\n /* best-effort */\n }\n}\n\n/**\n * True when `data` still means the same thing after JSON.stringify and JSON.parse —\n * keksdose's `isCacheSafe` (query-client.ts:165). Class instances, Map/Set/Date/Blob, a\n * non-finite number, a function: all refused. An `undefined` property survives.\n */\nexport function isCacheSafe(data: unknown, depth = 0): boolean {\n if (depth > 12) return false;\n if (data === null) return true;\n const t = typeof data;\n if (t === \"string\" || t === \"boolean\") return true;\n if (t === \"number\") return Number.isFinite(data as number);\n if (t !== \"object\") return false;\n if (Array.isArray(data)) return data.every((v) => isCacheSafe(v, depth + 1));\n const proto: unknown = Object.getPrototypeOf(data);\n if (proto !== Object.prototype && proto !== null) return false;\n return Object.values(data as Record<string, unknown>).every((v) => v === undefined || isCacheSafe(v, depth + 1));\n}\n\n/** A copy of `data` without the scrubbed fields, at any depth. The input is not touched. */\nfunction scrub(data: unknown, fields: readonly ScrubField[]): unknown {\n if (fields.length === 0 || data === null || typeof data !== \"object\") return data;\n if (Array.isArray(data)) return data.map((v) => scrub(v, fields));\n const out: Record<string, unknown> = {};\n for (const [name, value] of Object.entries(data as Record<string, unknown>)) {\n if (fields.some((f) => (typeof f === \"string\" ? f === name : f.test(name)))) continue;\n out[name] = scrub(value, fields);\n }\n return out;\n}\n\nconst defaultOnUnsafe = (queryKey: readonly unknown[]) => {\n console.error(\n `[query-cache] refusing to persist ${JSON.stringify(queryKey)}: the value is not plain JSON ` +\n `(a class instance, Map, Set, Date or Blob). Return plain data from the queryFn and build ` +\n `the rich object at the call site.`,\n );\n};\n\nexport function createQueryPersistence({\n app,\n user,\n company,\n shouldPersistKey,\n denyRoots = [],\n scrubFields = DEFAULT_SCRUB_FIELDS,\n onUnsafe = defaultOnUnsafe,\n buster,\n maxAge,\n storage = idbStorage,\n throttleTime = 1000,\n persistMutations = true,\n}: QueryPersistenceOptions): QueryPersistence {\n const prefix = `${app}-query-cache-`;\n const key = `${prefix}${user}${company === undefined || company === null || company === \"\" ? \"\" : `-${company}`}`;\n const denied = new Set(denyRoots);\n // Set by `leave` and `clear`: a write under this key after the person left it (a\n // throttled save of the emptied cache) is dropped. A restore re-arms it.\n let retired = false;\n\n const keyAllowed = (queryKey: readonly unknown[]) =>\n !denied.has(String(queryKey[0])) && (shouldPersistKey ? shouldPersistKey(queryKey) : true);\n\n /** The write side: a success, an allowed key, plain JSON (or the warning). */\n const shouldDehydrateQuery = (query: {\n queryKey: readonly unknown[];\n state: { status: string; data?: unknown };\n }): boolean => {\n if (query.state.status !== \"success\" || !keyAllowed(query.queryKey)) return false;\n if (isCacheSafe(query.state.data)) return true;\n onUnsafe(query.queryKey, query.state.data);\n return false;\n };\n\n /** One persisted query entry, scrubbed; `null` when it may not be restored. */\n const restorable = (entry: unknown): unknown => {\n if (!entry || typeof entry !== \"object\") return null;\n const { queryKey, state } = entry as { queryKey?: unknown; state?: { data?: unknown } };\n if (!Array.isArray(queryKey) || !keyAllowed(queryKey)) return null;\n if (!isCacheSafe(state?.data)) return null;\n return withScrubbedData(entry);\n };\n\n /** Whether `value` has a scrubbed field's name anywhere in it. */\n const carriesScrubbed = (value: unknown, depth = 0): boolean => {\n if (scrubFields.length === 0 || depth > 12 || value === null || typeof value !== \"object\") return false;\n if (Array.isArray(value)) return value.some((v) => carriesScrubbed(v, depth + 1));\n return Object.entries(value as Record<string, unknown>).some(\n ([name, v]) =>\n scrubFields.some((f) => (typeof f === \"string\" ? f === name : f.test(name))) || carriesScrubbed(v, depth + 1),\n );\n };\n\n /** The write side for mutations: TanStack's default (paused ones), minus any whose\n * variables carry a scrubbed field (S6); none at all with `persistMutations: false`. */\n const shouldDehydrateMutation = (mutation: { state: { isPaused: boolean; variables?: unknown } }): boolean =>\n persistMutations && mutation.state.isPaused && !carriesScrubbed(mutation.state.variables);\n\n const withScrubbedData = (entry: unknown): unknown => {\n const query = entry as { state?: { data?: unknown } };\n if (!query.state || !(\"data\" in query.state)) return entry;\n return { ...query, state: { ...query.state, data: scrub(query.state.data, scrubFields) } };\n };\n\n // The scrub on the way OUT: the in-memory cache keeps the field (the page that is open\n // shows it), the disk never sees it. Mutations are a paused write queue and are kept\n // whole — scrubbing one would change what it sends — so one carrying a scrubbed field is\n // not written at all (`shouldDehydrateMutation`).\n const serialize = (client: PersistedClient): string =>\n JSON.stringify({\n ...client,\n clientState: { ...client.clientState, queries: client.clientState.queries.map(withScrubbedData) },\n });\n\n // The twin on the way IN (keksdose's `sanitizePersistedCache`, :264-298): an older build\n // wrote what this one may deny. Never throws; an unreadable blob comes back with\n // `timestamp: 0`, which the restore treats as unusable and removes.\n const deserialize = (raw: string): PersistedClient => {\n const empty: PersistedClient = { timestamp: 0, buster: \"\", clientState: { mutations: [], queries: [] } };\n try {\n const parsed: unknown = JSON.parse(raw);\n if (!parsed || typeof parsed !== \"object\") return empty;\n const { timestamp, buster: stored, clientState } = parsed as Partial<PersistedClient>;\n if (typeof timestamp !== \"number\" || typeof stored !== \"string\") return empty;\n if (!clientState || typeof clientState !== \"object\" || !Array.isArray(clientState.queries)) return empty;\n return {\n timestamp,\n buster: stored,\n clientState: {\n mutations: persistMutations && Array.isArray(clientState.mutations)\n ? clientState.mutations.filter(\n (m) => !carriesScrubbed((m as { state?: { variables?: unknown } } | null)?.state?.variables),\n )\n : [],\n queries: clientState.queries.map(restorable).filter((q) => q !== null) as PersistedClient[\"clientState\"][\"queries\"],\n },\n };\n } catch {\n return empty;\n }\n };\n\n const persister = createAsyncStoragePersister({\n storage: {\n // Only the provider's restore reads: mounting this persistence again re-arms it.\n getItem: async (k) => {\n retired = false;\n return (await storage.getItem(k)) ?? null;\n },\n setItem: async (k, v) => {\n if (!retired) await storage.setItem(k, v);\n },\n removeItem: async (k) => {\n await storage.removeItem(k);\n },\n },\n key,\n throttleTime,\n serialize,\n deserialize,\n });\n\n const leave = async (queryClient: QueryClient) => {\n retired = true;\n try {\n queryClient.clear();\n } catch {\n /* best-effort */\n }\n };\n\n const clear = async (queryClient: QueryClient) => {\n retired = true;\n try {\n queryClient.clear();\n await persister.removeClient();\n } catch {\n /* best-effort: private mode / IndexedDB unavailable */\n }\n };\n\n const removeStale = () => removeStaleQueryCopies(app, maxAge, { storage, keep: key });\n\n return {\n key,\n persistOptions: { persister, maxAge, buster, dehydrateOptions: { shouldDehydrateQuery, shouldDehydrateMutation } },\n clear,\n leave,\n removeStale,\n };\n}\n"],"mappings":";AAAA,SAAS,mCAAmC;AAG5C,SAAS,KAAK,KAAK,MAAM,WAAW;AAuB7B,MAAM,uBAA8C,OAAO,OAAO;AAAA,EACvE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,CAAC;AAoFD,MAAM,aAAsC;AAAA,EAC1C,SAAS,CAAC,QAAQ,IAAY,GAAG;AAAA,EACjC,SAAS,CAAC,KAAK,UAAU,IAAI,KAAK,KAAK;AAAA,EACvC,YAAY,CAAC,QAAQ,IAAI,GAAG;AAAA,EAC5B,MAAM,MAAM,KAAK;AACnB;AAmBA,eAAsB,uBACpB,KACA,QACA,EAAE,UAAU,YAAY,KAAK,IAAmC,CAAC,GAClD;AACf,QAAM,SAAS,GAAG,GAAG;AACrB,MAAI;AACF,UAAM,MAAM,KAAK,IAAI;AACrB,eAAW,KAAK,MAAM,QAAQ,KAAK,GAAG;AACpC,UAAI,OAAO,MAAM,YAAY,CAAC,EAAE,WAAW,MAAM,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,IAAI,CAAC;AAEpF,SAAO;AAAA,IACL;AAAA,IACA,gBAAgB,EAAE,WAAW,QAAQ,QAAQ,kBAAkB,EAAE,sBAAsB,wBAAwB,EAAE;AAAA,IACjH;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;","names":[]}
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* vite-plugin-pwa's `registerSW` from `virtual:pwa-register` (`registerType: "prompt"`) —
|
|
3
|
+
* the app passes it in, since a virtual module is the app's build's, not the kit's. It
|
|
4
|
+
* answers the `updateSW(reloadPage)` function.
|
|
5
|
+
*/
|
|
6
|
+
export type RegisterServiceWorker = (options: {
|
|
7
|
+
onNeedRefresh?: () => void;
|
|
8
|
+
onOfflineReady?: () => void;
|
|
9
|
+
}) => (reloadPage?: boolean) => Promise<void>;
|
|
10
|
+
/** What {@link createServiceWorkerUpdates} answers: one store per app, a module constant. */
|
|
11
|
+
export interface ServiceWorkerUpdates {
|
|
12
|
+
/** Registers the service worker — once, however often it is called. Call it at start,
|
|
13
|
+
* before the router renders, so the sign-in pages get the offline shell too. */
|
|
14
|
+
start: () => void;
|
|
15
|
+
/** Whether a new version waits. */
|
|
16
|
+
needRefresh: () => boolean;
|
|
17
|
+
/** For `useSyncExternalStore`. */
|
|
18
|
+
subscribe: (listener: () => void) => () => void;
|
|
19
|
+
/** Activates the waiting version and reloads (`updateSW(true)`). Before `start`, nothing. */
|
|
20
|
+
reload: () => void;
|
|
21
|
+
/** The person closed the prompt: the version keeps waiting, the prompt stays down. */
|
|
22
|
+
dismiss: () => void;
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* 0.46 (kastlan K3, docs/local-first-harmonization.md §1.5 D8): the service worker
|
|
26
|
+
* registered ONCE AT START, and its "a new version waits" state as a small store the
|
|
27
|
+
* prompt reads wherever it lives. vite-plugin-pwa's `useRegisterSW` registers when the
|
|
28
|
+
* component that calls it mounts: an app whose {@link PwaUpdatePrompt} sits in its
|
|
29
|
+
* signed-in shell (it reads the tour state, the route) would register only after sign-in,
|
|
30
|
+
* and the sign-in pages would lose the offline shell on a first visit.
|
|
31
|
+
*
|
|
32
|
+
* ```ts
|
|
33
|
+
* // shared/pwa/sw-updates.ts
|
|
34
|
+
* import { registerSW } from "virtual:pwa-register";
|
|
35
|
+
* export const swUpdates = createServiceWorkerUpdates(registerSW);
|
|
36
|
+
* // main.tsx, before render: swUpdates.start();
|
|
37
|
+
* // the shell: <PwaUpdatePrompt {...useServiceWorkerUpdate(swUpdates)} hold={tourRunning} />
|
|
38
|
+
* ```
|
|
39
|
+
*/
|
|
40
|
+
export declare function createServiceWorkerUpdates(register: RegisterServiceWorker): ServiceWorkerUpdates;
|
|
41
|
+
/** {@link PwaUpdatePrompt}'s props from the store: `needRefresh`, `onReload`, `onDismiss`. */
|
|
42
|
+
export declare function useServiceWorkerUpdate(updates: ServiceWorkerUpdates): {
|
|
43
|
+
needRefresh: boolean;
|
|
44
|
+
onReload: () => void;
|
|
45
|
+
onDismiss: () => void;
|
|
46
|
+
};
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
"use client";
|
|
2
|
+
import { useSyncExternalStore } from "react";
|
|
3
|
+
function createServiceWorkerUpdates(register) {
|
|
4
|
+
let waiting = false;
|
|
5
|
+
let update = null;
|
|
6
|
+
const listeners = /* @__PURE__ */ new Set();
|
|
7
|
+
const emit = () => listeners.forEach((listener) => listener());
|
|
8
|
+
const set = (value) => {
|
|
9
|
+
if (waiting === value) return;
|
|
10
|
+
waiting = value;
|
|
11
|
+
emit();
|
|
12
|
+
};
|
|
13
|
+
return {
|
|
14
|
+
start: () => {
|
|
15
|
+
if (update) return;
|
|
16
|
+
update = register({ onNeedRefresh: () => set(true) });
|
|
17
|
+
},
|
|
18
|
+
needRefresh: () => waiting,
|
|
19
|
+
subscribe: (listener) => {
|
|
20
|
+
listeners.add(listener);
|
|
21
|
+
return () => {
|
|
22
|
+
listeners.delete(listener);
|
|
23
|
+
};
|
|
24
|
+
},
|
|
25
|
+
reload: () => {
|
|
26
|
+
void update?.(true);
|
|
27
|
+
},
|
|
28
|
+
dismiss: () => set(false)
|
|
29
|
+
};
|
|
30
|
+
}
|
|
31
|
+
function useServiceWorkerUpdate(updates) {
|
|
32
|
+
const needRefresh = useSyncExternalStore(updates.subscribe, updates.needRefresh, () => false);
|
|
33
|
+
return { needRefresh, onReload: updates.reload, onDismiss: updates.dismiss };
|
|
34
|
+
}
|
|
35
|
+
export {
|
|
36
|
+
createServiceWorkerUpdates,
|
|
37
|
+
useServiceWorkerUpdate
|
|
38
|
+
};
|
|
39
|
+
//# sourceMappingURL=service-worker-updates.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/offline/service-worker-updates.ts"],"sourcesContent":["import { useSyncExternalStore } from \"react\";\n\n/**\n * vite-plugin-pwa's `registerSW` from `virtual:pwa-register` (`registerType: \"prompt\"`) —\n * the app passes it in, since a virtual module is the app's build's, not the kit's. It\n * answers the `updateSW(reloadPage)` function.\n */\nexport type RegisterServiceWorker = (options: {\n onNeedRefresh?: () => void;\n onOfflineReady?: () => void;\n}) => (reloadPage?: boolean) => Promise<void>;\n\n/** What {@link createServiceWorkerUpdates} answers: one store per app, a module constant. */\nexport interface ServiceWorkerUpdates {\n /** Registers the service worker — once, however often it is called. Call it at start,\n * before the router renders, so the sign-in pages get the offline shell too. */\n start: () => void;\n /** Whether a new version waits. */\n needRefresh: () => boolean;\n /** For `useSyncExternalStore`. */\n subscribe: (listener: () => void) => () => void;\n /** Activates the waiting version and reloads (`updateSW(true)`). Before `start`, nothing. */\n reload: () => void;\n /** The person closed the prompt: the version keeps waiting, the prompt stays down. */\n dismiss: () => void;\n}\n\n/**\n * 0.46 (kastlan K3, docs/local-first-harmonization.md §1.5 D8): the service worker\n * registered ONCE AT START, and its \"a new version waits\" state as a small store the\n * prompt reads wherever it lives. vite-plugin-pwa's `useRegisterSW` registers when the\n * component that calls it mounts: an app whose {@link PwaUpdatePrompt} sits in its\n * signed-in shell (it reads the tour state, the route) would register only after sign-in,\n * and the sign-in pages would lose the offline shell on a first visit.\n *\n * ```ts\n * // shared/pwa/sw-updates.ts\n * import { registerSW } from \"virtual:pwa-register\";\n * export const swUpdates = createServiceWorkerUpdates(registerSW);\n * // main.tsx, before render: swUpdates.start();\n * // the shell: <PwaUpdatePrompt {...useServiceWorkerUpdate(swUpdates)} hold={tourRunning} />\n * ```\n */\nexport function createServiceWorkerUpdates(register: RegisterServiceWorker): ServiceWorkerUpdates {\n let waiting = false;\n let update: ((reloadPage?: boolean) => Promise<void>) | null = null;\n const listeners = new Set<() => void>();\n const emit = () => listeners.forEach((listener) => listener());\n const set = (value: boolean) => {\n if (waiting === value) return;\n waiting = value;\n emit();\n };\n return {\n start: () => {\n if (update) return;\n update = register({ onNeedRefresh: () => set(true) });\n },\n needRefresh: () => waiting,\n subscribe: (listener) => {\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n };\n },\n reload: () => {\n void update?.(true);\n },\n dismiss: () => set(false),\n };\n}\n\n/** {@link PwaUpdatePrompt}'s props from the store: `needRefresh`, `onReload`, `onDismiss`. */\nexport function useServiceWorkerUpdate(updates: ServiceWorkerUpdates): {\n needRefresh: boolean;\n onReload: () => void;\n onDismiss: () => void;\n} {\n const needRefresh = useSyncExternalStore(updates.subscribe, updates.needRefresh, () => false);\n return { needRefresh, onReload: updates.reload, onDismiss: updates.dismiss };\n}\n"],"mappings":";AAAA,SAAS,4BAA4B;AA2C9B,SAAS,2BAA2B,UAAuD;AAChG,MAAI,UAAU;AACd,MAAI,SAA2D;AAC/D,QAAM,YAAY,oBAAI,IAAgB;AACtC,QAAM,OAAO,MAAM,UAAU,QAAQ,CAAC,aAAa,SAAS,CAAC;AAC7D,QAAM,MAAM,CAAC,UAAmB;AAC9B,QAAI,YAAY,MAAO;AACvB,cAAU;AACV,SAAK;AAAA,EACP;AACA,SAAO;AAAA,IACL,OAAO,MAAM;AACX,UAAI,OAAQ;AACZ,eAAS,SAAS,EAAE,eAAe,MAAM,IAAI,IAAI,EAAE,CAAC;AAAA,IACtD;AAAA,IACA,aAAa,MAAM;AAAA,IACnB,WAAW,CAAC,aAAa;AACvB,gBAAU,IAAI,QAAQ;AACtB,aAAO,MAAM;AACX,kBAAU,OAAO,QAAQ;AAAA,MAC3B;AAAA,IACF;AAAA,IACA,QAAQ,MAAM;AACZ,WAAK,SAAS,IAAI;AAAA,IACpB;AAAA,IACA,SAAS,MAAM,IAAI,KAAK;AAAA,EAC1B;AACF;AAGO,SAAS,uBAAuB,SAIrC;AACA,QAAM,cAAc,qBAAqB,QAAQ,WAAW,QAAQ,aAAa,MAAM,KAAK;AAC5F,SAAO,EAAE,aAAa,UAAU,QAAQ,QAAQ,WAAW,QAAQ,QAAQ;AAC7E;","names":[]}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
"use client";
|
|
2
|
+
const DEFAULT_SHARED_COMPUTER_LABELS = {
|
|
3
|
+
label: "This is a shared computer",
|
|
4
|
+
hint: "No copy of your data stays on this device. Pages then open only with a connection."
|
|
5
|
+
};
|
|
6
|
+
export {
|
|
7
|
+
DEFAULT_SHARED_COMPUTER_LABELS
|
|
8
|
+
};
|
|
9
|
+
//# sourceMappingURL=shared-computer-labels.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/offline/shared-computer-labels.ts"],"sourcesContent":["// The English words of ./shared-computer, in a module with no component code (0.34, KS U8).\n\nimport type { SharedComputerLabels } from \"./shared-computer\";\n\nexport const DEFAULT_SHARED_COMPUTER_LABELS: SharedComputerLabels = {\n label: \"This is a shared computer\",\n hint: \"No copy of your data stays on this device. Pages then open only with a connection.\",\n};\n"],"mappings":";AAIO,MAAM,iCAAuD;AAAA,EAClE,OAAO;AAAA,EACP,MAAM;AACR;","names":[]}
|