@softr/sdk 1.0.1-alpha.0 → 1.1.1-alpha.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 (50) hide show
  1. package/CHANGELOG.md +8 -2
  2. package/dist/action.d.ts +34 -2
  3. package/dist/action.js +9 -2
  4. package/dist/auth/context.js +13 -0
  5. package/dist/auth/isomorphic.d.ts +6 -6
  6. package/dist/auth/isomorphic.js +6 -9
  7. package/dist/auth/methods/authenticator.js +1 -1
  8. package/dist/auth/methods/code.js +1 -1
  9. package/dist/auth/methods/emailCode2fa.js +1 -1
  10. package/dist/auth/methods/magicLink.js +1 -1
  11. package/dist/auth/methods/password.js +1 -1
  12. package/dist/auth/methods/passwordLink.js +1 -1
  13. package/dist/auth/methods/profile.js +1 -1
  14. package/dist/auth/methods/signup.js +1 -1
  15. package/dist/auth/methods/social.js +1 -1
  16. package/dist/auth/session.js +19 -6
  17. package/dist/datasource/chart.d.ts +1 -1
  18. package/dist/datasource/chart.js +27 -19
  19. package/dist/datasource/enforced-filter.d.ts +56 -0
  20. package/dist/datasource/enforced-filter.js +127 -0
  21. package/dist/datasource/fields.d.ts +2 -2
  22. package/dist/datasource/filter.d.ts +9 -2
  23. package/dist/datasource/filter.js +17 -1
  24. package/dist/datasource/record.d.ts +1 -1
  25. package/dist/datasource/record.js +58 -10
  26. package/dist/default-error-overlay.d.ts +2 -2
  27. package/dist/fetch.js +1 -15
  28. package/dist/formatting.d.ts +3 -3
  29. package/dist/mcp.d.ts +2 -2
  30. package/dist/mcp.js +1 -1
  31. package/dist/package.js +1 -1
  32. package/dist/pwa.d.ts +5 -4
  33. package/dist/pwa.js +36 -5
  34. package/package.json +1 -1
  35. package/skills/softr-sdk/SKILL.md +1 -1
  36. package/skills/softr-sdk/ai/SKILL.md +1 -1
  37. package/skills/softr-sdk/auth/SKILL.md +1 -1
  38. package/skills/softr-sdk/charts-and-metrics/SKILL.md +1 -1
  39. package/skills/softr-sdk/current-user/SKILL.md +1 -1
  40. package/skills/softr-sdk/file-uploads/SKILL.md +1 -1
  41. package/skills/softr-sdk/formatting/SKILL.md +1 -1
  42. package/skills/softr-sdk/integrations/SKILL.md +1 -1
  43. package/skills/softr-sdk/mcp/SKILL.md +1 -1
  44. package/skills/softr-sdk/push-notifications/SKILL.md +1 -1
  45. package/skills/softr-sdk/pwa/SKILL.md +7 -7
  46. package/skills/softr-sdk/record-mutations/SKILL.md +1 -1
  47. package/skills/softr-sdk/record-queries/SKILL.md +1 -1
  48. package/skills/softr-sdk/region-visibility/SKILL.md +1 -1
  49. package/skills/softr-sdk/routes-and-visibility/SKILL.md +1 -1
  50. package/skills/softr-sdk/workflows/SKILL.md +1 -1
package/CHANGELOG.md CHANGED
@@ -1,10 +1,16 @@
1
1
  # @softr/sdk
2
2
 
3
- ## 1.0.1
3
+ ## 1.1.1
4
4
 
5
5
  ### Patch Changes
6
6
 
7
- - Send the visitor's IP, signed, with calls to the Softr platform, so apps can log users out when the country they use the app from changes.
7
+ - `SoftrPwaHead` now gives iOS the app's home screen name and launch screens, so an installed app opens on its splash screen instead of white and Add to Home Screen suggests the app's name, not the page title. An app already on an iPhone home screen picks this up only after it is removed and added again.
8
+
9
+ ## 1.1.0
10
+
11
+ ### Minor Changes
12
+
13
+ - `defineQuery` takes an optional `filter` with its `filterFields`. Every read of the query, with `ds.list`, `ds.get`, `chart` and `metric`, returns only the records that match the filter. A read returns only `fields`, not `filterFields`.
8
14
 
9
15
  ## 1.0.0
10
16
 
package/dist/action.d.ts CHANGED
@@ -1,4 +1,6 @@
1
1
  import { SoftrUserGroupId } from "./auth/user.js";
