@softr/sdk 1.17.0-alpha.4 → 1.17.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.
Files changed (44) hide show
  1. package/CHANGELOG.md +20 -0
  2. package/dist/auth/isomorphic.d.ts +6 -6
  3. package/dist/auth/isomorphic.js +3 -1
  4. package/dist/auth/methods/authenticator.js +8 -1
  5. package/dist/auth/methods/code.js +5 -1
  6. package/dist/auth/methods/emailCode2fa.js +4 -1
  7. package/dist/auth/methods/magicLink.js +4 -1
  8. package/dist/auth/methods/password.js +3 -1
  9. package/dist/auth/methods/passwordLink.js +5 -1
  10. package/dist/auth/methods/signup.js +7 -1
  11. package/dist/auth/methods/social.js +4 -5
  12. package/dist/auth/methods/utils.d.ts +4 -1
  13. package/dist/auth/methods/utils.js +30 -1
  14. package/dist/auth/sso.js +2 -1
  15. package/dist/datasource/chart.js +5 -0
  16. package/dist/datasource/record.js +1 -0
  17. package/dist/default-error-overlay.d.ts +2 -2
  18. package/dist/mcp.d.ts +2 -2
  19. package/dist/offline.d.ts +6 -2
  20. package/dist/offline.js +57 -45
  21. package/dist/package.js +1 -1
  22. package/dist/pwa.d.ts +2 -2
  23. package/dist/service-worker.js +70 -11
  24. package/dist/tool.d.ts +7 -2
  25. package/dist/tool.js +1 -0
  26. package/package.json +1 -1
  27. package/skills/softr-sdk/SKILL.md +1 -1
  28. package/skills/softr-sdk/ai/SKILL.md +1 -1
  29. package/skills/softr-sdk/auth/SKILL.md +4 -3
  30. package/skills/softr-sdk/charts-and-metrics/SKILL.md +3 -1
  31. package/skills/softr-sdk/current-user/SKILL.md +1 -1
  32. package/skills/softr-sdk/email/SKILL.md +1 -1
  33. package/skills/softr-sdk/file-uploads/SKILL.md +1 -1
  34. package/skills/softr-sdk/formatting/SKILL.md +1 -1
  35. package/skills/softr-sdk/integrations/SKILL.md +1 -1
  36. package/skills/softr-sdk/mcp/SKILL.md +26 -12
  37. package/skills/softr-sdk/offline/SKILL.md +7 -8
  38. package/skills/softr-sdk/push-notifications/SKILL.md +1 -1
  39. package/skills/softr-sdk/pwa/SKILL.md +1 -1
  40. package/skills/softr-sdk/record-mutations/SKILL.md +1 -1
  41. package/skills/softr-sdk/record-queries/SKILL.md +21 -1
  42. package/skills/softr-sdk/region-visibility/SKILL.md +1 -1
  43. package/skills/softr-sdk/routes-and-visibility/SKILL.md +1 -1
  44. package/skills/softr-sdk/workflows/SKILL.md +1 -1
package/CHANGELOG.md CHANGED
@@ -1,11 +1,31 @@
1
1
  # @softr/sdk
2
2
 
3
+ ## 1.17.0
4
+
5
+ ### Minor Changes
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
+ - `auth.sendSignInCode`, `auth.signInWithCode`, and `auth.signUp` and `auth.confirmSignUp` without a password fail as `notEnabled` when the plan of the app's workspace does not include one-time email codes, as after a downgrade. Before, these calls worked on every plan. Action: on the login and sign-up pages, give `notEnabled` its own `case`, say this way to sign in is not available, and offer the other ways in.
9
+ - New error code `secondFactorNotEnabled`: the visitor owes a second step that the plan of the app's workspace does not include, as after a downgrade. Every call that signs a visitor in answers it in an app that asks that visitor for an authenticator step, and so does `auth.startAuthenticatorSetup`. `auth.signIn`, `auth.verifyEmailCode` and `auth.resendEmailCode` answer it in an app that asks for an emailed code after the password. Before, these calls worked on every plan. Action: give `secondFactorNotEnabled` its own `case` on the pages that sign a visitor in and on the page that sets up an authenticator. Say sign-in is not available on the app's plan and the app owner can fix it. Do not offer another way to sign in, because no way works.
10
+
3
11
  ## 1.16.0
4
12
 
5
13
  ### Minor Changes
6
14
 
7
15
  - 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
16
 
17
+ ## 1.15.4
18
+
19
+ ### Patch Changes
20
+
21
+ - 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.
22
+
23
+ ## 1.15.3
24
+
25
+ ### Patch Changes
26
+
27
+ - A `ds.get`, `ds.chart` or `ds.metric` builder reads again after a call such as `where` changes it, the same as `ds.list` and `ds.export`. Before, it answered the result of its first read and left out the new filter. Skills: record-queries and charts-and-metrics say that one builder is for one read, because `where` and `orderBy` add to the builder they are called on. No action is needed.
28
+
9
29
  ## 1.15.2
10
30
 
11
31
  ### Patch Changes
@@ -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 react7 from "react";
4
+ import * as react0 from "react";
5
5
  import { ReactNode } from "react";
6
- import * as _tanstack_react_start3 from "@tanstack/react-start";
6
+ import * as _tanstack_react_start0 from "@tanstack/react-start";
7
7
 
8
8
  //#region src/auth/isomorphic.d.ts
9
9
 
@@ -21,7 +21,7 @@ import * as _tanstack_react_start3 from "@tanstack/react-start";
21
21
  * requestMiddleware: [softrAuthMiddleware()],
22
22
  * }))
23
23
  */
