@softr/sdk 1.17.0-alpha.0 → 1.17.0-alpha.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/CHANGELOG.md CHANGED
@@ -4,7 +4,7 @@
4
4
 
5
5
  ### Minor Changes
6
6
 
7
- - Add `useOfflineMode()`: the published app opens without internet and shows the pages and data the visitor last loaded, read only. Call it once in `RootDocument`.
7
+ - Add `useOfflineMode()`: the published app opens without internet and shows the pages and data the visitor last loaded, read only. Call it once in `RootDocument`; `useOfflineMode({ enabled: false })` turns it off and deletes what browsers kept.
8
8
 
9
9
  ## 1.15.2
10
10
 
@@ -1,4 +1,4 @@
1
- import * as react7 from "react";
1
+ import * as react5 from "react";
2
2
 
3
3
  //#region src/default-error-overlay.d.ts
4
4
  type Props = {
@@ -8,6 +8,6 @@ type Props = {
8
8
  declare function DefaultErrorOverlay({
9
9
  error,
10
10
  reset
11
- }: Props): react7.JSX.Element;
11
+ }: Props): react5.JSX.Element;
12
12
  //#endregion
13
13
  export { DefaultErrorOverlay };
package/dist/index.d.ts CHANGED
@@ -21,9 +21,9 @@ import { useOverrides } from "./core/use-overrides.js";
21
21
  import { useUserTimezone } from "./timezone.js";
22
22
  import { PwaInstall, PwaPlatform, SoftrPwaHead, usePwaInstall } from "./pwa.js";
23
23
  import { PushNotifications, PushPrompt, usePushNotifications } from "./push.js";
24
- import { OfflineMode, useOfflineMode } from "./offline.js";
24
+ import { OfflineMode, OfflineModeOptions, useOfflineMode } from "./offline.js";
25
25
  import { DefaultErrorOverlay } from "./default-error-overlay.js";
26
26
  import { Audience } from "./route/audience.js";
27
27
  import { Logo, LogoFile } from "./softr-config.schema.js";
28
28
  import { getLogo } from "./softr-config.js";
29
- export { type ActionPermissions, type AiAnswer, type AiFile, type AiGenerateInit, type AiMessage, type AiUsage, Audience, type AuthOptions, type AuthSettings, AuthSettingsProvider, type DateOptions, type DateParts, type DateSeparator, type DateValue, DefaultErrorOverlay, type EmailErrorCode, type EmailSendInit, type EmailSent, type FieldShape, type FileAttachment, type FileItem, type FixedDateFormat, FormattedDate, type Formatting, FormattingScope, type Logo, type LogoFile, type OfflineMode, type Page, type PageSettings, type PushNotifications, type PushPrompt, type PwaInstall, type PwaPlatform, type SoftrContext, type SoftrDatasources, type SoftrFieldRegistry, SoftrPwaHead, type SoftrUserGroupId, type SoftrUserGroups, type SoftrUserProperties, type SsoError, type Tool, type ToolDefinition, type User, type WeekDay, assertRouteAccess, checkAccess, defineAiAction, defineEmailAction, defineIntegration, defineMutation, definePage, defineQuery, defineTool, defineVisibility, defineWorkflow, fieldShape, formatDate, formatDateTime, formatDuration, formatField, formatNumber, formatValue, getAuthSettings, getLogo, getSoftrContext, guardRoute, initialSoftrContext, isAccessError, isAlreadyAuthenticatedError, isAuthorized, isForbiddenError, isUnauthenticatedError, pageHead, registerSoftrFields, softrAuthMiddleware, softrMcpMiddleware, ssoSignInHref, toReturnPath, useAuthSettings, useCurrentUser, useFileUpload, useFormatting, useIdleTimeout, useOfflineMode, useOverrides, usePushNotifications, usePwaInstall, useUserTimezone };
29
+ export { type ActionPermissions, type AiAnswer, type AiFile, type AiGenerateInit, type AiMessage, type AiUsage, Audience, type AuthOptions, type AuthSettings, AuthSettingsProvider, type DateOptions, type DateParts, type DateSeparator, type DateValue, DefaultErrorOverlay, type EmailErrorCode, type EmailSendInit, type EmailSent, type FieldShape, type FileAttachment, type FileItem, type FixedDateFormat, FormattedDate, type Formatting, FormattingScope, type Logo, type LogoFile, type OfflineMode, type OfflineModeOptions, type Page, type PageSettings, type PushNotifications, type PushPrompt, type PwaInstall, type PwaPlatform, type SoftrContext, type SoftrDatasources, type SoftrFieldRegistry, SoftrPwaHead, type SoftrUserGroupId, type SoftrUserGroups, type SoftrUserProperties, type SsoError, type Tool, type ToolDefinition, type User, type WeekDay, assertRouteAccess, checkAccess, defineAiAction, defineEmailAction, defineIntegration, defineMutation, definePage, defineQuery, defineTool, defineVisibility, defineWorkflow, fieldShape, formatDate, formatDateTime, formatDuration, formatField, formatNumber, formatValue, getAuthSettings, getLogo, getSoftrContext, guardRoute, initialSoftrContext, isAccessError, isAlreadyAuthenticatedError, isAuthorized, isForbiddenError, isUnauthenticatedError, pageHead, registerSoftrFields, softrAuthMiddleware, softrMcpMiddleware, ssoSignInHref, toReturnPath, useAuthSettings, useCurrentUser, useFileUpload, useFormatting, useIdleTimeout, useOfflineMode, useOverrides, usePushNotifications, usePwaInstall, useUserTimezone };
package/dist/offline.d.ts CHANGED
@@ -4,9 +4,17 @@ type OfflineMode = {
4
4
  /** `false` while the browser has no connection. Always `true` during server rendering. */
5
5
  online: boolean;
6
6
  };
