@softr/sdk 1.17.0-alpha.0 → 1.17.0-alpha.2
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 +1 -1
- package/dist/auth/isomorphic.d.ts +6 -6
- package/dist/index.d.ts +2 -2
- package/dist/index.js +1 -1
- package/dist/mcp.d.ts +2 -2
- package/dist/offline.d.ts +11 -4
- package/dist/offline.js +54 -55
- package/dist/package.js +1 -1
- package/dist/push.js +4 -4
- package/dist/pwa.d.ts +2 -2
- package/dist/service-worker.js +61 -0
- package/package.json +11 -38
- package/skills/softr-sdk/offline/SKILL.md +10 -3
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,9 +1,9 @@
|
|
|
1
1
|
import { User } from "./user.js";
|
|
2
2
|
import { Formatting } from "../formatting.js";
|
|
3
3
|
import { SoftrContext } from "./context.js";
|
|
4
|
-
import * as
|
|
4
|
+
import * as react6 from "react";
|
|
5
5
|
import { ReactNode } from "react";
|
|
6
|
-
import * as
|
|
6
|
+
import * as _tanstack_react_start2 from "@tanstack/react-start";
|
|
7
7
|
|
|
8
8
|
//#region src/auth/isomorphic.d.ts
|
|
9
9
|
|
|
@@ -21,7 +21,7 @@ import * as _tanstack_react_start0 from "@tanstack/react-start";
|
|
|
21
21
|
* requestMiddleware: [softrAuthMiddleware()],
|
|
22
22
|
* }))
|
|
23
23
|
*/
|
|
24
|
-
declare function softrAuthMiddleware():
|
|
24
|
+
declare function softrAuthMiddleware(): _tanstack_react_start2.RequestMiddlewareAfterServer<{}, readonly [_tanstack_react_start2.RequestMiddlewareAfterServer<{}, undefined, undefined>, _tanstack_react_start2.RequestMiddlewareAfterServer<{}, undefined, undefined>, _tanstack_react_start2.RequestMiddlewareAfterServer<{}, undefined, undefined>, _tanstack_react_start2.RequestMiddlewareAfterServer<{}, undefined, undefined>, _tanstack_react_start2.RequestMiddlewareAfterServer<{}, undefined, undefined>, _tanstack_react_start2.RequestMiddlewareAfterServer<{}, undefined, undefined>, _tanstack_react_start2.RequestMiddlewareAfterServer<{}, undefined, undefined>, _tanstack_react_start2.RequestMiddlewareAfterServer<{}, undefined, undefined>], {
|
|
25
25
|
user: User | null;
|
|
26
26
|
permissions: {
|
|
27
27
|
datasources: {};
|
|
@@ -37,7 +37,7 @@ declare function softrAuthMiddleware(): _tanstack_react_start0.RequestMiddleware
|
|
|
37
37
|
* beforeLoad: async () => await getSoftrContext(),
|
|
38
38
|
* })
|
|
39
39
|
*/
|
|
40
|
-
declare const getSoftrContext:
|
|
40
|
+
declare const getSoftrContext: _tanstack_react_start2.OptionalFetcher<undefined, undefined, Promise<SoftrContext>>;
|
|
41
41
|
/**
|
|
42
42
|
* The context to hand `createRouter`, before any request has resolved one.
|
|
43
43
|
*
|
|
@@ -92,7 +92,7 @@ type AuthOptions = {
|
|
|
92
92
|
* staleTime: 60_000,
|
|
93
93
|
* })
|
|
94
94
|
*/
|
|
95
|
-
declare const getAuthSettings:
|
|
95
|
+
declare const getAuthSettings: _tanstack_react_start2.OptionalFetcher<undefined, undefined, Promise<AuthOptions>>;
|
|
96
96
|
/**
|
|
97
97
|
* Makes the auth options readable with {@link useAuthSettings} anywhere below.
|
|
98
98
|
*
|
|
@@ -112,7 +112,7 @@ declare function AuthSettingsProvider({
|
|
|
112
112
|
}: {
|
|
113
113
|
value: AuthOptions;
|
|
114
114
|
children?: ReactNode;
|
|
115
|
-
}):
|
|
115
|
+
}): react6.JSX.Element;
|
|
116
116
|
/**
|
|
117
117
|
* Which ways in this app offers. Requires an {@link AuthSettingsProvider}
|
|
118
118
|
* above it.
|
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/index.js
CHANGED
|
@@ -8,7 +8,6 @@ import { toReturnPath } from "./auth/returnPath.js";
|
|
|
8
8
|
import { ssoSignInHref } from "./auth/sso.js";
|
|
9
9
|
import { FormattedDate, FormattingScope, formatDate, formatDateTime, formatNumber, useFormatting } from "./formatting.js";
|
|
10
10
|
import { SoftrPwaHead, usePwaInstall } from "./pwa.js";
|
|
11
|
-
import { useOfflineMode } from "./offline.js";
|
|
12
11
|
import { usePushNotifications } from "./push.js";
|
|
13
12
|
import { AuthSettingsProvider, getAuthSettings, getSoftrContext, initialSoftrContext, softrAuthMiddleware, useAuthSettings, useCurrentUser } from "./auth/isomorphic.js";
|
|
14
13
|
import { useIdleTimeout } from "./auth/idle-timeout.js";
|
|
@@ -17,6 +16,7 @@ import { softrMcpMiddleware } from "./mcp.js";
|
|
|
17
16
|
import { fieldShape, formatDuration, formatField, formatValue, registerSoftrFields } from "./fields/format.js";
|
|
18
17
|
import { useOverrides } from "./core/use-overrides.js";
|
|
19
18
|
import { useUserTimezone } from "./timezone.js";
|
|
19
|
+
import { useOfflineMode } from "./offline.js";
|
|
20
20
|
import { DefaultErrorOverlay } from "./default-error-overlay.js";
|
|
21
21
|
import { Audience } from "./route/audience.js";
|
|
22
22
|
|
package/dist/mcp.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { DatasourceAction } from "./action.js";
|
|
2
2
|
import { Tool } from "./tool.js";
|
|
3
|
-
import * as
|
|
3
|
+
import * as _tanstack_react_start0 from "@tanstack/react-start";
|
|
4
4
|
|
|
5
5
|
//#region src/mcp.d.ts
|
|
6
6
|
|
|
@@ -38,6 +38,6 @@ type SoftrMcpOptions = {
|
|
|
38
38
|
* ],
|
|
39
39
|
* }))
|
|
40
40
|
*/
|
|
41
|
-
declare function softrMcpMiddleware(options?: SoftrMcpOptions):
|
|
41
|
+
declare function softrMcpMiddleware(options?: SoftrMcpOptions): _tanstack_react_start0.RequestMiddlewareAfterServer<{}, undefined, undefined>;
|
|
42
42
|
//#endregion
|
|
43
43
|
export { softrMcpMiddleware };
|
package/dist/offline.d.ts
CHANGED
|
@@ -1,12 +1,19 @@
|
|
|
1
1
|
//#region src/offline.d.ts
|
|
2
|
-
|
|
3
2
|
type OfflineMode = {
|
|
4
3
|
/** `false` while the browser has no connection. Always `true` during server rendering. */
|
|
5
4
|
online: boolean;
|
|
6
5
|
};
|
|
6
|
+
type OfflineModeOptions = {
|
|
7
|
+
/**
|
|
8
|
+
* `false` turns offline mode off and deletes what this browser kept. Keep the
|
|
9
|
+
* call with `false` rather than removing it: browsers that ran offline mode
|
|
10
|
+
* before keep their copies until this runs. Defaults to `true`.
|
|
11
|
+
*/
|
|
12
|
+
enabled?: boolean;
|
|
13
|
+
};
|
|
7
14
|
/**
|
|
8
15
|
* Lets the published app open without internet and show the pages and data
|
|
9
|
-
* the visitor
|
|
16
|
+
* the visitor loaded, read only. Saves made offline fail as usual.
|
|
10
17
|
*
|
|
11
18
|
* Call it once, in the root route's `RootDocument`. The saved copies are
|
|
12
19
|
* deleted when another visitor signs in on this browser, or when the visitor
|
|
@@ -19,6 +26,6 @@ type OfflineMode = {
|
|
|
19
26
|
* return <div role="status">You're offline. Showing the last saved data.</div>
|
|
20
27
|
* }
|
|
21
28
|
*/
|
|
22
|
-
declare function useOfflineMode(): OfflineMode;
|
|
29
|
+
declare function useOfflineMode(options?: OfflineModeOptions): OfflineMode;
|
|
23
30
|
//#endregion
|
|
24
|
-
export { OfflineMode, useOfflineMode };
|
|
31
|
+
export { OfflineMode, OfflineModeOptions, useOfflineMode };
|
package/dist/offline.js
CHANGED
|
@@ -1,46 +1,13 @@
|
|
|
1
|
+
import { OFFLINE_CACHE, OFFLINE_DATA_CACHE, OFFLINE_OWNER_KEY, OFFLINE_SKIPPED_PREFIXES, WORKER_PATH } from "./service-worker.js";
|
|
2
|
+
import { useCurrentUser } from "./auth/isomorphic.js";
|
|
1
3
|
import { useEffect, useSyncExternalStore } from "react";
|
|
2
|
-
import {
|
|
4
|
+
import { useLocation } from "@tanstack/react-router";
|
|
3
5
|
|
|
4
6
|
//#region src/offline.ts
|
|
5
|
-
const
|
|
6
|
-
const CACHE = "softr-offline-v1";
|
|
7
|
-
const OWNER_KEY = "/_softr/offline-owner";
|
|
8
|
-
/**
|
|
9
|
-
* Added to the service worker the app serves. Same-origin GET requests go to
|
|
10
|
-
* the network first, and the last good answer is kept on the device for when
|
|
11
|
-
* the network fails. Writes are never kept.
|
|
12
|
-
*
|
|
13
|
-
* It does nothing until `useOfflineMode()` creates the cache, so an app that
|
|
14
|
-
* registers the worker only for push keeps working as before.
|
|
15
|
-
*/
|
|
16
|
-
const OFFLINE_WORKER = `
|
|
17
|
-
// Offline mode, added by @softr/sdk.
|
|
18
|
-
self.addEventListener('fetch', (event) => {
|
|
19
|
-
const request = event.request;
|
|
20
|
-
if (request.method !== 'GET') return;
|
|
21
|
-
const url = new URL(request.url);
|
|
22
|
-
if (url.origin !== self.location.origin) return;
|
|
23
|
-
if (url.pathname.startsWith('/_softr/') || url.pathname.startsWith('/.softr/')) return;
|
|
24
|
-
event.respondWith((async () => {
|
|
25
|
-
if (!(await caches.has(${JSON.stringify(CACHE)}))) return fetch(request);
|
|
26
|
-
const cache = await caches.open(${JSON.stringify(CACHE)});
|
|
27
|
-
try {
|
|
28
|
-
const response = await fetch(request);
|
|
29
|
-
if (response.status === 200 && response.type === 'basic') {
|
|
30
|
-
event.waitUntil(cache.put(request, response.clone()).catch(() => {}));
|
|
31
|
-
}
|
|
32
|
-
return response;
|
|
33
|
-
} catch (error) {
|
|
34
|
-
const copy = await cache.match(request);
|
|
35
|
-
if (copy) return copy;
|
|
36
|
-
throw error;
|
|
37
|
-
}
|
|
38
|
-
})());
|
|
39
|
-
});
|
|
40
|
-
`;
|
|
7
|
+
const PAGE_MAX_AGE_MS = 5 * 6e4;
|
|
41
8
|
/**
|
|
42
9
|
* Lets the published app open without internet and show the pages and data
|
|
43
|
-
* the visitor
|
|
10
|
+
* the visitor loaded, read only. Saves made offline fail as usual.
|
|
44
11
|
*
|
|
45
12
|
* Call it once, in the root route's `RootDocument`. The saved copies are
|
|
46
13
|
* deleted when another visitor signs in on this browser, or when the visitor
|
|
@@ -53,34 +20,66 @@ self.addEventListener('fetch', (event) => {
|
|
|
53
20
|
* return <div role="status">You're offline. Showing the last saved data.</div>
|
|
54
21
|
* }
|
|
55
22
|
*/
|
|
56
|
-
function useOfflineMode() {
|
|
57
|
-
const
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
});
|
|
61
|
-
const href = useLocation({ select: (location) => location.href });
|
|
23
|
+
function useOfflineMode(options = {}) {
|
|
24
|
+
const enabled = options.enabled ?? true;
|
|
25
|
+
const userId = useCurrentUser()?.id ?? null;
|
|
26
|
+
const href = useLocation({ select: (location$1) => location$1.href });
|
|
62
27
|
const online = useSyncExternalStore(subscribeToConnection, () => navigator.onLine, () => true);
|
|
63
28
|
useEffect(() => {
|
|
64
|
-
if (!
|
|
29
|
+
if (process.env.NODE_ENV !== "production" || !("serviceWorker" in navigator) || !("caches" in window)) return;
|
|
30
|
+
if (!enabled) {
|
|
31
|
+
Promise.all([caches.delete(OFFLINE_CACHE), caches.delete(OFFLINE_DATA_CACHE)]).catch(() => {});
|
|
32
|
+
return;
|
|
33
|
+
}
|
|
65
34
|
(async () => {
|
|
66
35
|
await keepCopiesOnlyFor(userId ?? "");
|
|
67
36
|
await navigator.serviceWorker.register(WORKER_PATH, { scope: "/" });
|
|
68
37
|
if (!navigator.onLine) return;
|
|
69
|
-
const cache = await caches.open(
|
|
70
|
-
|
|
38
|
+
const cache = await caches.open(OFFLINE_CACHE);
|
|
39
|
+
await savePage(cache, href);
|
|
40
|
+
await saveLoadedFiles(cache);
|
|
71
41
|
})().catch((error) => console.warn("[@softr/sdk] Offline mode could not save this page:", error));
|
|
72
|
-
}, [
|
|
42
|
+
}, [
|
|
43
|
+
enabled,
|
|
44
|
+
userId,
|
|
45
|
+
href
|
|
46
|
+
]);
|
|
73
47
|
return { online };
|
|
74
48
|
}
|
|
75
|
-
function isOn() {
|
|
76
|
-
return process.env.NODE_ENV === "production" && "serviceWorker" in navigator && "caches" in window;
|
|
77
|
-
}
|
|
78
49
|
/** Deletes the copies when they belong to someone else, then marks them as this visitor's. */
|
|
79
50
|
async function keepCopiesOnlyFor(owner) {
|
|
80
|
-
const stored = await (await caches.open(
|
|
51
|
+
const stored = await (await caches.open(OFFLINE_CACHE)).match(OFFLINE_OWNER_KEY);
|
|
81
52
|
if (stored !== void 0 && await stored.text() === owner) return;
|
|
82
|
-
await caches.delete(
|
|
83
|
-
await (await caches.open(
|
|
53
|
+
await Promise.all([caches.delete(OFFLINE_CACHE), caches.delete(OFFLINE_DATA_CACHE)]);
|
|
54
|
+
await (await caches.open(OFFLINE_CACHE)).put(OFFLINE_OWNER_KEY, new Response(owner));
|
|
55
|
+
}
|
|
56
|
+
/**
|
|
57
|
+
* A page reached by a link was never loaded as a whole page, so the worker has
|
|
58
|
+
* no copy of it. Save it, and save it again once the copy is a few minutes
|
|
59
|
+
* old, so a reload offline shows recent data.
|
|
60
|
+
*/
|
|
61
|
+
async function savePage(cache, href) {
|
|
62
|
+
const copy = await cache.match(href);
|
|
63
|
+
const savedAt = Date.parse(copy?.headers.get("date") ?? "");
|
|
64
|
+
if (copy !== void 0 && Date.now() - savedAt < PAGE_MAX_AGE_MS) return;
|
|
65
|
+
await cache.add(href);
|
|
66
|
+
}
|
|
67
|
+
/**
|
|
68
|
+
* The page's scripts, styles and images, which loaded before the worker was in
|
|
69
|
+
* control, or went into copies that a sign-in deleted. Without them a reload
|
|
70
|
+
* offline shows a page that has no styles and does not respond.
|
|
71
|
+
*/
|
|
72
|
+
async function saveLoadedFiles(cache) {
|
|
73
|
+
const missing = [];
|
|
74
|
+
for (const entry of performance.getEntriesByType("resource")) {
|
|
75
|
+
if (!(entry instanceof PerformanceResourceTiming)) continue;
|
|
76
|
+
if (entry.initiatorType === "fetch" || entry.initiatorType === "xmlhttprequest") continue;
|
|
77
|
+
const url = new URL(entry.name);
|
|
78
|
+
if (url.origin !== location.origin) continue;
|
|
79
|
+
if (OFFLINE_SKIPPED_PREFIXES.some((prefix) => url.pathname.startsWith(prefix))) continue;
|
|
80
|
+
if (await cache.match(url.href) === void 0) missing.push(url.href);
|
|
81
|
+
}
|
|
82
|
+
await Promise.all(missing.map((url) => cache.add(url).catch(() => {})));
|
|
84
83
|
}
|
|
85
84
|
function subscribeToConnection(onChange) {
|
|
86
85
|
window.addEventListener("online", onChange);
|
|
@@ -92,4 +91,4 @@ function subscribeToConnection(onChange) {
|
|
|
92
91
|
}
|
|
93
92
|
|
|
94
93
|
//#endregion
|
|
95
|
-
export {
|
|
94
|
+
export { useOfflineMode };
|
package/dist/package.js
CHANGED
package/dist/push.js
CHANGED
|
@@ -4,14 +4,13 @@ import { sessionConfig } from "./auth/config.js";
|
|
|
4
4
|
import { readSessionToken } from "./auth/session.js";
|
|
5
5
|
import { readCached } from "./cache.js";
|
|
6
6
|
import { detectPlatform, isStandalone } from "./pwa.js";
|
|
7
|
-
import { OFFLINE_WORKER } from "./
|
|
7
|
+
import { OFFLINE_WORKER, WORKER_PATH } from "./service-worker.js";
|
|
8
8
|
import { z } from "zod";
|
|
9
9
|
import { useCallback, useEffect, useState } from "react";
|
|
10
10
|
import { createMiddleware } from "@tanstack/react-start";
|
|
11
11
|
import { rootRouteId, useRouteContext } from "@tanstack/react-router";
|
|
12
12
|
|
|
13
13
|
//#region src/push.ts
|
|
14
|
-
const WORKER_PATH = "/_softr/sw.js";
|
|
15
14
|
const SETTINGS_PATH = "/_softr/push.json";
|
|
16
15
|
const SUBSCRIPTION_PATH = "/_softr/push";
|
|
17
16
|
const TTL_MS = 6e4;
|
|
@@ -57,8 +56,9 @@ function readWorker() {
|
|
|
57
56
|
}
|
|
58
57
|
/**
|
|
59
58
|
* 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
|
|
61
|
-
* this browser's subscription for the signed-in visitor. Every other
|
|
59
|
+
* which also runs offline mode, the app's push settings, and saving or
|
|
60
|
+
* removing this browser's subscription for the signed-in visitor. Every other
|
|
61
|
+
* request passes through untouched.
|
|
62
62
|
*/
|
|
63
63
|
function pushMiddleware() {
|
|
64
64
|
return createMiddleware({ type: "request" }).server(async ({ next, pathname, request }) => {
|
package/dist/pwa.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import * as
|
|
1
|
+
import * as react4 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():
|
|
27
|
+
declare function SoftrPwaHead(): react4.FunctionComponentElement<react4.FragmentProps>;
|
|
28
28
|
type PwaPlatform = "ios" | "android" | "desktop";
|
|
29
29
|
type InstallChoice = "accepted" | "dismissed";
|
|
30
30
|
type PwaInstall = {
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
//#region src/service-worker.ts
|
|
2
|
+
const WORKER_PATH = "/_softr/sw.js";
|
|
3
|
+
/** Pages, scripts, styles and images. Its presence is what turns offline mode on. */
|
|
4
|
+
const OFFLINE_CACHE = "softr-offline-v1";
|
|
5
|
+
/** Answers to the app's data calls, kept apart so a long session of them never pushes out the pages. */
|
|
6
|
+
const OFFLINE_DATA_CACHE = "softr-offline-data-v1";
|
|
7
|
+
/** Whose copies the offline cache holds: the user id, or empty for a signed-out visitor. */
|
|
8
|
+
const OFFLINE_OWNER_KEY = "/_softr/offline-owner";
|
|
9
|
+
/** Paths offline mode never keeps: the SDK's own routes and the canvas engine's. */
|
|
10
|
+
const OFFLINE_SKIPPED_PREFIXES = ["/_softr/", "/.softr/"];
|
|
11
|
+
const MAX_COPIES = 300;
|
|
12
|
+
/**
|
|
13
|
+
* Added after the platform's worker. Same-origin GET requests go to the
|
|
14
|
+
* network first, and the last good answer is kept on the device for when the
|
|
15
|
+
* network fails. Writes and live streams are never kept.
|
|
16
|
+
*
|
|
17
|
+
* It does nothing until `useOfflineMode()` creates the cache, so an app that
|
|
18
|
+
* registers the worker only for push keeps working as before.
|
|
19
|
+
*/
|
|
20
|
+
const OFFLINE_WORKER = `
|
|
21
|
+
// Offline mode, added by @softr/sdk.
|
|
22
|
+
const SOFTR_OFFLINE_CACHE = ${JSON.stringify(OFFLINE_CACHE)};
|
|
23
|
+
const SOFTR_OFFLINE_DATA_CACHE = ${JSON.stringify(OFFLINE_DATA_CACHE)};
|
|
24
|
+
const SOFTR_OFFLINE_OWNER_KEY = ${JSON.stringify(OFFLINE_OWNER_KEY)};
|
|
25
|
+
const SOFTR_OFFLINE_SKIPPED = ${JSON.stringify(OFFLINE_SKIPPED_PREFIXES)};
|
|
26
|
+
|
|
27
|
+
async function softrKeepCopy(cacheName, request, response) {
|
|
28
|
+
const cache = await caches.open(cacheName);
|
|
29
|
+
await cache.put(request, response);
|
|
30
|
+
const keys = (await cache.keys()).filter((key) => new URL(key.url).pathname !== SOFTR_OFFLINE_OWNER_KEY);
|
|
31
|
+
await Promise.all(keys.slice(0, Math.max(0, keys.length - ${MAX_COPIES})).map((key) => cache.delete(key)));
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
self.addEventListener('fetch', (event) => {
|
|
35
|
+
const request = event.request;
|
|
36
|
+
if (request.method !== 'GET') return;
|
|
37
|
+
const url = new URL(request.url);
|
|
38
|
+
if (url.origin !== self.location.origin) return;
|
|
39
|
+
if (SOFTR_OFFLINE_SKIPPED.some((prefix) => url.pathname.startsWith(prefix))) return;
|
|
40
|
+
event.respondWith((async () => {
|
|
41
|
+
if (!(await caches.has(SOFTR_OFFLINE_CACHE))) return fetch(request);
|
|
42
|
+
// A data call from the app's code has no destination; a page or a file has one.
|
|
43
|
+
const cacheName = request.destination === '' ? SOFTR_OFFLINE_DATA_CACHE : SOFTR_OFFLINE_CACHE;
|
|
44
|
+
try {
|
|
45
|
+
const response = await fetch(request);
|
|
46
|
+
const streamed = (response.headers.get('content-type') || '').startsWith('text/event-stream');
|
|
47
|
+
if (response.status === 200 && response.type === 'basic' && !streamed) {
|
|
48
|
+
event.waitUntil(softrKeepCopy(cacheName, request, response.clone()).catch(() => {}));
|
|
49
|
+
}
|
|
50
|
+
return response;
|
|
51
|
+
} catch (error) {
|
|
52
|
+
const copy = await caches.match(request, { cacheName });
|
|
53
|
+
if (copy) return copy;
|
|
54
|
+
throw error;
|
|
55
|
+
}
|
|
56
|
+
})());
|
|
57
|
+
});
|
|
58
|
+
`;
|
|
59
|
+
|
|
60
|
+
//#endregion
|
|
61
|
+
export { OFFLINE_CACHE, OFFLINE_DATA_CACHE, OFFLINE_OWNER_KEY, OFFLINE_SKIPPED_PREFIXES, OFFLINE_WORKER, WORKER_PATH };
|
package/package.json
CHANGED
|
@@ -1,42 +1,17 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@softr/sdk",
|
|
3
|
-
"version": "1.17.0-alpha.
|
|
3
|
+
"version": "1.17.0-alpha.2",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"exports": {
|
|
6
|
-
".": {
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
},
|
|
10
|
-
"./
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
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, sometimes a little 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()
|
|
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
|
|