@softr/sdk 1.17.0-alpha.1 → 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.
@@ -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 react0 from "react";
4
+ import * as react6 from "react";
5
5
  import { ReactNode } from "react";
6
- import * as _tanstack_react_start0 from "@tanstack/react-start";
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(): _tanstack_react_start0.RequestMiddlewareAfterServer<{}, readonly [_tanstack_react_start0.RequestMiddlewareAfterServer<{}, undefined, undefined>, _tanstack_react_start0.RequestMiddlewareAfterServer<{}, undefined, undefined>, _tanstack_react_start0.RequestMiddlewareAfterServer<{}, undefined, undefined>, _tanstack_react_start0.RequestMiddlewareAfterServer<{}, undefined, undefined>, _tanstack_react_start0.RequestMiddlewareAfterServer<{}, undefined, undefined>, _tanstack_react_start0.RequestMiddlewareAfterServer<{}, undefined, undefined>, _tanstack_react_start0.RequestMiddlewareAfterServer<{}, undefined, undefined>, _tanstack_react_start0.RequestMiddlewareAfterServer<{}, undefined, undefined>], {
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: _tanstack_react_start0.OptionalFetcher<undefined, undefined, Promise<SoftrContext>>;
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: _tanstack_react_start0.OptionalFetcher<undefined, undefined, Promise<AuthOptions>>;
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
- }): react0.JSX.Element;
115
+ }): react6.JSX.Element;
116
116
  /**
117
117
  * Which ways in this app offers. Requires an {@link AuthSettingsProvider}
118
118
  * above it.
@@ -1,4 +1,4 @@
1
- import * as react5 from "react";
1
+ import * as react7 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): react5.JSX.Element;
11
+ }: Props): react7.JSX.Element;
12
12
  //#endregion
13
13
  export { DefaultErrorOverlay };
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 _tanstack_react_start11 from "@tanstack/react-start";
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): _tanstack_react_start11.RequestMiddlewareAfterServer<{}, undefined, undefined>;
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,5 +1,4 @@
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;
package/dist/offline.js CHANGED
@@ -1,43 +1,9 @@
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 { rootRouteId, useLocation, useRouteContext } from "@tanstack/react-router";
4
+ import { useLocation } from "@tanstack/react-router";
3
5
 
4
6
  //#region src/offline.ts
5
- const WORKER_PATH = "/_softr/sw.js";
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
- `;
41
7
  const PAGE_MAX_AGE_MS = 5 * 6e4;
42
8
  /**
43
9
  * Lets the published app open without internet and show the pages and data
@@ -56,23 +22,20 @@ const PAGE_MAX_AGE_MS = 5 * 6e4;
56
22
  */
57
23
  function useOfflineMode(options = {}) {
58
24
  const enabled = options.enabled ?? true;
59
- const userId = useRouteContext({
60
- from: rootRouteId,
61
- select: (context) => context.user?.id ?? null
62
- });
25
+ const userId = useCurrentUser()?.id ?? null;
63
26
  const href = useLocation({ select: (location$1) => location$1.href });
64
27
  const online = useSyncExternalStore(subscribeToConnection, () => navigator.onLine, () => true);
65
28
  useEffect(() => {
66
- if (!isSupported()) return;
29
+ if (process.env.NODE_ENV !== "production" || !("serviceWorker" in navigator) || !("caches" in window)) return;
67
30
  if (!enabled) {
68
- caches.delete(CACHE).catch(() => {});
31
+ Promise.all([caches.delete(OFFLINE_CACHE), caches.delete(OFFLINE_DATA_CACHE)]).catch(() => {});
69
32
  return;
70
33
  }
71
34
  (async () => {
72
35
  await keepCopiesOnlyFor(userId ?? "");
73
36
  await navigator.serviceWorker.register(WORKER_PATH, { scope: "/" });
74
37
  if (!navigator.onLine) return;
75
- const cache = await caches.open(CACHE);
38
+ const cache = await caches.open(OFFLINE_CACHE);
76
39
  await savePage(cache, href);
77
40
  await saveLoadedFiles(cache);
78
41
  })().catch((error) => console.warn("[@softr/sdk] Offline mode could not save this page:", error));
@@ -83,15 +46,12 @@ function useOfflineMode(options = {}) {
83
46
  ]);
84
47
  return { online };
85
48
  }
86
- function isSupported() {
87
- return process.env.NODE_ENV === "production" && "serviceWorker" in navigator && "caches" in window;
88
- }
89
49
  /** Deletes the copies when they belong to someone else, then marks them as this visitor's. */
90
50
  async function keepCopiesOnlyFor(owner) {
91
- const stored = await (await caches.open(CACHE)).match(OWNER_KEY);
51
+ const stored = await (await caches.open(OFFLINE_CACHE)).match(OFFLINE_OWNER_KEY);
92
52
  if (stored !== void 0 && await stored.text() === owner) return;
93
- await caches.delete(CACHE);
94
- await (await caches.open(CACHE)).put(OWNER_KEY, new Response(owner));
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));
95
55
  }
96
56
  /**
97
57
  * A page reached by a link was never loaded as a whole page, so the worker has
@@ -115,7 +75,8 @@ async function saveLoadedFiles(cache) {
115
75
  if (!(entry instanceof PerformanceResourceTiming)) continue;
116
76
  if (entry.initiatorType === "fetch" || entry.initiatorType === "xmlhttprequest") continue;
117
77
  const url = new URL(entry.name);
118
- if (url.origin !== location.origin || url.pathname.startsWith("/_softr/") || url.pathname.startsWith("/.softr/")) continue;
78
+ if (url.origin !== location.origin) continue;
79
+ if (OFFLINE_SKIPPED_PREFIXES.some((prefix) => url.pathname.startsWith(prefix))) continue;
119
80
  if (await cache.match(url.href) === void 0) missing.push(url.href);
120
81
  }
121
82
  await Promise.all(missing.map((url) => cache.add(url).catch(() => {})));
@@ -130,4 +91,4 @@ function subscribeToConnection(onChange) {
130
91
  }
131
92
 
132
93
  //#endregion
133
- export { OFFLINE_WORKER, useOfflineMode };
94
+ export { useOfflineMode };
package/dist/package.js CHANGED
@@ -1,5 +1,5 @@
1
1
  //#region package.json
2
- var version = "1.17.0-alpha.1";
2
+ var version = "1.17.0-alpha.2";
3
3
 
4
4
  //#endregion
5
5
  export { version };
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 "./offline.js";
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;
package/dist/pwa.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import * as react6 from "react";
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(): react6.FunctionComponentElement<react6.FragmentProps>;
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,6 +1,6 @@
1
1
  {
2
2
  "name": "@softr/sdk",
3
- "version": "1.17.0-alpha.1",
3
+ "version": "1.17.0-alpha.2",
4
4
  "type": "module",
5
5
  "exports": {
6
6
  ".": { "types": "./dist/index.d.ts", "import": "./dist/index.js" },
@@ -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, 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.
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
  >