@softr/sdk 1.16.0-se23079.0 → 1.16.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/CHANGELOG.md CHANGED
@@ -4,8 +4,13 @@
4
4
 
5
5
  ### Minor Changes
6
6
 
7
- - Every `auth` call that signs a visitor in or up fails as `userLimitReached` when the plan of the app's workspace has no room for this user. Before, `auth.signIn` threw, and the other calls answered `invalidCode`, `invalidCredentials`, `invalidDetails` or `linkExpired`. Action: on the login and sign-up pages, give `userLimitReached` its own `case` and say the app has reached its user limit and the app owner can fix it.
8
- - A sign-in or a sign-up that needs a one-time email code or an authenticator app fails as `notEnabled` when the plan of the app's workspace does not include it, as after a downgrade. For the email code these are `auth.sendSignInCode`, `auth.signInWithCode`, `auth.signUp` and `auth.confirmSignUp` without a password, `auth.verifyEmailCode`, `auth.resendEmailCode`, and `auth.signIn` in an app that asks for an emailed code after the password. For the authenticator app it is every call that signs a visitor in, in an app that asks that visitor for an authenticator step. Before, these calls worked on every plan. Action: on the login and sign-up pages, give `notEnabled` its own `case` and say this way to sign in is not available and the app owner can fix it.
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
+
9
+ ## 1.15.4
10
+
11
+ ### Patch Changes
12
+
13
+ - Skills: the mcp skill and the `defineTool` docs now say that a tool's handler never calls `ds`, or anything else from `@softr/sdk/server`, itself. `src/start.ts` imports the tools and is part of the browser bundle, so such a handler fails the production build. Action: move each such call into a helper wrapped in `createServerOnlyFn` from `@tanstack/react-start`, and call the helper from the handler.
9
14
 
10
15
  ## 1.15.3
11
16
 
@@ -10,12 +10,13 @@ import { readLocaleSettings } from "../locale-settings.js";
10
10
  import { settings } from "./methods/settings.js";
11
11
  import { bootErrorMiddleware } from "../boot-error.js";
12
12
  import { pwaMiddleware } from "../pwa.js";
13
+ import { OFFLINE_USER_HEADER } from "../service-worker.js";
13
14
  import { pushMiddleware } from "../push.js";
14
15
  import { faviconMiddleware } from "../favicon.js";
15
16
  import { embeddingMiddleware } from "../embedding.js";
16
17
  import { appIdentityMiddleware } from "../app-identity.js";
17
18
  import { accessDeniedStatusMiddleware } from "../route/access-denied-status.js";
18
- import { getRequestHeader } from "@tanstack/react-start/server";
19
+ import { getRequestHeader, setResponseHeader } from "@tanstack/react-start/server";
19
20
  import { createContext, useContext } from "react";
20
21
  import { createMiddleware, createServerFn } from "@tanstack/react-start";
21
22
  import { rootRouteId, useRouteContext } from "@tanstack/react-router";
@@ -65,6 +66,7 @@ function softrAuthMiddleware() {
65
66
  return session;
66
67
  }
67
68
  const [{ user }, settings$1] = await Promise.all([getSession(), readLocaleSettings()]);