2
+ import { FilterCriteria } from "./datasource/filter.js";
3
+ import { EnforcedFilter } from "./datasource/enforced-filter.js";
2
4
 
3
5
  //#region src/action.d.ts
4
6
  type ActionOperation = "read" | "create" | "update" | "delete";
@@ -69,6 +71,10 @@ type DatasourceResource = {
69
71
  datasourceId: SoftrDatasourceId;
70
72
  operation: ActionOperation;
71
73
  fields?: Record<string, string>;
74
+ /** The fields that the filter reads, by alias. A read returns only `fields`. */
75
+ filterFields?: Record<string, string>;
76
+ /** The enforced filter, keyed by alias, with its tokens unresolved. */
77
+ filter?: FilterCriteria;
72
78
  };
73
79
  /**
74
80
  * A datasource-backed action (query or mutation). The `TShape` brand carries field and
@@ -85,11 +91,19 @@ type WriteDeclaration<TId extends string, TDatasource$1, TOperation$1, TFields$1
85
91
  fields: TFields$1;
86
92
  permissions: ActionPermissions;
87
93
  };
88
- type ReadDeclaration<TId extends string, TDatasource$1, TFields$1> = {
94
+ type ReadDeclaration<TId extends string, TDatasource$1 extends SoftrDatasourceId, TFields$1 extends Record<string, string>, TFilterFields extends Record<string, string>> = {
89
95
  id: TId;
90
96
  datasourceId: TDatasource$1;
91
97
  fields: TFields$1;
92
98
  permissions: ActionPermissions;
99
+ /** The fields that `filter` reads, by alias. A read returns only `fields`. */
100
+ filterFields?: TFilterFields;
101
+ filter?: EnforcedFilter<{
102
+ id: TId;
103
+ datasourceId: TDatasource$1;
104
+ operation: "read";
105
+ fields: NoInfer<TFilterFields>;
106
+ }>;
93
107
  };