24
- declare function softrAuthMiddleware(): _tanstack_react_start3.RequestMiddlewareAfterServer<{}, readonly [_tanstack_react_start3.RequestMiddlewareAfterServer<{}, undefined, undefined>, _tanstack_react_start3.RequestMiddlewareAfterServer<{}, undefined, undefined>, _tanstack_react_start3.RequestMiddlewareAfterServer<{}, undefined, undefined>, _tanstack_react_start3.RequestMiddlewareAfterServer<{}, undefined, undefined>, _tanstack_react_start3.RequestMiddlewareAfterServer<{}, undefined, undefined>, _tanstack_react_start3.RequestMiddlewareAfterServer<{}, undefined, undefined>, _tanstack_react_start3.RequestMiddlewareAfterServer<{}, undefined, undefined>, _tanstack_react_start3.RequestMiddlewareAfterServer<{}, undefined, undefined>], {
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>], {
25
25
  user: User | null;
26
26
  permissions: {
27
27
  datasources: {};
@@ -37,7 +37,7 @@ declare function softrAuthMiddleware(): _tanstack_react_start3.RequestMiddleware
37
37
  * beforeLoad: async () => await getSoftrContext(),
38
38
  * })
39
39
  */
40
- declare const getSoftrContext: _tanstack_react_start3.OptionalFetcher<undefined, undefined, Promise<SoftrContext>>;
40
+ declare const getSoftrContext: _tanstack_react_start0.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_start3.OptionalFetcher<undefined, undefined, Promise<AuthOptions>>;
95
+ declare const getAuthSettings: _tanstack_react_start0.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
- }): react7.JSX.Element;
115
+ }): react0.JSX.Element;
116
116
  /**
117
117
  * Which ways in this app offers. Requires an {@link AuthSettingsProvider}
118
118
  * above it.
@@ -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 } from "./utils.js";
6
+ import { authError, isAuthenticatorNotInPlan, isUserLimitReached } from "./utils.js";
7
7
 
8
8
  //#region src/auth/methods/authenticator.ts
9
9
  /**
@@ -22,6 +22,7 @@ async function startAuthenticatorSetup() {
22
22
  assertCanChange("auth.startAuthenticatorSetup");
23
23
  const result = await makePlatform(sessionConfig().applicationId).authenticatorSetupInit(readPendingAuthToken() ?? readSessionToken());
24
24
  if (!result.ok) {
25
+ if (isAuthenticatorNotInPlan(result)) return authError("secondFactorNotEnabled", result.message);
25
26
  if (result.status === 401) return authError("notAuthenticated", result.message);
26
27
  if (result.status === 429) return authError("tooManyAttempts", result.message);
27
28
  if (result.status >= 500) panic(`Expected authenticator setup to start, but got ${result.status}: ` + result.message);
@@ -42,6 +43,8 @@ async function confirmAuthenticatorSetup(details) {
42
43
  assertCanChange("auth.confirmAuthenticatorSetup");
43
44
  const result = await makePlatform(sessionConfig().applicationId).authenticatorSetupComplete(readPendingAuthToken() ?? readSessionToken(), details.code);
44
45
  if (!result.ok) {
46
+ if (isUserLimitReached(result)) return authError("userLimitReached", result.message);
47
+ if (isAuthenticatorNotInPlan(result)) return authError("secondFactorNotEnabled", result.message);
45
48
  if (result.status === 400 || result.status === 401) return authError("invalidCode", result.message);
46
49
  if (result.status === 429) return authError("tooManyAttempts", result.message);
47
50
  if (result.status >= 500) panic(`Expected authenticator setup to finish, but got ${result.status}: ` + result.message);
@@ -68,6 +71,8 @@ async function skipAuthenticatorSetup() {
68
71
  assertCanChange("auth.skipAuthenticatorSetup");
69
72
  const result = await makePlatform(sessionConfig().applicationId).authenticatorSetupDismiss(readPendingAuthToken() ?? readSessionToken());
70
73
  if (!result.ok) {
74
+ if (isUserLimitReached(result)) return authError("userLimitReached", result.message);
75
+ if (isAuthenticatorNotInPlan(result)) return authError("secondFactorNotEnabled", result.message);
71
76
  if (result.status === 401) return authError("notAuthenticated", result.message);
72
77
  if (result.status === 429) return authError("tooManyAttempts", result.message);
73
78
  if (result.status >= 500) panic(`Expected to skip authenticator setup, but got ${result.status}: ` + result.message);
@@ -92,6 +97,8 @@ async function verifyAuthenticator(credentials) {
92
97
  assertCanChange("auth.verifyAuthenticator");
93
98
  const result = await makePlatform(sessionConfig().applicationId).authenticatorVerify(readPendingAuthToken() ?? readSessionToken(), "code" in credentials ? { totpCode: credentials.code } : { backupCode: credentials.backupCode });
94
99
  if (!result.ok) {
100
+ if (isUserLimitReached(result)) return authError("userLimitReached", result.message);
101
+ if (isAuthenticatorNotInPlan(result)) return authError("secondFactorNotEnabled", result.message);
95
102
  if (result.status === 400 || result.status === 401) return authError("invalidCode", result.message);
96
103
  if (result.status === 429) return authError("tooManyAttempts", result.message);
97
104
  if (result.status >= 500) panic(`Expected to verify the authenticator, 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 } from "./utils.js";
6
+ import { authError, isAuthenticatorNotInPlan, isNotInPlan, isUserLimitReached } 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"]]);
@@ -18,6 +18,7 @@ async function sendSignInCode(details) {
18
18
  assertCanChange("auth.sendSignInCode");
19
19
  const result = await makePlatform(sessionConfig().applicationId).sendSignInCode(details.email);
20
20
  if (!result.ok) {
21
+ if (isNotInPlan(result)) return authError("notEnabled", result.message);
21
22
  if (result.status === 429) return authError("tooManyAttempts", result.message);
22
23
  if (result.status === 400) return authError(SEND_CODE_ERRORS.get(result.message) ?? "invalidDetails", result.message);
23
24
  if (result.status >= 500) panic(`Expected the sign-in code to be emailed, but got ${result.status}: ` + result.message);
@@ -39,6 +40,9 @@ async function signInWithCode(credentials) {
39
40
  assertCanChange("auth.signInWithCode");
40
41
  const result = await makePlatform(sessionConfig().applicationId).signInWithCode(credentials);
41
42
  if (!result.ok) {
43
+ if (isUserLimitReached(result)) return authError("userLimitReached", result.message);
44
+ if (isAuthenticatorNotInPlan(result)) return authError("secondFactorNotEnabled", result.message);
45
+ if (isNotInPlan(result)) return authError("notEnabled", result.message);
42
46
  if (result.status === 429) return authError("tooManyAttempts", result.message);
43
47
  if (result.status === 400 || result.status === 401) return authError("invalidCode", result.message);
44
48
  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 } from "./utils.js";
6
+ import { authError, isAuthenticatorNotInPlan, isNotInPlan, isUserLimitReached } from "./utils.js";
7
7
 
8
8
  //#region src/auth/methods/emailCode2fa.ts
9
9
  /**
@@ -18,6 +18,8 @@ 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 (isAuthenticatorNotInPlan(result) || isNotInPlan(result)) return authError("secondFactorNotEnabled", result.message);
21
23
  if (result.status === 400 || result.status === 401) return authError("invalidCode", result.message);
22
24
  if (result.status === 429) return authError("tooManyAttempts", result.message);
23
25
  if (result.status >= 500) panic(`Expected to verify the emailed code, but got ${result.status}: ` + result.message);
@@ -55,6 +57,7 @@ async function resendEmailCode() {
55
57
  assertCanChange("auth.resendEmailCode");
56
58
  const result = await makePlatform(sessionConfig().applicationId).emailCodeResend(readPendingAuthToken());
57
59
  if (!result.ok) {
60
+ if (isAuthenticatorNotInPlan(result) || isNotInPlan(result)) return authError("secondFactorNotEnabled", result.message);
58
61
  if (result.status === 401) return authError("notAuthenticated", result.message);
59
62
  if (result.status === 429) return authError("tooManyAttempts", result.message);
60
63
  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 } from "./utils.js";
6
+ import { authError, isAuthenticatorNotInPlan, isNotInPlan, isUserLimitReached } from "./utils.js";
7
7
 
8
8
  //#region src/auth/methods/magicLink.ts
9
9
  /**
@@ -18,6 +18,9 @@ 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 (isAuthenticatorNotInPlan(result)) return authError("secondFactorNotEnabled", result.message);
23
+ if (isNotInPlan(result)) return authError("notEnabled", result.message);
21
24
  if (result.status === 429) return authError("tooManyAttempts", result.message);
22
25
  if (result.status === 400 || result.status === 401) return authError("invalidCredentials", result.message);
23
26
  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 } from "./utils.js";
6
+ import { authError, isAuthenticatorNotInPlan, isNotInPlan, isUserLimitReached } from "./utils.js";
7
7
 
8
8
  //#region src/auth/methods/password.ts
9
9
  /**
@@ -18,6 +18,8 @@ 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 (isAuthenticatorNotInPlan(result) || isNotInPlan(result)) return authError("secondFactorNotEnabled", result.message);
21
23
  if (result.status === 401) return authError("invalidCredentials", result.message);
22
24
  if (result.status === 429) return authError("tooManyAttempts", result.message);
23
25
  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 } from "./utils.js";
6
+ import { authError, isAuthenticatorNotInPlan, isNotInPlan, isUserLimitReached } from "./utils.js";
7
7
 
8
8
  //#region src/auth/methods/passwordLink.ts
9
9
  /**
@@ -31,6 +31,7 @@ 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);
34
35
  if (result.status === 429) return authError("tooManyAttempts", result.message);
35
36
  if (result.status === 400 || result.status === 401) return authError("linkExpired", result.message);
36
37
  panic(`Expected the link to be checked, but got ${result.status}: ${result.message}.`);
@@ -51,6 +52,9 @@ async function setPasswordWithLink(details) {
51
52
  assertCanChange("auth.setPasswordWithLink");
52
53
  const result = await makePlatform(sessionConfig().applicationId).setPassword(details);
53
54
  if (!result.ok) {
55
+ if (isUserLimitReached(result)) return authError("userLimitReached", result.message);
56
+ if (isAuthenticatorNotInPlan(result)) return authError("secondFactorNotEnabled", result.message);
57
+ if (isNotInPlan(result)) return authError("notEnabled", result.message);
54
58
  if (result.status === 429) return authError("tooManyAttempts", result.message);
55
59
  if (result.status === 400 && result.message.startsWith("Password must be at least")) return authError("invalidDetails", result.message);
56
60
  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 } from "./utils.js";
6
+ import { authError, isAuthenticatorNotInPlan, isNotInPlan, isUserLimitReached } from "./utils.js";
7
7
 
8
8
  //#region src/auth/methods/signup.ts
9
9
  /**
@@ -15,6 +15,9 @@ 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 (isAuthenticatorNotInPlan(result)) return authError("secondFactorNotEnabled", result.message);
20
+ if (isNotInPlan(result)) return authError("notEnabled", result.message);
18
21
  if (result.status === 409) return authError("emailTaken", result.message);
19
22
  if (result.status === 429) return authError("tooManyAttempts", result.message);
20
23
  if (result.status === 400) return authError("invalidDetails", result.message);
@@ -48,6 +51,9 @@ async function confirmSignUp(details) {
48
51
  password
49
52
  });
50
53
  if (!result.ok) {
54
+ if (isUserLimitReached(result)) return authError("userLimitReached", result.message);
55
+ if (isAuthenticatorNotInPlan(result)) return authError("secondFactorNotEnabled", result.message);
56
+ if (isNotInPlan(result)) return authError("notEnabled", result.message);
51
57
  if (result.status === 409) return authError("emailTaken", result.message);
52
58
  if (result.status === 429) return authError("tooManyAttempts", result.message);
53
59
  if (result.status === 400 && result.message.startsWith("Password must be at least")) return authError("invalidDetails", result.message);
@@ -3,11 +3,9 @@ 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 } from "./utils.js";
7
- import { z } from "zod";
6
+ import { authError, isAuthenticatorNotInPlan, isNotInPlan, isUserLimitReached } from "./utils.js";
8
7
 
9
8
  //#region src/auth/methods/social.ts
10
- const errorBodySchema = z.object({ code: z.string() });
11
9
  /**
12
10
  * Signs a visitor in with a Google token the browser obtained, creating their
13
11
  * account the first time.
@@ -27,9 +25,10 @@ async function signInWithGoogle(credentials) {
27
25
  assertCanChange("auth.signInWithGoogle");
28
26
  const result = await makePlatform(sessionConfig().applicationId).signInWithGoogle(credentials);
29
27
  if (!result.ok) {
28
+ if (isUserLimitReached(result)) return authError("userLimitReached", result.message);
29
+ if (isAuthenticatorNotInPlan(result)) return authError("secondFactorNotEnabled", result.message);
30
+ if (isNotInPlan(result)) return authError("notEnabled", result.message);
30
31
  if (result.status === 429) return authError("tooManyAttempts", result.message);
31
- const body = errorBodySchema.safeParse(result.body);
32
- if (body.success && body.data.code === "GOOGLE_NOT_IN_PLAN") return authError("notEnabled", result.message);
33
32
  if (result.status === 400 && result.message.startsWith("Emails with ") && result.message.endsWith(" domain is not allowed to signup.")) return authError("emailDomainNotAllowed", result.message);
34
33
  if (result.status === 400 || result.status === 401) return authError("invalidCredentials", result.message);
35
34
  if (result.status >= 500) panic(`Expected Google sign-in to succeed, but got ${result.status}: ` + result.message);
@@ -10,6 +10,9 @@ type AuthError = {
10
10
  code: AuthErrorCode;
11
11
  message: string;
12
12
  };
13
- type AuthErrorCode = "invalidCredentials" | "tooManyAttempts" | "emailTaken" | "invalidDetails" | "invalidCode" | "noAccount" | "accountDeactivated" | "notAuthenticated" | "emailDomainNotAllowed" | "notEnabled" | "linkExpired" | "invalidName" | "invalidPhoto" | "fileTooLarge" | "notAnImage" | "avatarNotSupported";
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. Another way in can still work. */ | "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"
16
+ /** The visitor owes a second step that the plan of the app's workspace no longer includes. No way in works until the app owner changes the plan. */ | "secondFactorNotEnabled";
14
17
  //#endregion