69
+ setResponseHeader(OFFLINE_USER_HEADER, user?.id ?? "");
68
70
  return next({ context: {
69
71
  user,
70
72
  permissions: { datasources: {} },
@@ -3,7 +3,7 @@ import { writeCookies } from "../../cookies.js";
3
3
  import { sessionConfig } from "../config.js";
4
4
  import { makePlatform } from "../platform.js";
5
5
  import { assertCanChange, clearPendingAuth, makeSessionDataCookie, makeSessionTokenCookie, readPendingAuthToken, readSessionToken } from "../session.js";
6
- import { authError, isNotInPlan, isUserLimitReached } from "./utils.js";
6
+ import { authError } from "./utils.js";
7
7
 
8
8
  //#region src/auth/methods/authenticator.ts
9
9
  /**
@@ -42,8 +42,6 @@ async function confirmAuthenticatorSetup(details) {
42
42
  assertCanChange("auth.confirmAuthenticatorSetup");
43
43
  const result = await makePlatform(sessionConfig().applicationId).authenticatorSetupComplete(readPendingAuthToken() ?? readSessionToken(), details.code);
44
44
  if (!result.ok) {
45
- if (isUserLimitReached(result)) return authError("userLimitReached", result.message);
46
- if (isNotInPlan(result)) return authError("notEnabled", result.message);
47
45
  if (result.status === 400 || result.status === 401) return authError("invalidCode", result.message);
48
46
  if (result.status === 429) return authError("tooManyAttempts", result.message);
49
47
  if (result.status >= 500) panic(`Expected authenticator setup to finish, but got ${result.status}: ` + result.message);
@@ -70,8 +68,6 @@ async function skipAuthenticatorSetup() {
70
68
  assertCanChange("auth.skipAuthenticatorSetup");
71
69
  const result = await makePlatform(sessionConfig().applicationId).authenticatorSetupDismiss(readPendingAuthToken() ?? readSessionToken());
72
70
  if (!result.ok) {
73
- if (isUserLimitReached(result)) return authError("userLimitReached", result.message);
74
- if (isNotInPlan(result)) return authError("notEnabled", result.message);
75
71
  if (result.status === 401) return authError("notAuthenticated", result.message);
76
72
  if (result.status === 429) return authError("tooManyAttempts", result.message);
77
73
  if (result.status >= 500) panic(`Expected to skip authenticator setup, but got ${result.status}: ` + result.message);
@@ -96,8 +92,6 @@ async function verifyAuthenticator(credentials) {
96
92
  assertCanChange("auth.verifyAuthenticator");
97
93
  const result = await makePlatform(sessionConfig().applicationId).authenticatorVerify(readPendingAuthToken() ?? readSessionToken(), "code" in credentials ? { totpCode: credentials.code } : { backupCode: credentials.backupCode });
98
94
  if (!result.ok) {
99
- if (isUserLimitReached(result)) return authError("userLimitReached", result.message);
100
- if (isNotInPlan(result)) return authError("notEnabled", result.message);
101
95
  if (result.status === 400 || result.status === 401) return authError("invalidCode", result.message);
102
96
  if (result.status === 429) return authError("tooManyAttempts", result.message);
103
97
  if (result.status >= 500) panic(`Expected to verify the authenticator, but got ${result.status}: ` + result.message);
@@ -9,9 +9,6 @@ import { AuthError, Result } from "./utils.js";
9
9
  *
10
10
  * An address with no account fails as `noAccount`, and a deactivated one as
11
11
  * `accountDeactivated`, so the visitor is not left waiting for an email.
12
- *
13
- * It fails as `notEnabled` when the app's plan no longer includes one-time
14
- * email codes, as after a downgrade.
15
12
  */
16
13
  declare function sendSignInCode(details: {
17
14
  email: string;
@@ -3,7 +3,7 @@ import { writeCookies } from "../../cookies.js";
3
3
  import { sessionConfig } from "../config.js";
4
4
  import { makePlatform } from "../platform.js";
5
5
  import { assertCanChange, clearPendingAuth, makePendingAuthCookie, makeSessionDataCookie, makeSessionTokenCookie } from "../session.js";
6
- import { authError, isNotInPlan, isUserLimitReached } from "./utils.js";
6
+ import { authError } from "./utils.js";
7
7
 
8
8
  //#region src/auth/methods/code.ts
9
9
  const SEND_CODE_ERRORS = new Map([["No account exists for this email.", "noAccount"], ["This account is deactivated. Please contact the application owner.", "accountDeactivated"]]);
@@ -13,15 +13,11 @@ const SEND_CODE_ERRORS = new Map([["No account exists for this email.", "noAccou
13
13
  *
14
14
  * An address with no account fails as `noAccount`, and a deactivated one as
15
15
  * `accountDeactivated`, so the visitor is not left waiting for an email.
16
- *
17
- * It fails as `notEnabled` when the app's plan no longer includes one-time
18
- * email codes, as after a downgrade.
19
16
  */
20
17
  async function sendSignInCode(details) {
21
18
  assertCanChange("auth.sendSignInCode");
22
19
  const result = await makePlatform(sessionConfig().applicationId).sendSignInCode(details.email);
23
20
  if (!result.ok) {
24
- if (isNotInPlan(result)) return authError("notEnabled", result.message);
25
21
  if (result.status === 429) return authError("tooManyAttempts", result.message);
26
22
  if (result.status === 400) return authError(SEND_CODE_ERRORS.get(result.message) ?? "invalidDetails", result.message);
27
23
  if (result.status >= 500) panic(`Expected the sign-in code to be emailed, but got ${result.status}: ` + result.message);
@@ -43,8 +39,6 @@ async function signInWithCode(credentials) {
43
39
  assertCanChange("auth.signInWithCode");
44
40
  const result = await makePlatform(sessionConfig().applicationId).signInWithCode(credentials);
45
41
  if (!result.ok) {
46
- if (isUserLimitReached(result)) return authError("userLimitReached", result.message);
47
- if (isNotInPlan(result)) return authError("notEnabled", result.message);
48
42
  if (result.status === 429) return authError("tooManyAttempts", result.message);
49
43
  if (result.status === 400 || result.status === 401) return authError("invalidCode", result.message);
50
44
  if (result.status >= 500) panic(`Expected sign-in to succeed, but got ${result.status}: ` + result.message);
@@ -3,7 +3,7 @@ import { writeCookies } from "../../cookies.js";
3
3
  import { sessionConfig } from "../config.js";
4
4
  import { makePlatform } from "../platform.js";
5
5
  import { assertCanChange, clearPendingAuth, makePendingAuthCookie, makeSessionDataCookie, makeSessionTokenCookie, readPendingAuthToken } from "../session.js";
6
- import { authError, isNotInPlan, isUserLimitReached } from "./utils.js";
6
+ import { authError } from "./utils.js";
7
7
 
8
8
  //#region src/auth/methods/emailCode2fa.ts
9
9
  /**
@@ -18,8 +18,6 @@ async function verifyEmailCode(details) {
18
18
  assertCanChange("auth.verifyEmailCode");
19
19
  const result = await makePlatform(sessionConfig().applicationId).emailCodeVerify(readPendingAuthToken(), details.code);
20
20
  if (!result.ok) {
21
- if (isUserLimitReached(result)) return authError("userLimitReached", result.message);
22
- if (isNotInPlan(result)) return authError("notEnabled", result.message);
23
21
  if (result.status === 400 || result.status === 401) return authError("invalidCode", result.message);
24
22
  if (result.status === 429) return authError("tooManyAttempts", result.message);
25
23
  if (result.status >= 500) panic(`Expected to verify the emailed code, but got ${result.status}: ` + result.message);
@@ -57,7 +55,6 @@ async function resendEmailCode() {
57
55
  assertCanChange("auth.resendEmailCode");
58
56
  const result = await makePlatform(sessionConfig().applicationId).emailCodeResend(readPendingAuthToken());
59
57
  if (!result.ok) {
60
- if (isNotInPlan(result)) return authError("notEnabled", result.message);
61
58
  if (result.status === 401) return authError("notAuthenticated", result.message);
62
59
  if (result.status === 429) return authError("tooManyAttempts", result.message);
63
60
  if (result.status >= 500) panic(`Expected the code to be emailed again, but got ${result.status}: ` + result.message);
@@ -3,7 +3,7 @@ import { writeCookies } from "../../cookies.js";
3
3
  import { sessionConfig } from "../config.js";
4
4
  import { makePlatform } from "../platform.js";
5
5
  import { assertCanChange, makePendingAuthCookie, makeSessionDataCookie, makeSessionTokenCookie } from "../session.js";
6
- import { authError, isNotInPlan, isUserLimitReached } from "./utils.js";
6
+ import { authError } from "./utils.js";
7
7
 
8
8
  //#region src/auth/methods/magicLink.ts
9
9
  /**
@@ -18,8 +18,6 @@ async function signInWithMagicLink(credentials) {
18
18
  assertCanChange("auth.signInWithMagicLink");
19
19
  const result = await makePlatform(sessionConfig().applicationId).signInWithMagicLink(credentials);
20
20
  if (!result.ok) {
21
- if (isUserLimitReached(result)) return authError("userLimitReached", result.message);
22
- if (isNotInPlan(result)) return authError("notEnabled", result.message);
23
21
  if (result.status === 429) return authError("tooManyAttempts", result.message);
24
22
  if (result.status === 400 || result.status === 401) return authError("invalidCredentials", result.message);
25
23
  if (result.status >= 500) panic(`Expected magic-link sign-in to succeed, but got ${result.status}: ` + result.message);
@@ -3,7 +3,7 @@ import { writeCookies } from "../../cookies.js";
3
3
  import { sessionConfig } from "../config.js";
4
4
  import { makePlatform } from "../platform.js";
5
5
  import { assertCanChange, clearPendingAuth, clearSession, makePendingAuthCookie, makeSessionDataCookie, makeSessionTokenCookie, readSessionToken } from "../session.js";
6
- import { authError, isNotInPlan, isUserLimitReached } from "./utils.js";
6
+ import { authError } from "./utils.js";
7
7
 
8
8
  //#region src/auth/methods/password.ts
9
9
  /**
@@ -18,8 +18,6 @@ async function signIn(credentials) {
18
18
  assertCanChange("auth.signIn");
19
19
  const result = await makePlatform(sessionConfig().applicationId).tokens(credentials);
20
20
  if (!result.ok) {
21
- if (isUserLimitReached(result)) return authError("userLimitReached", result.message);
22
- if (isNotInPlan(result)) return authError("notEnabled", result.message);
23
21
  if (result.status === 401) return authError("invalidCredentials", result.message);
24
22
  if (result.status === 429) return authError("tooManyAttempts", result.message);
25
23
  if (result.status >= 500) panic(`Expected sign-in to succeed, but got ${result.status}: ` + result.message);
@@ -3,7 +3,7 @@ import { writeCookies } from "../../cookies.js";
3
3
  import { sessionConfig } from "../config.js";
4
4
  import { makePlatform } from "../platform.js";
5
5
  import { assertCanChange, clearPendingAuth, makePendingAuthCookie, makeSessionDataCookie, makeSessionTokenCookie } from "../session.js";
6
- import { authError, isNotInPlan, isUserLimitReached } from "./utils.js";
6
+ import { authError } from "./utils.js";
7
7
 
8
8
  //#region src/auth/methods/passwordLink.ts
9
9
  /**
@@ -31,7 +31,6 @@ async function requestPasswordReset(details) {
31
31
  async function checkPasswordLink(details) {
32
32
  const result = await makePlatform(sessionConfig().applicationId).checkPasswordToken(details);
33
33
  if (!result.ok) {
34
- if (isUserLimitReached(result)) return authError("userLimitReached", result.message);
35
34
  if (result.status === 429) return authError("tooManyAttempts", result.message);
36
35
  if (result.status === 400 || result.status === 401) return authError("linkExpired", result.message);
37
36
  panic(`Expected the link to be checked, but got ${result.status}: ${result.message}.`);
@@ -52,8 +51,6 @@ async function setPasswordWithLink(details) {
52
51
  assertCanChange("auth.setPasswordWithLink");
53
52
  const result = await makePlatform(sessionConfig().applicationId).setPassword(details);
54
53
  if (!result.ok) {
55
- if (isUserLimitReached(result)) return authError("userLimitReached", result.message);
56
- if (isNotInPlan(result)) return authError("notEnabled", result.message);
57
54
  if (result.status === 429) return authError("tooManyAttempts", result.message);
58
55
  if (result.status === 400 && result.message.startsWith("Password must be at least")) return authError("invalidDetails", result.message);
59
56
  if (result.status === 400 || result.status === 401) return authError("linkExpired", result.message);
@@ -3,7 +3,7 @@ import { writeCookies } from "../../cookies.js";
3
3
  import { sessionConfig } from "../config.js";
4
4
  import { makePlatform } from "../platform.js";
5
5
  import { assertCanChange, clearPendingAuth, makePendingAuthCookie, makeSessionDataCookie, makeSessionTokenCookie } from "../session.js";
6
- import { authError, isNotInPlan, isUserLimitReached } from "./utils.js";
6
+ import { authError } from "./utils.js";
7
7
 
8
8
  //#region src/auth/methods/signup.ts
9
9
  /**
@@ -15,8 +15,6 @@ async function signUp(details) {
15
15
  assertCanChange("auth.signUp");
16
16
  const result = await makePlatform(sessionConfig().applicationId).sendSignUpCode(details);
17
17
  if (!result.ok) {
18
- if (isUserLimitReached(result)) return authError("userLimitReached", result.message);
19
- if (isNotInPlan(result)) return authError("notEnabled", result.message);
20
18
  if (result.status === 409) return authError("emailTaken", result.message);
21
19
  if (result.status === 429) return authError("tooManyAttempts", result.message);
22
20
  if (result.status === 400) return authError("invalidDetails", result.message);
@@ -50,8 +48,6 @@ async function confirmSignUp(details) {
50
48
  password
51
49
  });
52
50
  if (!result.ok) {
53
- if (isUserLimitReached(result)) return authError("userLimitReached", result.message);
54
- if (isNotInPlan(result)) return authError("notEnabled", result.message);
55
51
  if (result.status === 409) return authError("emailTaken", result.message);
56
52
  if (result.status === 429) return authError("tooManyAttempts", result.message);
57
53
  if (result.status === 400 && result.message.startsWith("Password must be at least")) return authError("invalidDetails", result.message);
@@ -3,7 +3,7 @@ import { writeCookies } from "../../cookies.js";
3
3
  import { sessionConfig } from "../config.js";
4
4
  import { makePlatform } from "../platform.js";
5
5
  import { assertCanChange, clearPendingAuth, makePendingAuthCookie, makeSessionDataCookie, makeSessionTokenCookie } from "../session.js";
6
- import { authError, isNotInPlan, isUserLimitReached } from "./utils.js";
6
+ import { authError } from "./utils.js";
7
7
  import { z } from "zod";
8
8
 
9
9
  //#region src/auth/methods/social.ts
@@ -27,8 +27,6 @@ async function signInWithGoogle(credentials) {
27
27
  assertCanChange("auth.signInWithGoogle");
28
28
  const result = await makePlatform(sessionConfig().applicationId).signInWithGoogle(credentials);
29
29
  if (!result.ok) {
30
- if (isUserLimitReached(result)) return authError("userLimitReached", result.message);
31
- if (isNotInPlan(result)) return authError("notEnabled", result.message);
32
30
  if (result.status === 429) return authError("tooManyAttempts", result.message);
33
31
  const body = errorBodySchema.safeParse(result.body);
34
32
  if (body.success && body.data.code === "GOOGLE_NOT_IN_PLAN") return authError("notEnabled", result.message);
@@ -10,8 +10,6 @@ type AuthError = {
10
10
  code: AuthErrorCode;
11
11
  message: string;
12
12
  };
13
- type AuthErrorCode = "invalidCredentials" | "tooManyAttempts" | "emailTaken" | "invalidDetails" | "invalidCode" | "noAccount" | "accountDeactivated" | "notAuthenticated" | "emailDomainNotAllowed"
14
- /** The plan of the app's workspace no longer includes this way to sign in, as after a downgrade. */ | "notEnabled" | "linkExpired" | "invalidName" | "invalidPhoto" | "fileTooLarge" | "notAnImage" | "avatarNotSupported"
15
- /** Any call that signs a visitor in or up: the plan of the app's workspace has no room for this user. */ | "userLimitReached";
13
+ type AuthErrorCode = "invalidCredentials" | "tooManyAttempts" | "emailTaken" | "invalidDetails" | "invalidCode" | "noAccount" | "accountDeactivated" | "notAuthenticated" | "emailDomainNotAllowed" | "notEnabled" | "linkExpired" | "invalidName" | "invalidPhoto" | "fileTooLarge" | "notAnImage" | "avatarNotSupported";
16
14
  //#endregion
17
15
  export { AuthError, Result };
@@ -1,5 +1,3 @@
1
- import { z } from "zod";
2
-
3
1
  //#region src/auth/methods/utils.ts
4
2
  function authError(code, message) {
5
3
  return {
@@ -10,25 +8,6 @@ function authError(code, message) {
10
8
  }
11
9
  };
12
10
  }
13
- const errorBodySchema = z.object({ code: z.string() });
14
- /**
15
- * True when Softr refused because the plan of the app's workspace has no room
16
- * for this user. It arrives as a 400, like a wrong code, so the status cannot
17
- * tell them apart.
18
- */
19
- function isUserLimitReached(result) {
20
- const body = errorBodySchema.safeParse(result.body);
21
- return body.success && body.data.code === "USER_LIMIT_REACHED";
22
- }
23
- /**
24
- * True when Softr refused because the plan of the app's workspace does not
25
- * include the emailed code or the authenticator app this sign-in needs, as
26
- * after a downgrade.
27
- */
28
- function isNotInPlan(result) {
29
- const body = errorBodySchema.safeParse(result.body);
30
- return body.success && (body.data.code === "EMAIL_CODE_NOT_IN_PLAN" || body.data.code === "AUTHENTICATOR_NOT_IN_PLAN");
31
- }
32
11
 
33
12
  //#endregion
34
- export { authError, isNotInPlan, isUserLimitReached };
13
+ export { authError };
package/dist/auth/sso.js CHANGED
@@ -145,8 +145,7 @@ function failure(result) {
145
145
  case "SSO_IDP_REJECTED": return { error: "idp" };
146
146
  case "SSO_NOT_ENABLED":
147
147
  case "SSO_NOT_IN_PLAN":
148
- case "SSO_MISCONFIGURED":
149
- case "AUTHENTICATOR_NOT_IN_PLAN": return { error: "not-enabled" };
148
+ case "SSO_MISCONFIGURED": return { error: "not-enabled" };
150
149
  case "SSO_SIGN_UP_DISABLED": return { error: "sign-up-disabled" };
151
150
  case "USER_DEACTIVATED":
152
151
  case "SIGN_IN_RESTRICTED": return { error: "restricted" };
package/dist/index.d.ts CHANGED
@@ -21,8 +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, OfflineModeOptions, useOfflineMode } from "./offline.js";
24
25
  import { DefaultErrorOverlay } from "./default-error-overlay.js";
25
26
  import { Audience } from "./route/audience.js";
26
27
  import { Logo, LogoFile } from "./softr-config.schema.js";
27
28
  import { getLogo } from "./softr-config.js";
28
- 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 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, 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
@@ -16,7 +16,8 @@ import { softrMcpMiddleware } from "./mcp.js";
16
16
  import { fieldShape, formatDuration, formatField, formatValue, registerSoftrFields } from "./fields/format.js";
17
17
  import { useOverrides } from "./core/use-overrides.js";
18
18
  import { useUserTimezone } from "./timezone.js";
19
+ import { useOfflineMode } from "./offline.js";
19
20
  import { DefaultErrorOverlay } from "./default-error-overlay.js";
20
21
  import { Audience } from "./route/audience.js";
21
22
 
22
- export { Audience, AuthSettingsProvider, DefaultErrorOverlay, FormattedDate, FormattingScope, SoftrPwaHead, 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, useOverrides, usePushNotifications, usePwaInstall, useUserTimezone };
23
+ export { Audience, AuthSettingsProvider, DefaultErrorOverlay, FormattedDate, FormattingScope, SoftrPwaHead, 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 };
@@ -0,0 +1,35 @@
1
+ //#region src/offline.d.ts
2
+ type OfflineMode = {
3
+ /**
4
+ * `false` while the browser has no connection, or while the app shows saved
5
+ * copies because it cannot reach the server. Always `true` during server rendering.
6
+ */
7
+ online: boolean;
8
+ };
9
+ type OfflineModeOptions = {
10
+ /**
11
+ * `false` turns offline mode off and deletes what this browser kept. Keep the
12
+ * call with `false` rather than removing it: browsers that ran offline mode
13
+ * before keep the visitor's copies, and keep saving new ones, until this runs
14
+ * or the visitor signs out. Defaults to `true`.
15
+ */
16
+ enabled?: boolean;
17
+ };
18
+ /**
19
+ * Lets the published app open without internet and show the pages and data
20
+ * the visitor loaded, read only. Saves made offline fail as usual.
21
+ *
22
+ * Call it once, in the root route's `RootDocument`. The saved copies are
23
+ * deleted when another visitor signs in on this browser, or when the visitor
24
+ * signs out. In the Studio preview it only reports `online`.
25
+ *
26
+ * @example
27
+ * function OfflineBanner() {
28
+ * const { online } = useOfflineMode()
29
+ * if (online) return null
30
+ * return <div role="status">You're offline. Showing the last saved data.</div>
31
+ * }
32
+ */
33
+ declare function useOfflineMode(options?: OfflineModeOptions): OfflineMode;
34
+ //#endregion
35
+ export { OfflineMode, OfflineModeOptions, useOfflineMode };
@@ -0,0 +1,106 @@
1
+ import { OFFLINE_CACHE, OFFLINE_DATA_CACHE, OFFLINE_MESSAGE, OFFLINE_OWNER_KEY, OFFLINE_SAVE_HEADER, OFFLINE_SKIPPED_PREFIXES, WORKER_PATH } from "./service-worker.js";
2
+ import { useCurrentUser } from "./auth/isomorphic.js";
3
+ import { useEffect, useState, useSyncExternalStore } from "react";
4
+ import { useLocation } from "@tanstack/react-router";
5
+
6
+ //#region src/offline.ts
7
+ const PAGE_MAX_AGE_MS = 30 * 6e4;
8
+ /**
9
+ * Lets the published app open without internet and show the pages and data
10
+ * the visitor loaded, read only. Saves made offline fail as usual.
11
+ *
12
+ * Call it once, in the root route's `RootDocument`. The saved copies are
13
+ * deleted when another visitor signs in on this browser, or when the visitor
14
+ * signs out. In the Studio preview it only reports `online`.
15
+ *
16
+ * @example
17
+ * function OfflineBanner() {
18
+ * const { online } = useOfflineMode()
19
+ * if (online) return null
20
+ * return <div role="status">You're offline. Showing the last saved data.</div>
21
+ * }
22
+ */
23
+ function useOfflineMode(options = {}) {
24
+ const enabled = options.enabled ?? true;
25
+ const userId = useCurrentUser()?.id ?? null;
26
+ const pathname = useLocation({ select: (location$1) => location$1.pathname });
27
+ const connected = useSyncExternalStore(subscribeToConnection, () => navigator.onLine, () => true);
28
+ const [showingCopies, setShowingCopies] = useState(false);
29
+ useEffect(() => {
30
+ if (!("serviceWorker" in navigator)) return;
31
+ const onMessage = (event) => {
32
+ const data = event.data;
33
+ if (typeof data !== "object" || data === null || !("type" in data) || data.type !== OFFLINE_MESSAGE) return;
34
+ setShowingCopies("showingCopies" in data && data.showingCopies === true);
35
+ };
36
+ const onOnline = () => {
37
+ setShowingCopies(false);
38
+ navigator.serviceWorker.controller?.postMessage({
39
+ type: OFFLINE_MESSAGE,
40
+ online: true
41
+ });
42
+ };
43
+ navigator.serviceWorker.addEventListener("message", onMessage);
44
+ window.addEventListener("online", onOnline);
45
+ navigator.serviceWorker.controller?.postMessage({ type: OFFLINE_MESSAGE });
46
+ return () => {
47
+ navigator.serviceWorker.removeEventListener("message", onMessage);
48
+ window.removeEventListener("online", onOnline);
49
+ };
50
+ }, []);
51
+ useEffect(() => {
52
+ if (process.env.NODE_ENV !== "production" || !("serviceWorker" in navigator) || !("caches" in window)) return;
53
+ if (!enabled) {
54
+ deleteCopies().catch(() => {});
55
+ return;
56
+ }
57
+ if (!connected || showingCopies) return;
58
+ (async () => {
59
+ const owner = userId ?? "";
60
+ const stored = await (await caches.open(OFFLINE_CACHE)).match(OFFLINE_OWNER_KEY);
61
+ if (stored === void 0 || await stored.text() !== owner) {
62
+ await deleteCopies();
63
+ await (await caches.open(OFFLINE_CACHE)).put(OFFLINE_OWNER_KEY, new Response(owner));
64
+ }
65
+ await navigator.serviceWorker.register(WORKER_PATH, { scope: "/" });
66
+ const cache = await caches.open(OFFLINE_CACHE);
67
+ const save = (url) => cache.add(new Request(url, { headers: { [OFFLINE_SAVE_HEADER]: "1" } }));
68
+ const page = await cache.match(pathname);
69
+ const savedAt = Date.parse(page?.headers.get("date") ?? "");
70
+ if (!(Date.now() - savedAt < PAGE_MAX_AGE_MS)) await save(pathname).catch(() => {});
71
+ const files = [];
72
+ for (const entry of performance.getEntriesByType("resource")) {
73
+ if (!(entry instanceof PerformanceResourceTiming)) continue;
74
+ if (entry.initiatorType === "fetch" || entry.initiatorType === "xmlhttprequest") continue;
75
+ const url = new URL(entry.name);
76
+ if (url.origin !== location.origin) continue;
77
+ if (OFFLINE_SKIPPED_PREFIXES.some((prefix) => url.pathname.startsWith(prefix))) continue;
78
+ files.push(url.href);
79
+ }
80
+ await Promise.all(files.map(async (url) => {
81
+ if (await cache.match(url) === void 0) await save(url).catch(() => {});
82
+ }));
83
+ })().catch((error) => console.warn("[@softr/sdk] Offline mode could not save this page:", error));
84
+ }, [
85
+ enabled,
86
+ userId,
87
+ pathname,
88
+ connected,
89
+ showingCopies
90
+ ]);
91
+ return { online: connected && !showingCopies };
92
+ }
93
+ async function deleteCopies() {
94
+ await Promise.all([caches.delete(OFFLINE_CACHE), caches.delete(OFFLINE_DATA_CACHE)]);
95
+ }
96
+ function subscribeToConnection(onChange) {
97
+ window.addEventListener("online", onChange);
98
+ window.addEventListener("offline", onChange);
99
+ return () => {
100
+ window.removeEventListener("online", onChange);
101
+ window.removeEventListener("offline", onChange);
102
+ };
103
+ }
104
+
105
+ //#endregion
106
+ export { useOfflineMode };
package/dist/package.js CHANGED
@@ -1,5 +1,5 @@
1
1
  //#region package.json
2
- var version = "1.16.0-se23079.0";
2
+ var version = "1.16.0";
3
3
 
4
4
  //#endregion
5
5
  export { version };
package/dist/push.js CHANGED
@@ -4,13 +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, WORKER_PATH } from "./service-worker.js";
7
8
  import { z } from "zod";
8
9
  import { useCallback, useEffect, useState } from "react";
9
10
  import { createMiddleware } from "@tanstack/react-start";
10
11
  import { rootRouteId, useRouteContext } from "@tanstack/react-router";
11
12
 
12
13
  //#region src/push.ts
13
- const WORKER_PATH = "/_softr/sw.js";
14
14
  const SETTINGS_PATH = "/_softr/push.json";
15
15
  const SUBSCRIPTION_PATH = "/_softr/push";
16
16
  const TTL_MS = 6e4;
@@ -55,9 +55,10 @@ function readWorker() {
55
55
  });
56
56
  }
57
57
  /**
58
- * Serves push notifications from the app's own origin: the service worker, the
59
- * app's push settings, and saving or removing this browser's subscription for
60
- * the signed-in visitor. Every other request passes through untouched.
58
+ * Serves push notifications from the app's own origin: the service worker,
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.
61
62
  */
62
63
  function pushMiddleware() {
63
64
  return createMiddleware({ type: "request" }).server(async ({ next, pathname, request }) => {
@@ -67,7 +68,7 @@ function pushMiddleware() {
67
68
  status: 503,
68
69
  headers: { "cache-control": "no-store" }
69
70
  });
70
- return new Response(worker, { headers: {
71
+ return new Response(worker + OFFLINE_WORKER, { headers: {
71
72
  "content-type": "text/javascript; charset=utf-8",
72
73
  "cache-control": "no-cache",
73
74
  "service-worker-allowed": "/"
@@ -0,0 +1,120 @@
1
+ //#region src/service-worker.ts
2
+ const WORKER_PATH = "/_softr/sw.js";
3
+ /** Pages, scripts, styles and images. Its owner entry 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
+ /** Between the worker and the page: whether the worker answers with saved copies. */
10
+ const OFFLINE_MESSAGE = "softr-offline";
11
+ /**
12
+ * Names the signed-in user on each answer from the app's server, or is empty
13
+ * for a signed-out visitor. The worker deletes copies kept for someone else.
14
+ */
15
+ const OFFLINE_USER_HEADER = "x-softr-offline-user";
16
+ /** Marks a request `useOfflineMode()` saves itself, so the worker leaves it alone. */
17
+ const OFFLINE_SAVE_HEADER = "x-softr-offline-save";
18
+ /** Paths offline mode never keeps: the SDK's own routes and the canvas engine's. */
19
+ const OFFLINE_SKIPPED_PREFIXES = ["/_softr/", "/.softr/"];
20
+ const MAX_COPIES = 300;
21
+ /**
22
+ * Added after the platform's worker. Same-origin GET requests go to the
23
+ * network first, and the last good answer is kept on the device for when the
24
+ * network fails. Writes and live streams are never kept.
25
+ *
26
+ * It keeps nothing until `useOfflineMode()` writes the owner entry. An app that
27
+ * registers the worker only for push still has its requests pass through it.
28
+ */
29
+ const OFFLINE_WORKER = `
30
+ // Offline mode, added by @softr/sdk.
31
+ const SOFTR_OFFLINE_CACHE = ${JSON.stringify(OFFLINE_CACHE)};
32
+ const SOFTR_OFFLINE_DATA_CACHE = ${JSON.stringify(OFFLINE_DATA_CACHE)};
33
+ const SOFTR_OFFLINE_OWNER_KEY = ${JSON.stringify(OFFLINE_OWNER_KEY)};
34
+ const SOFTR_OFFLINE_SAVE_HEADER = ${JSON.stringify(OFFLINE_SAVE_HEADER)};
35
+ const SOFTR_OFFLINE_SKIPPED = ${JSON.stringify(OFFLINE_SKIPPED_PREFIXES)};
36
+ const SOFTR_OFFLINE_MESSAGE = ${JSON.stringify(OFFLINE_MESSAGE)};
37
+ const SOFTR_OFFLINE_USER_HEADER = ${JSON.stringify(OFFLINE_USER_HEADER)};
38
+ // Unknown after the worker starts, so the first answer after a restart always reaches the page.
39
+ let softrShowingCopies;
40
+
41
+ function softrSetShowingCopies(showingCopies) {
42
+ if (softrShowingCopies === showingCopies) return;
43
+ softrShowingCopies = showingCopies;
44
+ self.clients.matchAll({ type: 'window' }).then((pages) => {
45
+ for (const page of pages) page.postMessage({ type: SOFTR_OFFLINE_MESSAGE, showingCopies });
46
+ });
47
+ }
48
+
49
+ // Page loads start while the worker starts, so a stopped worker does not delay them.
50
+ self.addEventListener('activate', (event) => {
51
+ if (self.registration.navigationPreload) event.waitUntil(self.registration.navigationPreload.enable());
52
+ });
53
+
54
+ self.addEventListener('message', (event) => {
55
+ if (event.data && event.data.type === SOFTR_OFFLINE_MESSAGE && event.source) {
56
+ // The browser is back online. The next request that fails says so again.
57
+ if (event.data.online === true) softrShowingCopies = false;
58
+ event.source.postMessage({ type: SOFTR_OFFLINE_MESSAGE, showingCopies: softrShowingCopies === true });
59
+ }
60
+ });
61
+
62
+ function softrOfflineOwner() {
63
+ return caches.match(SOFTR_OFFLINE_OWNER_KEY, { cacheName: SOFTR_OFFLINE_CACHE }).then((owner) => owner && owner.text());
64
+ }
65
+
66
+ async function softrKeepCopy(owner, cacheName, key, response) {
67
+ // The copies were deleted, or now belong to someone else, while the request ran.
68
+ if ((await softrOfflineOwner()) !== owner) return;
69
+ const cache = await caches.open(cacheName);
70
+ await cache.put(key, response);
71
+ const keys = (await cache.keys()).filter((key) => new URL(key.url).pathname !== SOFTR_OFFLINE_OWNER_KEY);
72
+ await Promise.all(keys.slice(0, Math.max(0, keys.length - ${MAX_COPIES})).map((key) => cache.delete(key)));
73
+ }
74
+
75
+ self.addEventListener('fetch', (event) => {
76
+ const request = event.request;
77
+ if (request.method !== 'GET') return;
78
+ const url = new URL(request.url);
79
+ if (url.origin !== self.location.origin) return;
80
+ if (SOFTR_OFFLINE_SKIPPED.some((prefix) => url.pathname.startsWith(prefix))) return;
81
+ if (request.headers.has(SOFTR_OFFLINE_SAVE_HEADER)) return;
82
+ event.respondWith((async () => {
83
+ const fromNetwork = () => (request.mode === 'navigate' && event.preloadResponse
84
+ ? event.preloadResponse.then((preloaded) => preloaded || fetch(request))
85
+ : fetch(request));
86
+ const owner = await softrOfflineOwner();
87
+ if (owner === undefined) return fromNetwork();
88
+ // A data call from the app's code has no destination; a page or a file has one.
89
+ const cacheName = request.destination === '' ? SOFTR_OFFLINE_DATA_CACHE : SOFTR_OFFLINE_CACHE;
90
+ // One copy of a page per path, whatever the search, like the hook keeps. Offline,
91
+ // a page opened with another search gets that copy, and its data may be missing.
92
+ const key = request.mode === 'navigate' ? url.origin + url.pathname : request;
93
+ try {
94
+ const response = await fromNetwork();
95
+ softrSetShowingCopies(false);
96
+ const user = response.headers.get(SOFTR_OFFLINE_USER_HEADER);
97
+ if (user !== null && user !== owner) {
98
+ // Someone else is signed in. Delete the copies even when the page no longer runs the hook.
99
+ event.waitUntil(Promise.all([caches.delete(SOFTR_OFFLINE_CACHE), caches.delete(SOFTR_OFFLINE_DATA_CACHE)]));
100
+ return response;
101
+ }
102
+ const streamed = (response.headers.get('content-type') || '').startsWith('text/event-stream');
103
+ if (response.status === 200 && response.type === 'basic' && !streamed) {
104
+ event.waitUntil(softrKeepCopy(owner, cacheName, key, response.clone()).catch(() => {}));
105
+ }
106
+ return response;
107
+ } catch (error) {
108
+ const copy = await caches.match(key, { cacheName });
109
+ if (copy) {
110
+ softrSetShowingCopies(true);
111
+ return copy;
112
+ }
113
+ throw error;
114
+ }
115
+ })());
116
+ });
117
+ `;
118
+
119
+ //#endregion
120
+ export { OFFLINE_CACHE, OFFLINE_DATA_CACHE, OFFLINE_MESSAGE, OFFLINE_OWNER_KEY, OFFLINE_SAVE_HEADER, OFFLINE_SKIPPED_PREFIXES, OFFLINE_USER_HEADER, OFFLINE_WORKER, WORKER_PATH };
package/dist/tool.d.ts CHANGED
@@ -37,8 +37,12 @@ type ToolDefinition<TInput extends z.ZodObject, TOutput> = {
37
37
  */
38
38
  destructive?: boolean;
39
39
  /**
40
- * Runs the tool as the signed-in user. `ds` calls inside it act as that user,
41
- * with their groups, as a click in the app would. Return JSON.
40
+ * Runs the tool as the signed-in user. The `ds` calls it reaches act as that
41
+ * user, with their groups, as a click in the app would. Return JSON.
42
+ *
43
+ * Never call `ds`, or anything else from `@softr/sdk/server`, in the handler
44
+ * itself: the production build fails. Call a helper wrapped in
45
+ * `createServerOnlyFn` from `@tanstack/react-start`.
42
46
  */
43
47
  handler: (input: z.output<TInput>, context: {
44
48
  user: User;
@@ -48,6 +52,7 @@ type ToolDefinition<TInput extends z.ZodObject, TOutput> = {
48
52
  * An MCP tool that runs the app's own logic, for `softrMcpMiddleware({ tools })`.
49
53
  *
50
54
  * @example
55
+ * // createIssueFor is wrapped in createServerOnlyFn, and calls `ds`.
51
56
  * export const createIssue = defineTool({
52
57
  * name: 'create_issue',
53
58
  * description: 'Create an issue in a project. Returns the new issue with its key.',
package/dist/tool.js CHANGED
@@ -8,6 +8,7 @@ const TOOL_NAME = /^[A-Za-z0-9_.-]{1,128}$/;
8
8
  * An MCP tool that runs the app's own logic, for `softrMcpMiddleware({ tools })`.
9
9
  *
10
10
  * @example
11
+ * // createIssueFor is wrapped in createServerOnlyFn, and calls `ds`.
11
12
  * export const createIssue = defineTool({
12
13
  * name: 'create_issue',
13
14
  * description: 'Create an issue in a project. Returns the new issue with its key.',
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@softr/sdk",
3
- "version": "1.16.0-se23079.0",
3
+ "version": "1.16.0",
4
4
  "type": "module",
5
5
  "exports": {
6
6
  ".": { "types": "./dist/index.d.ts", "import": "./dist/index.js" },
@@ -57,6 +57,7 @@ Each sub-skill stands alone for its task and repeats the boundary above, so most
57
57
  | Open the app to AI assistants over MCP | [mcp/SKILL.md](./mcp/SKILL.md) |
58
58
  | Let visitors install the app on their home screen | [pwa/SKILL.md](./pwa/SKILL.md) |
59
59
  | Let visitors turn on push notifications | [push-notifications/SKILL.md](./push-notifications/SKILL.md) |
60
+ | Let the app open without internet, or show that the visitor is offline | [offline/SKILL.md](./offline/SKILL.md) |
60
61
  | Show a date, a time or a number | [formatting/SKILL.md](./formatting/SKILL.md) |
61
62
 
62
63
  ## Quick Decision Tree
@@ -104,6 +105,9 @@ Adding an install button, or making the app installable?
104
105
  Letting visitors turn on push notifications, or "notify users when …"?
105
106
  load softr-sdk/push-notifications
106
107
 
108
+ Letting the app work offline, or showing that the visitor is offline?
109
+ load softr-sdk/offline
110
+
107
111
  Showing a date, a time or a number on a page?
108
112
  load softr-sdk/formatting
109
113
 
@@ -134,11 +134,10 @@ type AuthErrorCode =
134
134
  | 'notAuthenticated' // a call that needs a signed-in visitor, made by one who is not
135
135
  | 'emailDomainNotAllowed' // signUp, signInWithGoogle: the app lets only some email domains sign up, and this is not one
136
136
  | 'linkExpired' // checkPasswordLink, setPasswordWithLink: the link is used, expired or no longer valid
137
- | 'notEnabled' // any call that signs a visitor in or up, or emails a code: the app's plan no longer includes Google sign-in, emailed codes or the authenticator app
138
- | 'userLimitReached' // any call that signs a visitor in or up: the plan of the app's workspace has no room for this user
137
+ | 'notEnabled' // signInWithGoogle: the app's plan no longer includes Google sign-in
139
138
  ```
140
139
 
141
- Branch on `error.code` with a `switch` and write your own wording. Never put `error.message` in front of the visitor. The one exception is `invalidDetails` from `setPasswordWithLink` and `confirmSignUp`. Show its message: it names the password rule that failed. On `userLimitReached` the visitor did nothing wrong, and a retry does not help. Say the app has reached its user limit and that the app owner can fix it. Give it its own `case` on the login and sign-up pages, so it does not fall to a "wrong password" or "wrong code" message.
140
+ Branch on `error.code` with a `switch` and write your own wording. Never put `error.message` in front of the visitor. The one exception is `invalidDetails` from `setPasswordWithLink` and `confirmSignUp`. Show its message: it names the password rule that failed.
142
141
 
143
142
  `code` is typed as every code the SDK produces, not the ones a given call can answer, so a `switch` needs a `default` even when the cases above it are complete. Give it a message rather than leaving it out.
144
143
 
@@ -14,7 +14,7 @@ metadata:
14
14
  library_version: 1.16.0
15
15
  ---
16
16
 
17
- **Boundary.** `softrMcpMiddleware` lives on `@softr/sdk` and is registered once, in `src/start.ts`. The actions you hand it are the same `defineQuery` / `defineMutation` values the app's own pages use — declared wherever they already live, not duplicated for MCP. The tools you hand it come from `defineTool`, also on `@softr/sdk`, and call the same server logic the pages do.
17
+ **Boundary.** `softrMcpMiddleware` lives on `@softr/sdk` and is registered once, in `src/start.ts`. The actions you hand it are the same `defineQuery` / `defineMutation` values the app's own pages use — declared wherever they already live, not duplicated for MCP. The tools you hand it come from `defineTool`, also on `@softr/sdk`, and call the same server logic the pages do. `src/start.ts` is part of the browser bundle, so a tool's handler never calls `ds` itself: it calls a helper wrapped in `createServerOnlyFn` from `@tanstack/react-start` (the `record-queries` boundary).
18
18
 
19
19
  # MCP
20
20
 
@@ -57,10 +57,8 @@ An action is one list, create, update or delete on one datasource. When the app
57
57
  ```ts
58
58
  // src/mcp-tools.ts
59
59
  import { defineTool } from '@softr/sdk'
60
- import { ds } from '@softr/sdk/server'
61
60
  import { z } from 'zod'
62
- import { createIssueFor } from './issues'
63
- import { projectIssues } from './actions'
61
+ import { createIssueFor, listIssues } from './issues'
64
62
 
65
63
  export const createIssue = defineTool({
66
64
  name: 'create_issue',
@@ -83,16 +81,30 @@ export const findIssues = defineTool({
83
81
  status: z.enum(['open', 'done']).optional().describe('Only issues with this status.'),
84
82
  }),
85
83
  readOnly: true,
86
- handler: async (input) => {
87
- let list = ds.list(projectIssues).where((q) => q.project.isOneOf([input.projectId]))
88
- if (input.status) list = list.where((q) => q.status.is(input.status))
89
- const { records } = await list.orderBy((q) => q.createdAt.desc).limit(50)
90
- return { issues: records.map((r) => ({ id: r.id, ...r.fields })) }
91
- },
84
+ handler: async (input) => ({ issues: await listIssues(input) }),
85
+ })
86
+ ```
87
+
88
+ The `ds` calls live in helpers wrapped in `createServerOnlyFn`, in a file of their own:
89
+
90
+ ```ts
91
+ // src/issues.ts
92
+ import { createServerOnlyFn } from '@tanstack/react-start'
93
+ import { ds } from '@softr/sdk/server'
94
+ import { projectIssues } from './actions'
95
+
96
+ export const listIssues = createServerOnlyFn(async ({ projectId, status }: { projectId: string; status?: 'open' | 'done' }) => {
97
+ let list = ds.list(projectIssues).where((q) => q.project.isOneOf([projectId]))
98
+ if (status) list = list.where((q) => q.status.is(status))
99
+ const { records } = await list.orderBy((q) => q.createdAt.desc).limit(50)
100
+ return records.map((r) => ({ id: r.id, ...r.fields }))
92
101
  })
93
102
  ```
94
103
 
95
- - **`handler` runs as the signed-in user.** `ds` calls inside it act as that user, with their groups, as a click in the app would. `user` is the same `User` a server function reads from `context.user`. Move logic a server function and a tool share into a function that takes the user, and pass `context.user` from the server function and `user` from the tool.
104
+ `createIssueFor` is wrapped the same way.
105
+
106
+ - **`handler` runs as the signed-in user.** The `ds` calls its helpers make act as that user, with their groups, as a click in the app would. `user` is the same `User` a server function reads from `context.user`. Move logic a server function and a tool share into a function that takes the user, and pass `context.user` from the server function and `user` from the tool.
107
+ - **`handler` never calls `ds` itself.** Nor anything else from `@softr/sdk/server`. Each such call goes in a helper wrapped in `createServerOnlyFn`, and the handler calls the helper. A helper the app's server functions already use is fine as long as it is wrapped.
96
108
  - **`readOnly` is required.** `true` only when the tool changes nothing. A read-only tool that calls `ds.create`, `ds.update`, `ds.delete`, `email`, `workflow`, `upload` or an `integration` action whose method is not `GET` or `HEAD` from `@softr/sdk/server` fails with an error, and nothing is written or sent. An integration that reads with `POST`, such as a search or GraphQL API, fails too: make that tool `readOnly: false`. So does every `auth` call that is not a plain read: a sign-in, a sign-up, a password reset, a sign-out, a profile change or an authenticator change. Your own calls to other services are not stopped, so keep them out of a read-only tool too. An `ai` call is not stopped either: it changes no data, but it spends the workspace's AI credits for an assistant approved to read only, so use it there on purpose.
97
109
  - **`destructive`** says whether a tool that is not read-only deletes or overwrites data: `true` when it does, `false` when it only adds. The assistant may ask the user before it runs a destructive one. Left out, the assistant is told neither and treats the tool as one that may delete or overwrite, so set it on every tool that is not read-only.
98
110
  - **`input` is a zod object.** Describe each field with `.describe()`: the assistant reads it. Use types JSON can carry: a string for a date, not `z.date()`, which fails when the tool is defined. A top-level argument the schema does not name is refused with a message saying which, and the handler does not run. Inside a nested object an unknown key is dropped without a word, so declare a nested object with `z.strictObject` to have it refused too.
@@ -125,6 +137,8 @@ Connecting starts with an approval page the app serves. Most people hit it signe
125
137
 
126
138
  **A write as an action, where the app has logic around it.** The record is written and everything the app does around it is skipped: no counter, no log entry, no email, no author. Write it as a `defineTool` that calls that logic.
127
139
 
140
+ **A tool handler that calls `ds` directly fails the production build.** `src/start.ts` imports the tool, so the server-only import reaches the browser bundle. The preview may still work, and publishing fails. Move the call into a `createServerOnlyFn` helper.
141
+
128
142
  **Marking a tool read-only that changes data.** Its writes fail when it runs. Set `readOnly: false`.
129
143
 
130
144
  **Registering after `softrAuthMiddleware`.** Not a supported order. Put the MCP middleware first.
@@ -0,0 +1,119 @@
1
+ ---
2
+ name: offline
3
+ description: >-
4
+ Let the published app open without internet and show the pages and data the
5
+ visitor last loaded, read only: useOfflineMode, the OfflineMode type, the
6
+ offline banner and saves made offline. The service worker is already served,
7
+ never write one.
8
+ metadata:
9
+ type: sub-skill
10
+ library: softr-sdk
11
+ library_version: 1.16.0
12
+ ---
13
+
14
+ # Offline mode
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, sometimes a little older. Pages the visitor never opened are not there: a link to one shows the app's error page. Offline mode keeps nothing to save later: a save made offline fails as it would on any network error, and the app tells the visitor, unless the app has its own offline saving.
17
+
18
+ > **CRITICAL**: Never write a service worker, a `public/sw.js`, or any `navigator.serviceWorker` or `caches` 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
+ >
20
+ > **CRITICAL**: `useOfflineMode()` keeps reads only. Saving offline is app code, built only when the builder asks for it: the changes wait in IndexedDB in the page and are sent when the connection is back. It never goes into a service worker.
21
+
22
+ ## Setup
23
+
24
+ ```ts
25
+ import { useOfflineMode } from '@softr/sdk'
26
+ import type { OfflineMode, OfflineModeOptions } from '@softr/sdk'
27
+ ```
28
+
29
+ ```ts
30
+ type OfflineModeOptions = {
31
+ enabled?: boolean // false turns offline mode off and deletes what browsers kept; defaults to true
32
+ }
33
+
34
+ type OfflineMode = {
35
+ online: boolean // false while the browser has no connection, or the app shows saved copies because it cannot reach the server; always true during server rendering
36
+ }
37
+ ```
38
+
39
+ ## Core Patterns
40
+
41
+ ### Turning it on
42
+
43
+ Call `useOfflineMode()` once, in `RootDocument` in `src/routes/__root.tsx`, so every page is kept. Call it nowhere else: each call also turns offline mode on or off. Render the banner from the same place. Use the banner component the template ships when it has one.
44
+
45
+ ```tsx
46
+ function OfflineBanner() {
47
+ const { online } = useOfflineMode()
48
+ if (online) return null
49
+ return <div role="status">You're offline. Showing the last saved data.</div>
50
+ }
51
+ ```
52
+
53
+ Offline mode works only on the published app. Inside the Studio preview `online` still follows the connection, but nothing is kept on the device. That is expected, not a bug to fix.
54
+
55
+ ### Saves made offline
56
+
57
+ A save made offline rejects like any failed request. Catch it as usual, and when `navigator.onLine` is `false`, say that the visitor is offline rather than showing a generic error. Do not call `useOfflineMode()` in the form for this:
58
+
59
+ ```tsx
60
+ import { toast } from 'sonner'
61
+
62
+ // `save` is the form's own server function.
63
+ save(values).catch(() =>
64
+ toast.error(navigator.onLine ? 'Could not save your changes.' : "You're offline. Connect to save your changes."),
65
+ )
66
+ ```
67
+
68
+ ### Signing out
69
+
70
+ Nothing to add. The copies kept on the device are deleted when the visitor signs out, or when someone else signs in on the same browser.
71
+
72
+ ### Turning it off
73
+
74
+ 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 offline mode on in browsers that ran it: they keep the visitor's copies, and keep saving new ones, until the visitor signs out or someone else signs in.
75
+
76
+ ## Common Mistakes
77
+
78
+ ### CRITICAL Writing a service worker for offline
79
+
80
+ Wrong:
81
+
82
+ ```ts
83
+ navigator.serviceWorker.register('/sw.js')
84
+ ```
85
+
86
+ Correct:
87
+
88
+ ```tsx
89
+ const { online } = useOfflineMode()
90
+ ```
91
+
92
+ The app serves one service worker for push and offline mode. A worker of the app's own replaces it, so push notifications stop and nothing is kept offline.
93
+
94
+ Source: packages/sdk/src/offline.ts
95
+
96
+ ### HIGH Calling the hook only on some pages
97
+
98
+ Wrong:
99
+
100
+ ```tsx
101
+ // src/routes/_app/orders.tsx
102
+ const { online } = useOfflineMode()
103
+ ```
104
+
105
+ Correct:
106
+
107
+ ```tsx
108
+ // RootDocument in src/routes/__root.tsx
109
+ <OfflineBanner />
110
+ ```
111
+
112
+ A page is kept for offline only while the hook runs. Called from one page, every other page is missing offline.
113
+
114
+ Source: packages/sdk/src/offline.ts
115
+
116
+ ## References
117
+
118
+ - [SKILL.md](../SKILL.md): the entrypoints and which one each export lives on
119
+ - [push-notifications/SKILL.md](../push-notifications/SKILL.md): push notifications, which share the same service worker