7
+ type OfflineModeOptions = {
8
+ /**
9
+ * `false` turns offline mode off and deletes what this browser kept. Keep the
10
+ * call with `false` rather than removing it: browsers that ran offline mode
11
+ * before keep their copies until this runs. Defaults to `true`.
12
+ */
13
+ enabled?: boolean;
14
+ };
7
15
  /**
8
16
  * Lets the published app open without internet and show the pages and data
9
- * the visitor last loaded, read only. Saves made offline fail as usual.
17
+ * the visitor loaded, read only. Saves made offline fail as usual.
10
18
  *
11
19
  * Call it once, in the root route's `RootDocument`. The saved copies are
12
20
  * deleted when another visitor signs in on this browser, or when the visitor
@@ -19,6 +27,6 @@ type OfflineMode = {
19
27
  * return <div role="status">You're offline. Showing the last saved data.</div>
20
28
  * }
21
29
  */
22
- declare function useOfflineMode(): OfflineMode;
30
+ declare function useOfflineMode(options?: OfflineModeOptions): OfflineMode;
23
31
  //#endregion
24
- export { OfflineMode, useOfflineMode };
32
+ export { OfflineMode, OfflineModeOptions, useOfflineMode };
package/dist/offline.js CHANGED
@@ -38,9 +38,10 @@ self.addEventListener('fetch', (event) => {
38
38
  })());
39
39
  });