15
18
  export { AuthError, Result };
@@ -1,3 +1,5 @@
1
+ import { z } from "zod";
2
+
1
3
  //#region src/auth/methods/utils.ts
2
4
  function authError(code, message) {
3
5
  return {
@@ -8,6 +10,33 @@ function authError(code, message) {
8
10
  }
9
11
  };
10
12
  }
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 this way to sign in: Google sign-in or the one-time email code, as
26
+ * after a downgrade.
27
+ */
28
+ function isNotInPlan(result) {
29
+ const body = errorBodySchema.safeParse(result.body);
30
+ return body.success && (body.data.code === "GOOGLE_NOT_IN_PLAN" || body.data.code === "EMAIL_CODE_NOT_IN_PLAN");
31
+ }
32
+ /**
33
+ * True when Softr refused because the visitor owes an authenticator app step
34
+ * that the plan of the app's workspace does not include, as after a downgrade.
35
+ */
36
+ function isAuthenticatorNotInPlan(result) {
37
+ const body = errorBodySchema.safeParse(result.body);
38
+ return body.success && body.data.code === "AUTHENTICATOR_NOT_IN_PLAN";
39
+ }
11
40
 
12
41
  //#endregion
13
- export { authError };
42
+ export { authError, isAuthenticatorNotInPlan, isNotInPlan, isUserLimitReached };
package/dist/auth/sso.js CHANGED
@@ -145,7 +145,8 @@ 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": return { error: "not-enabled" };
148
+ case "SSO_MISCONFIGURED":
149
+ case "AUTHENTICATOR_NOT_IN_PLAN": return { error: "not-enabled" };
149
150
  case "SSO_SIGN_UP_DISABLED": return { error: "sign-up-disabled" };