94
108
  type DeleteDeclaration<TId extends string, TDatasource$1> = {
95
109
  id: TId;
@@ -103,6 +117,14 @@ type DeleteDeclaration<TId extends string, TDatasource$1> = {
103
117
  *
104
118
  * The argument must be a static object.
105
119
  *
120
+ * `filter` limits every read of the query to the rows that match it, and a `where` cannot widen
121
+ * it. Write a filter on the visitor with a user token. A condition on a user token matches no rows
122
+ * for a visitor who is signed out. A filter has at most 4 group levels.
123
+ *
124
+ * The keys of `filter` are aliases of `filterFields`. A read returns only `fields`, so a field
125
+ * that only the filter needs, such as the owner's email, stays hidden. A field that the read
126
+ * returns and the filter reads goes in both.
127
+ *
106
128
  * @example
107
129
  * const publishedPosts = defineQuery({
108
130
  * id: "publishedPosts",
@@ -115,8 +137,18 @@ type DeleteDeclaration<TId extends string, TDatasource$1> = {
115
137
  * .list(publishedPosts)
116
138
  * .where((q) => q.publishedAt.lte(today))
117
139
  * .orderBy((q) => q.publishedAt.desc)
140
+ *
141
+ * @example
142
+ * const myRequests = defineQuery({
143
+ * id: "myRequests",
144
+ * datasourceId: "8f14e45f-ceea-467a-9d0b-2c1a0e3b5d77",
145
+ * fields: { title: "V1StGXR8", dueAt: "Xp2dLh6v" },
146
+ * filterFields: { requesterEmail: "Z7pQm4Kd" },
147
+ * permissions: { userGroupTypes: ["LOGGED_IN_USERS"] },
148
+ * filter: { requesterEmail: { is: "{USER:::EMAIL}" }, dueAt: { gte: "FIXED_DATE:DAYS_AGO:7" } },
149
+ * })
118
150
  */
119
- declare function defineQuery<const TId extends string, const TDatasource$1 extends SoftrDatasourceId, const TFields$1 extends Record<string, ReadFieldIdOf<TDatasource$1>>>(definition: ReadDeclaration<TId, TDatasource$1, TFields$1>): DatasourceAction<{
151
+ declare function defineQuery<const TId extends string, const TDatasource$1 extends SoftrDatasourceId, const TFields$1 extends Record<string, ReadFieldIdOf<TDatasource$1>>, const TFilterFields extends Record<string, ReadFieldIdOf<TDatasource$1>> = Record<never, never>>(definition: ReadDeclaration<TId, TDatasource$1, TFields$1, TFilterFields>): DatasourceAction<{
120
152
  id: TId;
121
153
  datasourceId: TDatasource$1;
122
154
  operation: "read";
package/dist/action.js CHANGED
@@ -1,12 +1,19 @@
1
+ import { assert } from "./assertions.js";
2
+ import { buildEnforcedFilter } from "./datasource/enforced-filter.js";
3
+
1
4
  //#region src/action.ts
2
5
  function defineQuery(definition) {
6
+ const { id, filterFields, filter } = definition;
7
+ assert(filter === void 0 === (filterFields === void 0), () => `defineQuery "${id}": declare filter and filterFields together. The filter names aliases of filterFields.`);
3
8
  return {
4
- id: definition.id,
9
+ id,
5
10
  resource: {
6
11
  type: "DATASOURCE",
7
12
  datasourceId: definition.datasourceId,
8
13
  operation: "read",
9
- fields: definition.fields
14
+ fields: definition.fields,
15
+ filterFields,
16
+ filter: filter === void 0 ? void 0 : buildEnforcedFilter(filter, Object.keys(filterFields ?? {}))
10
17
  },
11
18
  permissions: definition.permissions
12
19
  };
@@ -0,0 +1,13 @@
1
+ import { assert } from "../assertions.js";
2
+ import { getGlobalStartContext } from "@tanstack/react-start";
3
+
4
+ //#region src/auth/context.ts
5
+ /** The context that `softrAuthMiddleware` resolved for this request. Server only. */
6
+ function readSoftrContext() {
7
+ const context = getGlobalStartContext();
8
+ assert(typeof context === "object" && context !== null && "user" in context && "permissions" in context && "formatting" in context, "softrAuthMiddleware has not run: the Start global context carries no session. Register it as a global request middleware, e.g. createStart(() => ({ requestMiddleware: [softrAuthMiddleware()] })).");
9
+ return context;
10
+ }
11
+
12
+ //#endregion
13
+ export { readSoftrContext };
@@ -1,9 +1,9 @@
1
1
  import { User } from "./user.js";
2
2
  import { Formatting } from "../formatting.js";
3
3
  import { SoftrContext } from "./context.js";
4
- import * as react0 from "react";
4
+ import * as react6 from "react";
5
5
  import { ReactNode } from "react";
6
- import * as _tanstack_react_start0 from "@tanstack/react-start";
6
+ import * as _tanstack_react_start2 from "@tanstack/react-start";
7
7
 
8
8
  //#region src/auth/isomorphic.d.ts
9
9
 
@@ -21,7 +21,7 @@ import * as _tanstack_react_start0 from "@tanstack/react-start";
21
21
  * requestMiddleware: [softrAuthMiddleware()],
22
22
  * }))
23
23
  */
24
- declare function softrAuthMiddleware(): _tanstack_react_start0.RequestMiddlewareAfterServer<{}, readonly [_tanstack_react_start0.RequestMiddlewareAfterServer<{}, undefined, undefined>, _tanstack_react_start0.RequestMiddlewareAfterServer<{}, undefined, undefined>, _tanstack_react_start0.RequestMiddlewareAfterServer<{}, undefined, undefined>, _tanstack_react_start0.RequestMiddlewareAfterServer<{}, undefined, undefined>, _tanstack_react_start0.RequestMiddlewareAfterServer<{}, undefined, undefined>, _tanstack_react_start0.RequestMiddlewareAfterServer<{}, undefined, undefined>], {
24
+ declare function softrAuthMiddleware(): _tanstack_react_start2.RequestMiddlewareAfterServer<{}, readonly [_tanstack_react_start2.RequestMiddlewareAfterServer<{}, undefined, undefined>, _tanstack_react_start2.RequestMiddlewareAfterServer<{}, undefined, undefined>, _tanstack_react_start2.RequestMiddlewareAfterServer<{}, undefined, undefined>, _tanstack_react_start2.RequestMiddlewareAfterServer<{}, undefined, undefined>, _tanstack_react_start2.RequestMiddlewareAfterServer<{}, undefined, undefined>, _tanstack_react_start2.RequestMiddlewareAfterServer<{}, undefined, undefined>], {
25
25
  user: User | null;
26
26
  permissions: {
27
27
  datasources: {};
@@ -37,7 +37,7 @@ declare function softrAuthMiddleware(): _tanstack_react_start0.RequestMiddleware
37
37
  * beforeLoad: async () => await getSoftrContext(),
38
38
  * })
39
39
  */
40
- declare const getSoftrContext: _tanstack_react_start0.OptionalFetcher<undefined, undefined, Promise<SoftrContext>>;
40
+ declare const getSoftrContext: _tanstack_react_start2.OptionalFetcher<undefined, undefined, Promise<SoftrContext>>;
41
41
  /**
42
42
  * The context to hand `createRouter`, before any request has resolved one.
43
43
  *
@@ -85,7 +85,7 @@ type AuthOptions = {
85
85
  * staleTime: 60_000,
86
86
  * })
87
87
  */
88
- declare const getAuthSettings: _tanstack_react_start0.OptionalFetcher<undefined, undefined, Promise<AuthOptions>>;
88
+ declare const getAuthSettings: _tanstack_react_start2.OptionalFetcher<undefined, undefined, Promise<AuthOptions>>;
89
89
  /**
90
90
  * Makes the auth options readable with {@link useAuthSettings} anywhere below.
91
91
  *
@@ -105,7 +105,7 @@ declare function AuthSettingsProvider({
105
105
  }: {
106
106
  value: AuthOptions;
107
107
  children?: ReactNode;
108
- }): react0.JSX.Element;
108
+ }): react6.JSX.Element;
109
109
  /**
110
110
  * Which ways in this app offers. Requires an {@link AuthSettingsProvider}
111
111
  * above it.
@@ -1,10 +1,11 @@
1
- import { assert, panic, requireDefined } from "../assertions.js";
1
+ import { panic, requireDefined } from "../assertions.js";
2
2
  import { readUserTimezone, writeCookies } from "../cookies.js";
3
3
  import { sessionConfig } from "./config.js";
4
+ import { makePlatform } from "./platform.js";
4
5
  import { clearSession, makeSessionDataCookie, readSessionData, readSessionToken } from "./session.js";
6
+ import { readSoftrContext } from "./context.js";
5
7
  import { defaultFormatting, resolveFormatting } from "../formatting.js";
6
8
  import { readLocaleSettings } from "../locale-settings.js";
7
- import { makePlatform } from "./platform.js";
8
9
  import { settings } from "./methods/settings.js";
9
10
  import { bootErrorMiddleware } from "../boot-error.js";
10
11
  import { pwaMiddleware } from "../pwa.js";
@@ -12,9 +13,9 @@ import { pushMiddleware } from "../push.js";
12
13
  import { faviconMiddleware } from "../favicon.js";
13
14
  import { embeddingMiddleware } from "../embedding.js";
14
15
  import { appIdentityMiddleware } from "../app-identity.js";
15
- import { getRequestHeader } from "@tanstack/react-start/server";
16
16
  import { createContext, useContext } from "react";
17
- import { createMiddleware, createServerFn, getGlobalStartContext } from "@tanstack/react-start";
17
+ import { createMiddleware, createServerFn } from "@tanstack/react-start";
18
+ import { getRequestHeader } from "@tanstack/react-start/server";
18
19
  import { rootRouteId, useRouteContext } from "@tanstack/react-router";
19
20
  import { jsx } from "react/jsx-runtime";
20
21
 
@@ -76,11 +77,7 @@ function softrAuthMiddleware() {
76
77
  * beforeLoad: async () => await getSoftrContext(),
77
78
  * })
78
79
  */
79
- const getSoftrContext = createServerFn({ method: "GET" }).handler(async () => {
80
- const context = getGlobalStartContext();
81
- assert(typeof context === "object" && context !== null && "user" in context && "permissions" in context && "formatting" in context, "softrAuthMiddleware has not run: the Start global context carries no session. Register it as a global request middleware, e.g. createStart(() => ({ requestMiddleware: [softrAuthMiddleware()] })).");
82
- return context;
83
- });
80
+ const getSoftrContext = createServerFn({ method: "GET" }).handler(async () => readSoftrContext());
84
81
  /**
85
82
  * The context to hand `createRouter`, before any request has resolved one.
86
83
  *
@@ -1,8 +1,8 @@
1
1
  import { assert, panic } from "../../assertions.js";
2
2
  import { writeCookies } from "../../cookies.js";
3
3
  import { sessionConfig } from "../config.js";
4
- import { clearPendingAuth, makeSessionDataCookie, makeSessionTokenCookie, readPendingAuthToken, readSessionToken } from "../session.js";
5
4
  import { makePlatform } from "../platform.js";
5
+ import { clearPendingAuth, makeSessionDataCookie, makeSessionTokenCookie, readPendingAuthToken, readSessionToken } from "../session.js";
6
6
  import { authError } from "./utils.js";
7
7
 
8
8
  //#region src/auth/methods/authenticator.ts
@@ -1,8 +1,8 @@
1
1
  import { assert, panic } from "../../assertions.js";
2
2
  import { writeCookies } from "../../cookies.js";
3
3
  import { sessionConfig } from "../config.js";
4
- import { clearPendingAuth, makePendingAuthCookie, makeSessionDataCookie, makeSessionTokenCookie } from "../session.js";
5
4
  import { makePlatform } from "../platform.js";
5
+ import { clearPendingAuth, makePendingAuthCookie, makeSessionDataCookie, makeSessionTokenCookie } from "../session.js";
6
6
  import { authError } from "./utils.js";
7
7
 
8
8
  //#region src/auth/methods/code.ts
@@ -1,8 +1,8 @@
1
1
  import { assert, panic } from "../../assertions.js";
2
2
  import { writeCookies } from "../../cookies.js";
3
3
  import { sessionConfig } from "../config.js";
4
- import { clearPendingAuth, makePendingAuthCookie, makeSessionDataCookie, makeSessionTokenCookie, readPendingAuthToken } from "../session.js";
5
4
  import { makePlatform } from "../platform.js";
5
+ import { clearPendingAuth, makePendingAuthCookie, makeSessionDataCookie, makeSessionTokenCookie, readPendingAuthToken } from "../session.js";
6
6
  import { authError } from "./utils.js";
7
7
 
8
8
  //#region src/auth/methods/emailCode2fa.ts
@@ -1,8 +1,8 @@
1
1
  import { assert, panic } from "../../assertions.js";
2
2
  import { writeCookies } from "../../cookies.js";
3
3
  import { sessionConfig } from "../config.js";
4
- import { makePendingAuthCookie, makeSessionDataCookie, makeSessionTokenCookie } from "../session.js";
5
4
  import { makePlatform } from "../platform.js";
5
+ import { makePendingAuthCookie, makeSessionDataCookie, makeSessionTokenCookie } from "../session.js";
6
6
  import { authError } from "./utils.js";
7
7
 
8
8
  //#region src/auth/methods/magicLink.ts
@@ -1,8 +1,8 @@
1
1
  import { assert, panic, softAssert } from "../../assertions.js";
2
2
  import { writeCookies } from "../../cookies.js";
3
3
  import { sessionConfig } from "../config.js";
4
- import { clearPendingAuth, clearSession, makePendingAuthCookie, makeSessionDataCookie, makeSessionTokenCookie, readSessionToken } from "../session.js";
5
4
  import { makePlatform } from "../platform.js";
5
+ import { clearPendingAuth, clearSession, makePendingAuthCookie, makeSessionDataCookie, makeSessionTokenCookie, readSessionToken } from "../session.js";
6
6
  import { authError } from "./utils.js";
7
7
 
8
8
  //#region src/auth/methods/password.ts
@@ -1,8 +1,8 @@
1
1
  import { assert, panic } from "../../assertions.js";
2
2
  import { writeCookies } from "../../cookies.js";
3
3
  import { sessionConfig } from "../config.js";
4
- import { clearPendingAuth, makePendingAuthCookie, makeSessionDataCookie, makeSessionTokenCookie } from "../session.js";
5
4
  import { makePlatform } from "../platform.js";
5
+ import { clearPendingAuth, makePendingAuthCookie, makeSessionDataCookie, makeSessionTokenCookie } from "../session.js";
6
6
  import { authError } from "./utils.js";
7
7
 
8
8
  //#region src/auth/methods/passwordLink.ts
@@ -1,7 +1,7 @@
1
1
  import { assert, panic } from "../../assertions.js";
2
2
  import { sessionConfig } from "../config.js";
3
- import { clearSessionData, readSessionToken } from "../session.js";
4
3
  import { makePlatform } from "../platform.js";
4
+ import { clearSessionData, readSessionToken } from "../session.js";
5
5
  import { authError } from "./utils.js";
6
6
 
7
7
  //#region src/auth/methods/profile.ts
@@ -1,8 +1,8 @@
1
1
  import { assert, panic } from "../../assertions.js";
2
2
  import { writeCookies } from "../../cookies.js";
3
3
  import { sessionConfig } from "../config.js";
4
- import { clearPendingAuth, makePendingAuthCookie, makeSessionDataCookie, makeSessionTokenCookie } from "../session.js";
5
4
  import { makePlatform } from "../platform.js";
5
+ import { clearPendingAuth, makePendingAuthCookie, makeSessionDataCookie, makeSessionTokenCookie } from "../session.js";
6
6
  import { authError } from "./utils.js";
7
7
 
8
8
  //#region src/auth/methods/signup.ts
@@ -1,8 +1,8 @@
1
1
  import { assert, panic } from "../../assertions.js";
2
2
  import { writeCookies } from "../../cookies.js";
3
3
  import { sessionConfig } from "../config.js";
4
- import { clearPendingAuth, makePendingAuthCookie, makeSessionDataCookie, makeSessionTokenCookie } from "../session.js";
5
4
  import { makePlatform } from "../platform.js";
5
+ import { clearPendingAuth, makePendingAuthCookie, makeSessionDataCookie, makeSessionTokenCookie } from "../session.js";
6
6
  import { authError } from "./utils.js";
7
7
 
8
8
  //#region src/auth/methods/social.ts
@@ -1,10 +1,12 @@
1
+ import { panic } from "../assertions.js";
1
2
  import { expireCookie, expireOtherCopy, readRequestCookies, serializeCookie, writeCookies } from "../cookies.js";
2
3
  import { sessionConfig } from "./config.js";
4
+ import { makePlatform } from "./platform.js";
3
5
  import { userSchema } from "./user.js";
4
- import { getRequestProtocol } from "@tanstack/react-start/server";
5
6
  import { z } from "zod";
6
7
  import { createCipheriv, createDecipheriv, createHash, randomBytes } from "node:crypto";
7
8
  import { AsyncLocalStorage } from "node:async_hooks";
9
+ import { getRequestProtocol } from "@tanstack/react-start/server";
8
10
 
9
11
  //#region src/auth/session.ts
10
12
  const SESSION_TOKEN = "session_token";
@@ -43,12 +45,23 @@ function sessionCookie(base) {
43
45
  * call authenticates with a bearer token and has no cookie at all.
44
46
  */
45
47
  function withSessionToken(token, fn) {
46
- return standInToken.run(token, fn);
48
+ return standIn.run({ token }, fn);
49
+ }
50
+ /**
51
+ * The visitor of the token that {@link withSessionToken} stands in, fetched once
52
+ * per scope. `undefined` outside one, where the request middleware has already
53
+ * resolved the visitor.
54
+ */
55
+ function readStandInUser() {
56
+ const scope = standIn.getStore();
57
+ if (scope === void 0) return void 0;
58
+ scope.user ??= makePlatform(sessionConfig().applicationId).session(scope.token).then((result) => result.ok ? result.data.user : panic(result.message));
59
+ return scope.user;
47
60
  }
48
61
  /** The platform token this request carries, or `null`. */
49
62
  function readSessionToken() {
50
- const standIn = standInToken.getStore();
51
- if (standIn !== void 0) return standIn;
63
+ const scope = standIn.getStore();
64
+ if (scope !== void 0) return scope.token;
52
65
  const { name } = sessionCookie(SESSION_TOKEN);
53
66
  return openEnvelope(readRequestCookies()[name], SESSION_TOKEN);
54
67
  }
@@ -127,7 +140,7 @@ function clearSession() {
127
140
  function clearSessionData() {
128
141
  clearCookies([SESSION_DATA]);
129
142
  }
130
- const standInToken = new AsyncLocalStorage();
143
+ const standIn = new AsyncLocalStorage();
131
144
  const sessionDataSchema = z.object({
132
145
  user: userSchema.nullable(),
133
146
  exp: z.number(),
@@ -215,4 +228,4 @@ function openEnvelope(raw, purpose) {
215
228
  }
216
229
 
217
230
  //#endregion
218
- export { clearPendingAuth, clearSession, clearSessionData, makePendingAuthCookie, makeSessionDataCookie, makeSessionTokenCookie, readPendingAuthToken, readSessionData, readSessionToken, withSessionToken };
231
+ export { clearPendingAuth, clearSession, clearSessionData, makePendingAuthCookie, makeSessionDataCookie, makeSessionTokenCookie, readPendingAuthToken, readSessionData, readSessionToken, readStandInUser, withSessionToken };
@@ -1,6 +1,6 @@
1
- import { DatasourceAction, FieldTypeOf, ReadShape, SoftrDatasources } from "../action.js";
2
1
  import { ConstructableOrderBy } from "./filter.js";
3
2
  import { DateFieldType, NumberFieldType, SortSet } from "./fields.js";
3
+ import { DatasourceAction, FieldTypeOf, ReadShape, SoftrDatasources } from "../action.js";
4
4
  import { WhereCallback } from "./record.js";
5
5
 
6
6
  //#region src/datasource/chart.d.ts
@@ -2,9 +2,9 @@ import { assert, panic } from "../assertions.js";
2
2
  import { fetch } from "../fetch.js";
3
3
  import { readUserTimezone } from "../cookies.js";
4
4
  import { readSessionToken } from "../auth/session.js";
5
- import { INTERNAL_KIND, buildFilterCriteria, buildOrderBy, dealiasFilterCriteria } from "./filter.js";
6
- import { andAll, makeFieldSet, makeSortSet } from "./fields.js";
7
- import { describeFailure, dsUrl, refererHeader, resolveTarget } from "./record.js";
5
+ import { INTERNAL_KIND, buildOrderBy } from "./filter.js";
6
+ import { makeFieldSet, makeSortSet } from "./fields.js";
7
+ import { describeFailure, dsUrl, readFilterCriteria, refererHeader, resolveTarget } from "./record.js";
8
8
 
9
9
  //#region src/datasource/chart.ts
10
10
  const COUNT_CNT = "COUNT_CNT";
@@ -137,7 +137,7 @@ function chart(query) {
137
137
  };
138
138
  return builder;
139
139
  }
140
- function buildChartRequest(state, select) {
140
+ function buildChartRequest(state, select, filterCriteria) {
141
141
  const groups = state.groups;
142
142
  assert(groups && groups.length > 0, "a chart needs at least one column to group by");
143
143
  const metrics = state.metrics ?? [];
@@ -161,14 +161,13 @@ function buildChartRequest(state, select) {
161
161
  }];
162
162
  }
163
163
  const responseKeyOf = new Map(columns.map((column) => [column.key, column.responseKey]));
164
- const sortingOptions = orderBys.map((orderBy) => ({
165
- sortingField: responseKeyOf.get(orderBy.sortingField) ?? panic(() => `"${orderBy.sortingField}" is not a column of this chart`),
166
- sortType: orderBy.sortType
167
- }));
168
164
  return {
169
165
  body: {
170
- filterCriteria: toFilterCriteria(state.filters, select),
171
- sortingOptions,
166
+ filterCriteria,
167
+ sortingOptions: orderBys.map((orderBy) => ({
168
+ sortingField: responseKeyOf.get(orderBy.sortingField) ?? panic(() => `"${orderBy.sortingField}" is not a column of this chart`),
169
+ sortType: orderBy.sortType
170
+ })),
172
171
  groupBy: groups.map(([, handle]) => handle.options ? {
173
172
  field: handle.fieldId,
174
173
  options: handle.options
@@ -192,8 +191,14 @@ function mapChartRows(columns, data) {
192
191
  });
193
192
  }
194
193
  async function executeChart(query, state) {
195
- const { actionId, select } = resolveTarget(query, "read");
196
- const { body, columns } = buildChartRequest(state, select);
194
+ const target = resolveTarget(query, "read");
195
+ const { actionId, select } = target;
196
+ const filterCriteria = await readFilterCriteria(target, state.filters);
197
+ if (filterCriteria === null) return {
198
+ data: [],
199
+ executionTimestamp: /* @__PURE__ */ new Date()
200
+ };
201
+ const { body, columns } = buildChartRequest(state, select, filterCriteria);
197
202
  const res = await fetch(`${dsUrl(actionId)}/chart/data`, {
198
203
  method: "POST",
199
204
  headers: {
@@ -247,7 +252,7 @@ function metric(query, pick) {
247
252
  };
248
253
  return builder;
249
254
  }
250
- function buildMetricRequest(handle, filters, select) {
255
+ function buildMetricRequest(handle, filterCriteria) {
251
256
  return {
252
257
  body: {
253
258
  groupBy: [],
@@ -255,7 +260,7 @@ function buildMetricRequest(handle, filters, select) {
255
260
  field: handle.fieldId ?? void 0,
256
261
  aggregation: handle.aggregation
257
262
  }],
258
- filterCriteria: toFilterCriteria(filters, select)
263
+ filterCriteria
259
264
  },
260
265
  responseKey: handle.aggregation === "COUNT" && !handle.fieldId ? COUNT_CNT : handle.fieldId
261
266
  };
@@ -266,8 +271,14 @@ function readMetricValue(responseKey, data) {
266
271
  return row[responseKey];
267
272
  }
268
273
  async function executeMetric(query, handle, filters) {
269
- const { actionId, select } = resolveTarget(query, "read");
270
- const { body, responseKey } = buildMetricRequest(handle, filters, select);
274
+ const target = resolveTarget(query, "read");
275
+ const filterCriteria = await readFilterCriteria(target, filters);
276
+ if (filterCriteria === null) return {
277
+ value: handle.aggregation === "COUNT" || handle.aggregation === "DISTINCT" ? 0 : null,
278
+ executionTimestamp: /* @__PURE__ */ new Date()
279
+ };
280
+ const { actionId } = target;
281
+ const { body, responseKey } = buildMetricRequest(handle, filterCriteria);
271
282
  const res = await fetch(`${dsUrl(actionId)}/chart/data`, {
272
283
  method: "POST",
273
284
  headers: {
@@ -285,9 +296,6 @@ async function executeMetric(query, handle, filters) {
285
296
  executionTimestamp: /* @__PURE__ */ new Date(payload.executionTimestamp * 1e3)
286
297
  };
287
298
  }
288
- function toFilterCriteria(filters, select) {
289
- return filters.length ? dealiasFilterCriteria(buildFilterCriteria(andAll(filters)), select) : {};
290
- }
291
299
 
292
300
  //#endregion
293
301
  export { chart, metric };
@@ -0,0 +1,56 @@
1
+ import { AnyChain, ChainFor } from "./fields.js";
2
+ import { FieldTypeOf, ReadOf, ReadShape, SoftrDatasources } from "../action.js";
3
+
4
+ //#region src/datasource/enforced-filter.d.ts
5
+
6
+ /**
7
+ * The operators of one alias, each written as the value its `where` method takes. An operator
8
+ * with no value takes `true`, and a range takes a pair.
9
+ */
10
+ type Conditions<TChain> = { [Operator in keyof TChain]?: TChain[Operator] extends ((...args: infer TArgs) => unknown) ? TArgs extends [] ? true : TArgs extends [infer TValue] ? TValue : TArgs extends [infer TStart, infer TEnd] ? [TStart, TEnd] : never : never };
11
+ type Junctions<TShape extends ReadShape> = {
12
+ $and?: Array<EnforcedFilter<TShape>>;
13
+ $or?: Array<EnforcedFilter<TShape>>;
14
+ };
15
+ /**
16
+ * The filter a query enforces on every read. Each key is an alias of the query's `filterFields`,
17
+ * with the same operators as `where`. `$and` and `$or` nest more filters. The keys of one object
18
+ * combine with AND.
19
+ *
20
+ * A read returns `fields`, not `filterFields`. So a field that the visitor must not see can be in
21
+ * `filterFields` only. The datasource refuses a read that filters on a field a data restriction
22
+ * hides, even when it hides the field on some records only.
23
+ *
24
+ * A token stands for a value of the visitor or for a day. Write it in the form that the Studio
25
+ * condition builder stores:
26
+ * - `{USER:::EMAIL}` and `{USER:::EMAIL_DOMAIN}`: the visitor's email and its domain.
27
+ * - `USER:::<field id>`: a field of the visitor's row in the users table. softr.json must declare
28
+ * it under `user.properties`. For the id of that row, declare a Record ID field.
29
+ * - `PREDEFINED:TODAY`, `PREDEFINED:YESTERDAY`, `PREDEFINED:TOMORROW`,
30
+ * `FIXED_DATE:DAYS_AGO:<n>` and `FIXED_DATE:DAYS_FROM_NOW:<n>`: a day relative to today.
31
+ *
32
+ * The datasource resolves the tokens on each read. It resolves a day in the app's time zone. A
33
+ * condition on a user token matches no rows for a visitor who is signed out or has no value for
34
+ * it. In an `$or`, the other branches still match.
35
+ *
36
+ * Compare a field of the visitor that can hold several values, such as a link to their teams,
37
+ * with `isOneOf`. With a scalar `is`, a visitor who holds more than one value reads no rows.
38
+ *
39
+ * @example
40
+ * // "7fMhE" is a Record ID field of the users table, declared under `user.properties`.
41
+ * filter: { assignee: { isOneOf: ["USER:::7fMhE"] } }
42
+ *
43
+ * @example
44
+ * // `requesterEmail` is in `filterFields`, so public rows do not show it.
45
+ * filter: {
46
+ * $or: [
47
+ * { requesterEmail: { is: "{USER:::EMAIL}" } },
48
+ * { visibility: { is: "public" }, publishedAt: { lte: "PREDEFINED:TODAY" } },
49
+ * ],
50
+ * }
51
+ */
52
+ type EnforcedFilter<TShape extends ReadShape> = keyof SoftrDatasources extends never ? {
53
+ [key: string]: Conditions<AnyChain> | Array<EnforcedFilter<TShape>>;
54
+ } : { [Alias in keyof TShape["fields"]]?: Conditions<ChainFor<FieldTypeOf<TShape["datasourceId"], TShape["fields"][Alias]>, NonNullable<ReadOf<TShape["datasourceId"]>[TShape["fields"][Alias] & keyof ReadOf<TShape["datasourceId"]>]>>> } & Junctions<TShape>;
55
+ //#endregion
56
+ export { EnforcedFilter };