40
40
  `;
41
+ const PAGE_MAX_AGE_MS = 5 * 6e4;
41
42
  /**
42
43
  * Lets the published app open without internet and show the pages and data
43
- * the visitor last loaded, read only. Saves made offline fail as usual.
44
+ * the visitor loaded, read only. Saves made offline fail as usual.
44
45
  *
45
46
  * Call it once, in the root route's `RootDocument`. The saved copies are
46
47
  * deleted when another visitor signs in on this browser, or when the visitor
@@ -53,26 +54,36 @@ self.addEventListener('fetch', (event) => {
53
54
  * return <div role="status">You're offline. Showing the last saved data.</div>
54
55
  * }
55
56
  */
56
- function useOfflineMode() {
57
+ function useOfflineMode(options = {}) {
58
+ const enabled = options.enabled ?? true;
57
59
  const userId = useRouteContext({
58
60
  from: rootRouteId,
59
61
  select: (context) => context.user?.id ?? null
60
62
  });
61
- const href = useLocation({ select: (location) => location.href });
63
+ const href = useLocation({ select: (location$1) => location$1.href });
62
64
  const online = useSyncExternalStore(subscribeToConnection, () => navigator.onLine, () => true);
63
65
  useEffect(() => {
64
- if (!isOn()) return;
66
+ if (!isSupported()) return;
67
+ if (!enabled) {
68
+ caches.delete(CACHE).catch(() => {});
69
+ return;
70
+ }
65
71
  (async () => {
66
72
  await keepCopiesOnlyFor(userId ?? "");
67
73
  await navigator.serviceWorker.register(WORKER_PATH, { scope: "/" });
68
74
  if (!navigator.onLine) return;
69
75
  const cache = await caches.open(CACHE);
70
- if (await cache.match(href) === void 0) await cache.add(href);
76
+ await savePage(cache, href);
77
+ await saveLoadedFiles(cache);
71
78
  })().catch((error) => console.warn("[@softr/sdk] Offline mode could not save this page:", error));
72
- }, [userId, href]);
79
+ }, [
80
+ enabled,
81
+ userId,
82
+ href
83
+ ]);
73
84
  return { online };
74
85
  }
75
- function isOn() {
86
+ function isSupported() {
76
87
  return process.env.NODE_ENV === "production" && "serviceWorker" in navigator && "caches" in window;
77
88
  }
78
89
  /** Deletes the copies when they belong to someone else, then marks them as this visitor's. */
@@ -82,6 +93,33 @@ async function keepCopiesOnlyFor(owner) {
82
93
  await caches.delete(CACHE);
83
94
  await (await caches.open(CACHE)).put(OWNER_KEY, new Response(owner));
84
95
  }
96
+ /**
97
+ * A page reached by a link was never loaded as a whole page, so the worker has
98
+ * no copy of it. Save it, and save it again once the copy is a few minutes
99
+ * old, so a reload offline shows recent data.
100
+ */
101
+ async function savePage(cache, href) {
102
+ const copy = await cache.match(href);
103
+ const savedAt = Date.parse(copy?.headers.get("date") ?? "");
104
+ if (copy !== void 0 && Date.now() - savedAt < PAGE_MAX_AGE_MS) return;
105
+ await cache.add(href);
106
+ }
107
+ /**
108
+ * The page's scripts, styles and images, which loaded before the worker was in
109
+ * control, or went into copies that a sign-in deleted. Without them a reload
110
+ * offline shows a page that has no styles and does not respond.
111
+ */
112
+ async function saveLoadedFiles(cache) {
113
+ const missing = [];
114
+ for (const entry of performance.getEntriesByType("resource")) {
115
+ if (!(entry instanceof PerformanceResourceTiming)) continue;
116
+ if (entry.initiatorType === "fetch" || entry.initiatorType === "xmlhttprequest") continue;
117
+ const url = new URL(entry.name);
118
+ if (url.origin !== location.origin || url.pathname.startsWith("/_softr/") || url.pathname.startsWith("/.softr/")) continue;
119
+ if (await cache.match(url.href) === void 0) missing.push(url.href);
120
+ }
121
+ await Promise.all(missing.map((url) => cache.add(url).catch(() => {})));
122
+ }
85
123
  function subscribeToConnection(onChange) {
86
124
  window.addEventListener("online", onChange);
87
125
  window.addEventListener("offline", onChange);
package/dist/package.js CHANGED
@@ -1,5 +1,5 @@
1
1
  //#region package.json
2
- var version = "1.17.0-alpha.0";
2
+ var version = "1.17.0-alpha.1";
3
3
 
4
4
  //#endregion
5
5
  export { version };
package/dist/push.js CHANGED
@@ -57,8 +57,9 @@ function readWorker() {
57
57
  }
58
58
  /**
59
59
  * Serves push notifications from the app's own origin: the service worker,
60
- * which also runs offline mode, the app's push settings, and saving or removing
61
- * this browser's subscription for the signed-in visitor. Every other request passes through untouched.
60
+ * which also runs offline mode, the app's push settings, and saving or
61
+ * removing this browser's subscription for the signed-in visitor. Every other
62
+ * request passes through untouched.
62
63
  */
63
64
  function pushMiddleware() {
64
65
  return createMiddleware({ type: "request" }).server(async ({ next, pathname, request }) => {
package/dist/pwa.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import * as react5 from "react";
1
+ import * as react6 from "react";
2
2
  import "@tanstack/react-start";
3
3
 
4
4
  //#region src/pwa.d.ts
@@ -24,7 +24,7 @@ import "@tanstack/react-start";
24
24
  * )
25
25
  * }
26
26
  */
27
- declare function SoftrPwaHead(): react5.FunctionComponentElement<react5.FragmentProps>;
27
+ declare function SoftrPwaHead(): react6.FunctionComponentElement<react6.FragmentProps>;
28
28
  type PwaPlatform = "ios" | "android" | "desktop";
29
29
  type InstallChoice = "accepted" | "dismissed";
30
30
  type PwaInstall = {
package/package.json CHANGED
@@ -1,42 +1,17 @@
1
1
  {
2
2
  "name": "@softr/sdk",
3
- "version": "1.17.0-alpha.0",
3
+ "version": "1.17.0-alpha.1",
4
4
  "type": "module",
5
5
  "exports": {
6
- ".": {
7
- "types": "./dist/index.d.ts",
8
- "import": "./dist/index.js"
9
- },
10
- "./client": {
11
- "types": "./dist/client.d.ts",
12
- "import": "./dist/client.js"
13
- },
14
- "./server": {
15
- "types": "./dist/server.d.ts",
16
- "import": "./dist/server.js"
17
- },
18
- "./vite": {
19
- "types": "./dist/vite.d.ts",
20
- "import": "./dist/vite.js"
21
- },
22
- "./logo-icon": {
23
- "types": "./dist/logo-icon.d.ts",
24
- "import": "./dist/logo-icon.js"
25
- }
26
- },
27
- "bin": {
28
- "softr-sdk": "./dist/cli.js"
29
- },
30
- "files": [
31
- "dist",
32
- "schema",
33
- "skills",
34
- "!skills/_artifacts",
35
- "CHANGELOG.md"
36
- ],
37
- "publishConfig": {
38
- "access": "public"
39
- },
6
+ ".": { "types": "./dist/index.d.ts", "import": "./dist/index.js" },
7
+ "./client": { "types": "./dist/client.d.ts", "import": "./dist/client.js" },
8
+ "./server": { "types": "./dist/server.d.ts", "import": "./dist/server.js" },
9
+ "./vite": { "types": "./dist/vite.d.ts", "import": "./dist/vite.js" },
10
+ "./logo-icon": { "types": "./dist/logo-icon.d.ts", "import": "./dist/logo-icon.js" }
11
+ },
12
+ "bin": { "softr-sdk": "./dist/cli.js" },
13
+ "files": ["dist", "schema", "skills", "!skills/_artifacts", "CHANGELOG.md"],
14
+ "publishConfig": { "access": "public" },
40
15
  "scripts": {
41
16
  "build": "tsdown",
42
17
  "test": "node --import ./src/test-utils/setup.ts --test",
@@ -68,9 +43,7 @@
68
43
  "optional": true
69
44
  }
70
45
  },
71
- "keywords": [
72
- "tanstack-intent"
73
- ],
46
+ "keywords": ["tanstack-intent"],
74
47
  "intent": {
75
48
  "version": 1,
76
49
  "repo": "@softr/sdk",
@@ -13,7 +13,7 @@ metadata:
13
13
 
14
14
  # Offline mode
15
15
 
16
- With offline mode on, the published app opens without internet and shows the pages and data the visitor already loaded while online, as they were then. Pages the visitor never opened are not there. Nothing can be saved offline: a save fails as it would on any network error, and the app tells the visitor.
16
+ With offline mode on, the published app opens without internet and shows the pages and data the visitor already loaded while online, as they were then, up to a few minutes older. Pages the visitor never opened are not there: a link to one shows the app's error page. Nothing can be saved offline: a save fails as it would on any network error, and the app tells the visitor.
17
17
 
18
18
  > **CRITICAL**: Never write a service worker, a `public/sw.js`, or any `navigator.serviceWorker`, `caches` or IndexedDB code for offline. The app already serves its service worker, shared with push notifications, and `useOfflineMode()` turns offline mode on. A worker of the app's own replaces it, and push notifications stop arriving.
19
19
  >
@@ -23,10 +23,14 @@ With offline mode on, the published app opens without internet and shows the pag
23
23
 
24
24
  ```ts