150
151
  case "USER_DEACTIVATED":
151
152
  case "SIGN_IN_RESTRICTED": return { error: "restricted" };
@@ -100,6 +100,7 @@ function chart(query) {
100
100
  const groups = entries;
101
101
  assert(groups.length < 2 || groups[0][1].fieldId !== groups[1][1].fieldId, "a chart may group by a field only once");
102
102
  state.groups = groups;
103
+ result = void 0;
103
104
  return builder;
104
105
  },
105
106
  metrics(build) {
@@ -114,15 +115,18 @@ function chart(query) {
114
115
  seen.add(pair);
115
116
  }
116
117
  state.metrics = metrics;
118
+ result = void 0;
117
119
  return builder;
118
120
  },
119
121
  where(build) {
120
122
  state.filters.push(build(makeFieldSet(aliases)));
123
+ result = void 0;
121
124
  return builder;
122
125
  },
123
126
  orderBy(build) {
124
127
  const sorting = build(makeSortSet([...state.groups ?? [], ...state.metrics ?? []].map(([key]) => key)));
125
128
  state.orderBys.push(...buildOrderBy(Array.isArray(sorting) ? sorting : [sorting]));
129
+ result = void 0;
126
130
  return builder;
127
131
  },
128
132
  then(onfulfilled, onrejected) {
@@ -238,6 +242,7 @@ function metric(query, pick) {
238
242
  [Symbol.toStringTag]: "MetricQuery",
239
243
  where(build) {
240
244
  filters.push(build(makeFieldSet(aliases)));
245
+ result = void 0;
241
246
  return builder;
242
247
  },
243
248
  then(onfulfilled, onrejected) {
@@ -228,6 +228,7 @@ function getRecord(query, options) {
228
228
  [Symbol.toStringTag]: "RecordFetch",
229
229
  where(build) {
230
230
  filters.push(build(makeFieldSet(aliases)));
231
+ record = void 0;
231
232
  return builder;
232
233
  },
233
234
  then(onfulfilled, onrejected) {
@@ -1,4 +1,4 @@
1
- import * as react6 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): react6.JSX.Element;
11
+ }: Props): react7.JSX.Element;
12
12
  //#endregion
13
13
  export { DefaultErrorOverlay };
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_start0 from "@tanstack/react-start";
3
+ import * as _tanstack_react_start11 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_start0.RequestMiddlewareAfterServer<{}, undefined, undefined>;
41
+ declare function softrMcpMiddleware(options?: SoftrMcpOptions): _tanstack_react_start11.RequestMiddlewareAfterServer<{}, undefined, undefined>;
42
42
  //#endregion
43
43
  export { softrMcpMiddleware };
package/dist/offline.d.ts CHANGED
@@ -1,13 +1,17 @@
1
1
  //#region src/offline.d.ts
2
2
  type OfflineMode = {
3
- /** `false` while the browser has no connection. Always `true` during server rendering. */
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
+ */
4
7
  online: boolean;
5
8
  };
6
9
  type OfflineModeOptions = {
7
10
  /**
8
11
  * `false` turns offline mode off and deletes what this browser kept. Keep the
9
12
  * call with `false` rather than removing it: browsers that ran offline mode
10
- * before keep their copies until this runs. Defaults to `true`.
13
+ * before keep the visitor's copies, and keep saving new ones, until this runs
14
+ * or the visitor signs out. Defaults to `true`.
11
15
  */
12
16
  enabled?: boolean;
13
17
  };
package/dist/offline.js CHANGED
@@ -1,10 +1,10 @@
1
- import { OFFLINE_CACHE, OFFLINE_DATA_CACHE, OFFLINE_OWNER_KEY, OFFLINE_SKIPPED_PREFIXES, WORKER_PATH } from "./service-worker.js";
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
2
  import { useCurrentUser } from "./auth/isomorphic.js";
3
- import { useEffect, useSyncExternalStore } from "react";
3
+ import { useEffect, useState, useSyncExternalStore } from "react";
4
4
  import { useLocation } from "@tanstack/react-router";
5
5
 
6
6
  //#region src/offline.ts
7
- const PAGE_MAX_AGE_MS = 5 * 6e4;
7
+ const PAGE_MAX_AGE_MS = 30 * 6e4;
8
8
  /**
9
9
  * Lets the published app open without internet and show the pages and data
10
10
  * the visitor loaded, read only. Saves made offline fail as usual.
@@ -23,63 +23,75 @@ const PAGE_MAX_AGE_MS = 5 * 6e4;
23
23
  function useOfflineMode(options = {}) {
24
24
  const enabled = options.enabled ?? true;
25
25
  const userId = useCurrentUser()?.id ?? null;
26
- const href = useLocation({ select: (location$1) => location$1.href });
27
- const online = useSyncExternalStore(subscribeToConnection, () => navigator.onLine, () => true);
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
+ }, []);
28
51
  useEffect(() => {
29
52
  if (process.env.NODE_ENV !== "production" || !("serviceWorker" in navigator) || !("caches" in window)) return;
30
53
  if (!enabled) {
31
- Promise.all([caches.delete(OFFLINE_CACHE), caches.delete(OFFLINE_DATA_CACHE)]).catch(() => {});
54
+ deleteCopies().catch(() => {});
32
55
  return;
33
56
  }
57
+ if (!connected || showingCopies) return;
34
58
  (async () => {
35
- await keepCopiesOnlyFor(userId ?? "");
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
+ }
36
65
  await navigator.serviceWorker.register(WORKER_PATH, { scope: "/" });
37
- if (!navigator.onLine) return;
38
66
  const cache = await caches.open(OFFLINE_CACHE);
39
- await savePage(cache, href);
40
- await saveLoadedFiles(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
+ }));
41
83
  })().catch((error) => console.warn("[@softr/sdk] Offline mode could not save this page:", error));
42
84
  }, [
43
85
  enabled,
44
86
  userId,
45
- href
87
+ pathname,
88
+ connected,
89
+ showingCopies
46
90
  ]);
47
- return { online };
91
+ return { online: connected && !showingCopies };
48
92
  }
49
- /** Deletes the copies when they belong to someone else, then marks them as this visitor's. */
50
- async function keepCopiesOnlyFor(owner) {
51
- const stored = await (await caches.open(OFFLINE_CACHE)).match(OFFLINE_OWNER_KEY);
52
- if (stored !== void 0 && await stored.text() === owner) return;
93
+ async function deleteCopies() {
53
94
  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(() => {})));
83
95
  }
84
96
  function subscribeToConnection(onChange) {
85
97
  window.addEventListener("online", onChange);
package/dist/package.js CHANGED
@@ -1,5 +1,5 @@
1
1
  //#region package.json
2
- var version = "1.17.0-alpha.4";
2
+ var version = "1.17.0";
3
3
 
4
4
  //#endregion
5
5
  export { version };
package/dist/pwa.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import * as react4 from "react";
1
+ import * as react5 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(): react4.FunctionComponentElement<react4.FragmentProps>;
27
+ declare function SoftrPwaHead(): react5.FunctionComponentElement<react5.FragmentProps>;
28
28
  type PwaPlatform = "ios" | "android" | "desktop";
29
29
  type InstallChoice = "accepted" | "dismissed";
30
30
  type PwaInstall = {
@@ -1,11 +1,20 @@
1
1
  //#region src/service-worker.ts
2
2
  const WORKER_PATH = "/_softr/sw.js";
3
- /** Pages, scripts, styles and images. Its presence is what turns offline mode on. */
3
+ /** Pages, scripts, styles and images. Its owner entry is what turns offline mode on. */
4
4
  const OFFLINE_CACHE = "softr-offline-v1";
5
5
  /** Answers to the app's data calls, kept apart so a long session of them never pushes out the pages. */
6
6
  const OFFLINE_DATA_CACHE = "softr-offline-data-v1";
7
7
  /** Whose copies the offline cache holds: the user id, or empty for a signed-out visitor. */
8
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";
9
18
  /** Paths offline mode never keeps: the SDK's own routes and the canvas engine's. */
10
19
  const OFFLINE_SKIPPED_PREFIXES = ["/_softr/", "/.softr/"];
11
20
  const MAX_COPIES = 300;
@@ -14,19 +23,51 @@ const MAX_COPIES = 300;
14
23
  * network first, and the last good answer is kept on the device for when the
15
24
  * network fails. Writes and live streams are never kept.
16
25
  *
17
- * It does nothing until `useOfflineMode()` creates the cache, so an app that
18
- * registers the worker only for push keeps working as before.
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.
19
28
  */
20
29
  const OFFLINE_WORKER = `
21
30
  // Offline mode, added by @softr/sdk.
22
31
  const SOFTR_OFFLINE_CACHE = ${JSON.stringify(OFFLINE_CACHE)};
23
32
  const SOFTR_OFFLINE_DATA_CACHE = ${JSON.stringify(OFFLINE_DATA_CACHE)};
24
33
  const SOFTR_OFFLINE_OWNER_KEY = ${JSON.stringify(OFFLINE_OWNER_KEY)};
34
+ const SOFTR_OFFLINE_SAVE_HEADER = ${JSON.stringify(OFFLINE_SAVE_HEADER)};
25
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
+ });
26
53
 
27
- async function softrKeepCopy(cacheName, request, response) {
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;
28
69
  const cache = await caches.open(cacheName);
29
- await cache.put(request, response);
70
+ await cache.put(key, response);
30
71
  const keys = (await cache.keys()).filter((key) => new URL(key.url).pathname !== SOFTR_OFFLINE_OWNER_KEY);
31
72
  await Promise.all(keys.slice(0, Math.max(0, keys.length - ${MAX_COPIES})).map((key) => cache.delete(key)));
32
73
  }
@@ -37,20 +78,38 @@ self.addEventListener('fetch', (event) => {
37
78
  const url = new URL(request.url);
38
79
  if (url.origin !== self.location.origin) return;
39
80
  if (SOFTR_OFFLINE_SKIPPED.some((prefix) => url.pathname.startsWith(prefix))) return;
81
+ if (request.headers.has(SOFTR_OFFLINE_SAVE_HEADER)) return;
40
82
  event.respondWith((async () => {
41
- if (!(await caches.has(SOFTR_OFFLINE_CACHE))) return fetch(request);
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();
42
88
  // A data call from the app's code has no destination; a page or a file has one.
43
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;
44
93
  try {
45
- const response = await fetch(request);
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
+ }
46
102
  const streamed = (response.headers.get('content-type') || '').startsWith('text/event-stream');
47
103
  if (response.status === 200 && response.type === 'basic' && !streamed) {
48
- event.waitUntil(softrKeepCopy(cacheName, request, response.clone()).catch(() => {}));
104
+ event.waitUntil(softrKeepCopy(owner, cacheName, key, response.clone()).catch(() => {}));
49
105
  }
50
106
  return response;
51
107
  } catch (error) {
52
- const copy = await caches.match(request, { cacheName });
53
- if (copy) return copy;
108
+ const copy = await caches.match(key, { cacheName });
109
+ if (copy) {
110
+ softrSetShowingCopies(true);
111
+ return copy;
112
+ }
54
113
  throw error;
55
114
  }
56
115
  })());
@@ -58,4 +117,4 @@ self.addEventListener('fetch', (event) => {
58
117
  `;
59
118
 
60
119
  //#endregion
61
- export { OFFLINE_CACHE, OFFLINE_DATA_CACHE, OFFLINE_OWNER_KEY, OFFLINE_SKIPPED_PREFIXES, OFFLINE_WORKER, WORKER_PATH };
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.17.0-alpha.4",
3
+ "version": "1.17.0",
4
4
  "type": "module",
5
5
  "exports": {
6
6
  ".": { "types": "./dist/index.d.ts", "import": "./dist/index.js" },
@@ -11,7 +11,7 @@ description: >-
11
11
  metadata:
12
12
  type: core
13
13
  library: softr-sdk
14
- library_version: 1.16.0
14
+ library_version: 1.17.0
15
15
  ---
16
16
 
17
17
  # Softr SDK core
@@ -13,7 +13,7 @@ description: >-
13
13
  metadata:
14
14
  type: sub-skill
15
15
  library: softr-sdk
16
- library_version: 1.16.0
16
+ library_version: 1.17.0
17
17
  ---
18
18
 
19
19
  **Boundary.** `ai` lives on `@softr/sdk/server` and runs only inside a `createServerFn` handler — importing it into a component fails the build. `defineAiAction` and every type come from `@softr/sdk` and can be imported anywhere.
@@ -10,7 +10,7 @@ description: >-
10
10
  metadata:
11
11
  type: sub-skill
12
12
  library: softr-sdk
13
- library_version: 1.16.0
13
+ library_version: 1.17.0
14
14
  ---
15
15
 
16
16
  **Boundary.** `auth` lives on `@softr/sdk/server` and runs only inside a `createServerFn` handler — importing it into a component fails the build.
@@ -134,10 +134,11 @@ 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' // signInWithGoogle: the app's plan no longer includes Google sign-in
137
+ | 'notEnabled' | 'secondFactorNotEnabled' // the app's plan no longer includes this way in (Google, an emailed code), or the second step this visitor owes (an emailed code after the password, 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
138
139
  ```
139
140
 
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.
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. Do the same for `secondFactorNotEnabled`: no other way to sign in works for this visitor, so do not offer one. Say that sign-in is not available on the app's plan and that the app owner can fix it.
141
142
 
142
143
  `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.
143
144
 
@@ -10,7 +10,7 @@ description: >-
10
10
  metadata:
11
11
  type: sub-skill
12
12
  library: softr-sdk
13
- library_version: 1.16.0
13
+ library_version: 1.17.0
14
14
  ---
15
15
 
16
16
  **Boundary.** `ds` lives on `@softr/sdk/server` and runs only inside a `createServerFn` handler — importing it into a component fails the build. A helper that calls `ds` outside a handler goes in `createServerOnlyFn` from `@tanstack/react-start` (the `record-queries` boundary). `defineQuery` and every type come from `@softr/sdk` and can be imported anywhere.
@@ -195,6 +195,8 @@ A chart can group, aggregate and `where` only on `fields`, not on `filterFields`
195
195
 
196
196
  `groupBy` comes first and exactly once; a chart cannot be awaited before it. `metrics` follows, at most once, or not at all for distinct values. `where` can be chained anywhere, repeatedly, and calling it more than once ands the filters together. `orderBy` sorts by the chart's own keys, group and metric alike, and only sees the keys declared so far, so call it last.
197
197
 
198
+ A builder is for one read. `where` adds to the builder it is called on, so a `ds.chart` or `ds.metric` kept in a variable and read again carries the filters of the earlier read. Start each figure from its own `ds.chart` or `ds.metric`, as the dashboard load above does.
199
+
198
200
  ## References
199
201
 
200
202
  - [references/aggregations.md](./references/aggregations.md): every bucket interval and its value type, and which aggregations each kind of field offers. Load it when choosing a bucket or when a field does not offer the aggregation you expected.
@@ -11,7 +11,7 @@ description: >-
11
11
  metadata:
12
12
  type: sub-skill
13
13
  library: softr-sdk
14
- library_version: 1.16.0
14
+ library_version: 1.17.0
15
15
  ---
16
16
 
17
17
  # The current user
@@ -12,7 +12,7 @@ description: >-
12
12
  metadata:
13
13
  type: sub-skill
14
14
  library: softr-sdk
15
- library_version: 1.16.0
15
+ library_version: 1.17.0
16
16
  ---
17
17
 
18
18
  **Boundary.** `email` and `EmailError` live on `@softr/sdk/server` and run only inside a `createServerFn` handler — importing them into a component fails the build. `defineEmailAction` and every type come from `@softr/sdk` and can be imported anywhere.
@@ -7,7 +7,7 @@ description: >-
7
7
  metadata:
8
8
  type: sub-skill
9
9
  library: softr-sdk
10
- library_version: 1.16.0
10
+ library_version: 1.17.0
11
11
  ---
12
12
 
13
13
  **Boundary.** `upload` lives on `@softr/sdk/server` and runs inside server functions. `useFileUpload` and `FileItem` live on `@softr/sdk` and run in components. `FileAttachment` comes from `@softr/sdk` and can be imported anywhere.
@@ -8,7 +8,7 @@ description: >-
8
8
  metadata:
9
9
  type: sub-skill
10
10
  library: softr-sdk
11
- library_version: 1.16.0
11
+ library_version: 1.17.0
12
12
  ---
13
13
 
14
14
  # Dates, times and numbers
@@ -7,7 +7,7 @@ description: >-
7
7
  metadata:
8
8
  type: sub-skill
9
9
  library: softr-sdk
10
- library_version: 1.16.0
10
+ library_version: 1.17.0
11
11
  ---
12
12
 
13
13
  **Boundary.** `integration` lives on `@softr/sdk/server` and runs only inside a `createServerFn` handler — importing it into a component fails the build. `defineIntegration` and every type come from `@softr/sdk` and can be imported anywhere.
@@ -11,10 +11,10 @@ description: >-
11
11
  metadata:
12
12
  type: sub-skill
13
13
  library: softr-sdk
14
- library_version: 1.16.0
14
+ library_version: 1.17.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.
@@ -4,11 +4,11 @@ description: >-
4
4
  Let the published app open without internet and show the pages and data the
5
5
  visitor last loaded, read only: useOfflineMode, the OfflineMode type, the
6
6
  offline banner and saves made offline. The service worker is already served,
7
- never write one. Saving offline is not built in.
7
+ never write one.
8
8
  metadata:
9
9
  type: sub-skill
10
10
  library: softr-sdk
11
- library_version: 1.16.0
11
+ library_version: 1.17.0
12
12
  ---
13
13
 
14
14
  # Offline mode
@@ -32,7 +32,7 @@ type OfflineModeOptions = {
32
32
  }
33
33
 
34
34
  type OfflineMode = {
35
- online: boolean // false while the browser has no connection; always true during server rendering
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
36
  }
37
37
  ```
38
38
 
@@ -40,7 +40,7 @@ type OfflineMode = {
40
40
 
41
41
  ### Turning it on
42
42
 
43
- Call `useOfflineMode()` once, in `RootDocument` in `src/routes/__root.tsx`, so every page is kept. Render the banner from the same place. Use the banner component the template ships when it has one.
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
44
 
45
45
  ```tsx
46
46
  function OfflineBanner() {
@@ -54,15 +54,14 @@ Offline mode works only on the published app. Inside the Studio preview `online`
54
54
 
55
55
  ### Saves made offline
56
56
 
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:
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
58
 
59
59
  ```tsx
60
60
  import { toast } from 'sonner'
61
61
 
62
62
  // `save` is the form's own server function.
63
- const { online } = useOfflineMode()
64
63
  save(values).catch(() =>
65
- toast.error(online ? 'Could not save your changes.' : "You're offline. Connect to save your changes."),
64
+ toast.error(navigator.onLine ? 'Could not save your changes.' : "You're offline. Connect to save your changes."),
66
65
  )
67
66
  ```
68
67
 
@@ -72,7 +71,7 @@ Nothing to add. The copies kept on the device are deleted when the visitor signs
72
71
 
73
72
  ### Turning it off
74
73
 
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.
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.
76
75
 
77
76
  ## Common Mistakes
78
77
 
@@ -9,7 +9,7 @@ description: >-
9
9
  metadata:
10
10
  type: sub-skill
11
11
  library: softr-sdk
12
- library_version: 1.16.0
12
+ library_version: 1.17.0
13
13
  ---
14
14
 
15
15
  # Push notifications
@@ -10,7 +10,7 @@ description: >-
10
10
  metadata:
11
11
  type: sub-skill
12
12
  library: softr-sdk
13
- library_version: 1.16.0
13
+ library_version: 1.17.0
14
14
  ---
15
15
 
16
16
  # Installing the app
@@ -10,7 +10,7 @@ description: >-
10
10
  metadata:
11
11
  type: sub-skill
12
12
  library: softr-sdk
13
- library_version: 1.16.0
13
+ library_version: 1.17.0
14
14
  ---
15
15
 
16
16
  **Boundary.** `ds` lives on `@softr/sdk/server` and runs only inside a `createServerFn` handler — importing it into a component fails the build. `defineMutation` and every type come from `@softr/sdk` and can be imported anywhere.
@@ -11,7 +11,7 @@ description: >-
11
11
  metadata:
12
12
  type: sub-skill
13
13
  library: softr-sdk
14
- library_version: 1.16.0
14
+ library_version: 1.17.0
15
15
  ---
16
16
 
17
17
  **Boundary.** `ds` lives on `@softr/sdk/server` and runs only inside a `createServerFn` handler — importing it into a component fails the build. A route `loader` also runs in the browser, so it calls a server function, never `ds`. A helper that calls `ds` outside a handler, in this file or in another one, goes in `createServerOnlyFn` from `@tanstack/react-start`, or inside the handler. An exported helper without it keeps the server-only import in the browser bundle, and every page stops loading until it moves. Do not make such a helper a server function when it takes an id: any visitor can call a server function with any id. `defineQuery` and every type come from `@softr/sdk` and can be imported anywhere.
@@ -99,6 +99,26 @@ Calling `.where` more than once ands the filters together, and the query's `filt
99
99
  .orderBy((q) => [q.views.desc, q.title.asc]) // array for tie-breakers
100
100
  ```
101
101
 
102
+ ### One builder, one read
103
+
104
+ `where` and `orderBy` add to the builder they are called on and return that same builder. A builder kept in a variable carries its filters and sorts into every later read, with no error. Start each read from its own `ds.list`, `ds.get` or `ds.export`:
105
+
106
+ ```ts
107
+ // Wrong: the second read asks for open AND closed, and returns no records.
108
+ const list = ds.list(orders)
109
+ const open = await list.where((q) => q.status.is('open'))
110
+ const closed = await list.where((q) => q.status.is('closed'))
111
+
112
+ // Right: one builder for each read.
113
+ const open = await ds.list(orders).where((q) => q.status.is('open'))
114
+ const closed = await ds.list(orders).where((q) => q.status.is('closed'))
115
+ ```
116
+
117
+ - A loop with one filter per pass, such as one count per tab, starts a new builder on each pass.
118
+ - A second `orderBy` on the same builder only breaks the ties of the first.
119
+ - A reused `ds.export` builder writes a file with only the records that match every filter it collected.
120
+ - To add a filter only when an input is set, reassign the builder before its one read: `if (search) list = list.where(...)`, as in [Keep a large table on the server](#keep-a-large-table-on-the-server).
121
+
102
122
  ### Get one record
103
123
 
104
124
  ```ts
@@ -9,7 +9,7 @@ description: >-
9
9
  metadata:
10
10
  type: sub-skill
11
11
  library: softr-sdk
12
- library_version: 1.16.0
12
+ library_version: 1.17.0
13
13
  ---
14
14
 
15
15
  **Boundary.** `Audience` and `defineVisibility` come from `@softr/sdk` and work anywhere.
@@ -9,7 +9,7 @@ description: >-
9
9
  metadata:
10
10
  type: sub-skill
11
11
  library: softr-sdk
12
- library_version: 1.16.0
12
+ library_version: 1.17.0
13
13
  ---
14
14
 
15
15
  **Boundary.** `definePage`, `pageHead`, the access functions and the error predicates come from `@softr/sdk` and work anywhere.
@@ -9,7 +9,7 @@ description: >-
9
9
  metadata:
10
10
  type: sub-skill
11
11
  library: softr-sdk
12
- library_version: 1.16.0
12
+ library_version: 1.17.0
13
13
  ---
14
14
 
15
15
  **Boundary.** `workflow` lives on `@softr/sdk/server` and runs only inside a `createServerFn` handler — importing it into a component fails the build. `defineWorkflow` and every type come from `@softr/sdk` and can be imported anywhere.