25
25
  import { useOfflineMode } from '@softr/sdk'
26
- import type { OfflineMode } from '@softr/sdk'
26
+ import type { OfflineMode, OfflineModeOptions } from '@softr/sdk'
27
27
  ```
28
28
 
29
29
  ```ts
30
+ type OfflineModeOptions = {
31
+ enabled?: boolean // false turns offline mode off and deletes what browsers kept; defaults to true
32
+ }
33
+
30
34
  type OfflineMode = {
31
35
  online: boolean // false while the browser has no connection; always true during server rendering
32
36
  }
@@ -53,6 +57,9 @@ Offline mode works only on the published app. Inside the Studio preview `online`
53
57
  A save made offline rejects like any failed request. Catch it as usual, and when `online` is `false`, say that the visitor is offline rather than showing a generic error:
54
58
 
55
59
  ```tsx
60
+ import { toast } from 'sonner'
61
+
62
+ // `save` is the form's own server function.
56
63
  const { online } = useOfflineMode()
57
64
  save(values).catch(() =>
58
65
  toast.error(online ? 'Could not save your changes.' : "You're offline. Connect to save your changes."),
@@ -65,7 +72,7 @@ Nothing to add. The copies kept on the device are deleted when the visitor signs
65
72
 
66
73
  ### Turning it off
67
74
 
68
- Remove the `useOfflineMode()` call and the banner. Copies already kept on visitors' devices are no longer used.
75
+ Remove the banner, and keep one call in `RootDocument` as `useOfflineMode({ enabled: false })`. That deletes what visitors' browsers kept the next time they open the app. Removing the call instead leaves those copies working offline, and they are no longer deleted on sign-out.
69
76
 
70
77
  ## Common Mistakes
71
78